var Nearme = {
	country: null,
	countryName: null,
	latitude: 0,
	longitude: 0,
	byIP: true,
	categories: {},
	pois: {},
	translation: {},
	map: null,
	marker: null,
	geocoder: null,
	setCountry: null,
	setCountryName: null,
	allowSave: true,
	marker2: null,
	
	initMap: function() {
		this.map = new google.maps.Map(document.getElementById('map'), {mapTypeId: google.maps.MapTypeId.ROADMAP});
		this.marker = new google.maps.Marker({
			map: this.map,
			draggable: true
		});
		google.maps.event.addListener(this.marker, 'dragend', function() {
			Nearme.setLocation(Nearme.marker.getPosition());
		});

		google.maps.event.addListener(this.map, 'click', function(event) {
			//Nearme.marker2.setMap(null);
			Nearme.marker.setPosition(event.latLng);
			Nearme.setLocation(event.latLng);
			
		});
		
		
		this.geocoder = new google.maps.Geocoder();
	},
	
	showMap: function() {
			if (null == this.fallback) {
				Nearme.map.setCenter(new google.maps.LatLng(80, -30));
				Nearme.map.setZoom(2);
			} else {
				this.geocoder.geocode(
					{address: this.fallback},
					function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							Nearme.map.setCenter(results[0].geometry.location);
							Nearme.map.fitBounds(results[0].geometry.viewport);
							Nearme.marker.setPosition(results[0].geometry.location);
						} else {
							Nearme.map.setCenter(new google.maps.LatLng(0, 20));
							Nearme.map.setZoom(2);
						}
					}
				);
			}
			$('#map').hide();
			google.maps.event.trigger(this.map, 'resize'); 
	},
	
	setLocation: function(location) {
		$('#coordinates').val(location.lat() + ';' + location.lng());
		this.latitude = location.lat();
		this.longitude = location.lng();
	},
	
	confirmLocation: function() {
		Nearme.showHideMap();
		$('#confirm').hide();
		$.post('/user/confirm-location', {
			lat: Nearme.latitude,
			lng: Nearme.longitude
		}, function(data) {
			
		}, 'json');
	},
	
	setIpLocation: function(lat, long) {
		$('#coordinates').val(lat + ';' + long);
		coords = new google.maps.LatLng(lat,long);
		Nearme.marker.setPosition(coords);
		/*Nearme.marker2 = new google.maps.Marker({
	        position: latlng, 
	        map: Nearme.map
	    }); */ 
	},
	
	showHideMap: function() {
		if ($('#map').css('display') == 'none') {
			$('#map').show();
			$('#confirm').show();
		} else {
			$('#map').hide();
			$('#confirm').hide();
		}
		google.maps.event.trigger(this.map, 'resize'); 
	}
};

var poi = {
		id: null,
		category: null,
		longitude: null,
		latitude: null,
		map: null,
		criteria: {},
		average: 0,
		keys: [],
		poiName: null,
		
		initMap: function() {
			this.map = new google.maps.Map(document.getElementById('poi_map'), {mapTypeId: google.maps.MapTypeId.ROADMAP});
			this.geocoder = new google.maps.Geocoder();
			
			if (this.latitude != null) {
				var marker = new google.maps.Marker({
		              map: poi.map, 
		              position: new google.maps.LatLng(this.latitude, this.longitude)
		          });
				poi.map.setCenter(new google.maps.LatLng(this.latitude, this.longitude));
				poi.map.setZoom(13);
				poi.center = poi.map.getCenter();
				poi.zoom = 2;
			}
			
			/*if(this.geocoder) {
				this.geocoder.geocode(
					{latLng: new google.maps.LatLng(this.latitude, this.longitude)},
					function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							poi.map.setCenter(results[0].geometry.location);
							poi.map.fitBounds(results[0].geometry.viewport);
							//Võibolla kaardi suurus hiljem muutub ja järgnev rida pole enam vajalik.
							poi.map.setZoom(poi.map.getZoom() + 1);
							var marker = new google.maps.Marker({
					              map: poi.map, 
					              position: results[0].geometry.location
					          });
						} else {
							poi.map.setCenter(new google.maps.LatLng(0, 20));
							poi.map.setZoom(2);
						}
						poi.center = poi.map.getCenter();
						poi.zoom = poi.map.getZoom();
					}
				);*/
			 else {
				poi.map.setCenter(new google.maps.LatLng(0, 20));
				poi.map.setZoom(2);
				poi.center = poi.map.getCenter();
				poi.zoom = 2;
			}
		}
		
		
	};

var profile = {
		map: null,
		marker: null,
		initialLocation: null,
		id: null,
		firstName: null,
		lastName: null,
		email: null,
		hasPosition: false,
		latitude: null,
		longitude: null,
		
		init: function() {
			this.initMap();
			//this.initPosition();
			this.hideAll();
		},
		
		initMap: function() {
			var latlng = new google.maps.LatLng(this.latitude, this.longitude);
			var myOptions = {
				    zoom: 14,
				    center: latlng,
				    mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			this.map = new google.maps.Map(document.getElementById("profileMap"), myOptions);
			this.marker = new google.maps.Marker({
							map: this.map,
							draggable: true
						});
			
			google.maps.event.addListener(this.marker, 'dragend', function() {
				profile.setLocation(profile.marker.getPosition());
			});

			google.maps.event.addListener(this.map, 'click', function(event) {
				profile.marker.setPosition(event.latLng);
				profile.setLocation(event.latLng);
				
			});
			this.marker.setPosition(latlng);
		},
		
		setLocation: function(location) {
			this.latitude = location.lat();
			this.longitude = location.lng();
		},
		
		confirmLocation: function() {
			$.post('/user/confirm-location', {
				lat: profile.latitude,
				lng: profile.longitude
			}, function(data) {
				
			}, 'json');
		},
		
		showProfileChange: function() {
			$('#changeprofilebutton').hide();
			$('#newfirstname').val(this.firstName);
			$('#newlastname').val(this.lastName);
			$('#newemail').val(this.email);
			$('#changeprofilecontainer').show();
		},
		
		changeProfile: function() {
			var firstname = jQuery.trim($('#newfirstname').val());
			var lastname = jQuery.trim($('#newlastname').val());
			var email = jQuery.trim($('#newemail').val());
			if (firstname == '') {
				alert(this.translation.poi_Error_Name);
			} else {
				this.hideAll();
				$.post('/profile/change', {
					id: this.id,
					firstname: firstname,
					lastname: lastname,
					email: email
				}, function(data) {
					if (null != data.name) {
						profile.firstName = data.firstname;
						profile.lastName = data.lastname;
						profile.email = data.email;
					}
				}, 'json');
			}
		},
		
		hideAll: function() {
			if ($('#changeprofilecontainer').is(':visible')) {
				$('#changeprofilecontainer').hide();
				$('#changeprofilebutton').show();
			}
		}
		
};

var myMap = {
		map: null,
		marker: null,
		
		initialize: function() {
		    var latlng = new google.maps.LatLng(67, 24);
		    var myOptions = {
		      zoom: 5,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    
		    this.map = new google.maps.Map(document.getElementById("map_canvas"),
		        myOptions);
		    
		    this.marker = new google.maps.Marker({
				map: this.map,
				draggable: true
			});
		    
		    this.marker.setPosition(latlng);
		    
			google.maps.event.addListener(this.marker, 'dragend', function() {
				myMap.setLocation(this.marker.getPosition());
			});

			google.maps.event.addListener(this.map, 'click', function(event) {
				myMap.marker.setPosition(event.latLng);
				myMap.setLocation(event.latLng);
				
			});
			
			
			this.geocoder = new google.maps.Geocoder();
		    
		  },
		  
			setLocation: function(location) {
				if(this.geocoder) {
					this.geocoder.geocode(
						{latLng: location},
						function(results, status) {
							if (status == google.maps.GeocoderStatus.OK) {
								if (results[0]) {
									$('#address').val(results[0].formatted_address);
								}
								for(i=0;results[0].address_components.length;i++) {
									if(results[0].address_components[i].types[0] == "country") {
										$('#country').val(results[0].address_components[i].short_name);
										break;
									}
										
								}
							}
						}
					);
					
				}
				$('#latitude').val(location.lat());
				$('#longitude').val(location.lng());
			}
};

var Places = {
	
	init: function() {
		
	},
	
	getCountries: function(continentId) {
		$.ajax({
			  url: '/travelinfo/countries/continent/' + continentId,
			  dataType: 'json',
			  success: function(data) {
			    var html = '<div class="valiku_tulp">';
			    j = 0;
				for (var i in data) {
			    	html += '<span><a href="javascript:;" onclick="Places.getCategories(\''+data[i].country+'\', '+continentId+')">' + data[i].country_name + '</a></span>';
			    	if (j == Math.floor(data.length/3)) {
			    		html += '</div><div class="valiku_tulp">';
			    		j = 0;
			    	}
			    	j++;
				}
				html += '</div>';
				$('#countries').html(html);
			  }
			});
	},
	
	getCategories: function(countryId, continentId) {
		$.get('/travelinfo/country-info/country/' + countryId, function(data) {
			  $('#countryInfo').html(data);
			});
		$.get('/travelinfo/wiki/country/' + countryId, function(data) {
			  $('#wiki').html(data);
			});
		$.ajax({
			  url: '/travelinfo/load-categories/country/' + countryId,
			  dataType: 'json',
			  success: function(data) {
			    var html = '<div class="valiku_tulp">';
			    j = 0;
				for (var i in data.categories) {
			    	html += '<span><a href="/travelinfo/load-pois/category/'+data.categories[i].id+'/country/'+countryId+'/continent/'+continentId+'">' + data.categories[i].name + '</a></span>';
			    	if (j == Math.floor(data.categories.length/3)) {
			    		html += '</div><div class="valiku_tulp">';
			    		j = 0;
			    	}
			    	j++;
				}
				html += '</div>';
				$('#categories').html(html);
			  }
			});
	}
};

var myPoi = {
		id: null,
		country: null,
		name: null,
		phone: null,
		mail: null,
		web: null,
		description: '',
		translation: {},
		isInTop: false,
		language: 'default',
		tipsLanguage: null,
		tips: {},
		selectedTip: null,
		attributesList: {},
		attributes: {},
		imagesPath: null,
		countryName: null,
		translation: {},
		geocoder: null,
		map: null,
		marker: null,
		latitude: null,
		longitude: null,
		
		init: function() {
			//this.showTopState();
			this.setDescription();
			this.buildAttributesList();
			this.buildPicturesList();
			this.buildTipsList();
			this.initMap();
			if(this.latitude == 0 && this.longitude == 0) {
				this.initPosition();
			}
			//this.hideAll();
		},
		
		initPosition: function() {
			if(navigator.geolocation) {
			    navigator.geolocation.getCurrentPosition(function(position) {
			      var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			      	myPoi.map.setCenter(initialLocation);
			      	myPoi.marker.setPosition(initialLocation);
			      	$('#latitude').val(initialLocation.lat());
					$('#longitude').val(initialLocation.lng());
			    }, function() {
			      alert("Asukohta ei leitud.");
			    });
			  } else {
			    alert("Asukohta ei leitud.");
			  }
		},
		
		initMap: function() {
		    var latlng = new google.maps.LatLng(this.latitude, this.longitude);
		    var myOptions = {
		      zoom: 10,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    
		    this.map = new google.maps.Map(document.getElementById("map_canvas"),
		        myOptions);
		    
		    this.marker = new google.maps.Marker({
				map: this.map,
				draggable: true
			});
		    
		    this.marker.setPosition(latlng);
		    this.setLocation(latlng);
		    
			google.maps.event.addListener(this.marker, 'dragend', function() {
				myPoi.setLocation(this.marker.getPosition());
			});
		
			google.maps.event.addListener(this.map, 'click', function(event) {
				myPoi.marker.setPosition(event.latLng);
				myPoi.setLocation(event.latLng);
				
			});
			
			this.geocoder = new google.maps.Geocoder();
		},
		
		
		  
		setLocation: function(location) {
			if(this.geocoder) {
				this.geocoder.geocode(
					{latLng: location},
					function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							if (results[0]) {
								$('#address').val(results[0].formatted_address);
							}
							for(i=0;results[0].address_components.length;i++) {
								if(results[0].address_components[i].types[0] == "country") {
									$('#country').val(results[0].address_components[i].short_name);
									break;
								}
									
							}
						}
					}
				);
				
			}
			$('#latitude').val(location.lat());
			$('#longitude').val(location.lng());
		},
		
		setTitle: function() {
			$('h2.poi_title').html(this.name);
		},
		
		showTiny: function() {
			tinyMCE.init({ 
			    theme : "simple", 
			    mode: "exact",
			    elements : "description", 

			   	//theme options
			    theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
			    theme_advanced_toolbar_location : "top",
			    theme_advanced_toolbar_align : "left",
			    theme_advanced_statusbar_location : "bottom",
			    theme_advanced_resizing : true

			   	
			}); 
		},
		
		showNameChange: function() {
			this.hideAll();
			$('#changenamebutton').hide();
			$('#newname').val(this.name);
			$('#newmail').val(this.mail);
			$('#newphone').val(this.phone);
			$('#newweb').val(this.web);
			$('#changenamecontainer').show();
		},
		
		showTopState: function() {
			var html = '';
			if (this.isInTop == true) {
				html += this.translation.poi_Label_Intop + ' ';
				html += '<a href="javascript:gpse.poi.toggleTopState()">' + this.translation.poi_Button_Removefromtop + '</a>';
			} else {
				html += this.translation.poi_Label_Notintop + ' ';
				html += '<a href="javascript:gpse.poi.toggleTopState()">' + this.translation.poi_Button_Addtotop + '</a>';
			}
			html += ' <a href="/poi/top/country/' + this.country + '">' + this.translation.poi_Button_Top + '</a>';
			$('#topstate').html(html);
		},
		
		toggleTopState: function() {
			$('#topstate').empty();
			$.post('/poi/toggle-top-state', {
				country: this.country,
				poi_id: this.id
			}, function(data) {
				if (data.isInTop == true) {
					gpse.poi.isInTop = true;
				} else {
					gpse.poi.isInTop = false;
				}
				gpse.poi.showTopState();
			}, 'json');
		},
		
		showAddAttribute: function() {
			this.hideAll();
			$('#addattributebutton').hide();
			this.buildAddList();
			$('#addattributescontainer').show();
		},
		
		hideAll: function() {
			if ($('#changenamecontainer').is(':visible')) {
				$('#changenamecontainer').hide();
				$('#changenamebutton').show();
			}
			if ($('#editdescriptioncontainer').is(':visible')) {
				$('#editdescriptioncontainer').hide();
				this.setDescription();
				$('#descriptioncontainer').show();
			}
			if ($('#addattributescontainer').is(':visible')) {
				$('#addattributescontainer').hide();
				$('#addattributebutton').show();
			}
			if ($('#addtipcontainer').is(':visible')) {
				$('#newtip').val('');
				$('#addtipcontainer').hide();
				$('#addtipbutton').show();
			}
			if (null != this.selectedTip) {
				var html = '<p>' + this.tips[this.selectedTip].text;
				html += '<br /><a href="javascript:myPoi.editTip(' + this.selectedTip + ')">' + this.translation.poi_Button_Edit;
				html += '</a> <a href="javascript:myPoi.deleteTip(' + this.tips[this.selectedTip].id + ')">' + this.translation.poi_Button_Delete;
				html += '</a></p>';
				var row = $('#tipslist').find('p').eq(this.selectedTip);
				row.replaceWith(html);
				this.selectedTip = null;
			}
		},
		
		buildAddList: function() {
			$('#addattributeslist').empty();
			var html = '';
			var row = null;
			for (row in this.attributesList) {
				if (true != this.attributes[row]) {
					html = '<a title="' + this.attributesList[row].description + '" class="attributeicon" ';
					html += 'href="javascript:myPoi.addAttribute(' + row;
					html += ')"><img src="' + this.imagesPath + this.attributesList[row].filename;
					html += '" alt="' + this.attributesList[row].description + '" /></a>';
					$('#addattributeslist').append(html);
				}
			}
		},
		
		buildAttributesList: function() {
			$('#attributeslist').empty();
			var html = '';
			var attribute = null;
			var row = null;
			for (row in this.attributes) {
					attribute = this.attributesList[row];
					html = '<div class="attributefloat"><img src="' + this.imagesPath + attribute.filename;
					html += '" alt="' + attribute.description;
					html += '" title="' + attribute.description;
					html += '" /><br /><a href="javascript:myPoi.deleteAttribute(' + row;
					html += ')">' + this.translation.poi_Button_Delete + '</a></div>';
					$('#attributeslist').append(html);
			}
		},
		
		addAttribute: function(id) {
			$.post('/poi/add-attribute', {
				poi_id: this.id,
				attribute_id: id
			}, function(data) {
				if (null != data.attributes) {
					myPoi.attributes = data.attributes;
					myPoi.buildAddList();
					myPoi.buildAttributesList();
				}
			}, 'json');
		},
		
		deleteAttribute: function(id) {
			this.hideAll();
			if (confirm(this.translation.poi_Confirm_Delete)) {
				$.post('/poi/delete-attribute', {
					poi_id: this.id,
					attribute_id: id
				}, function(data) {
					if (null != data.attributes) {
						myPoi.attributes = data.attributes;
						myPoi.buildAttributesList();
					}
				}, 'json');
			}
		},
		
		changeName: function() {
			var newname = jQuery.trim($('#newname').val());
			$('#newname').val(jQuery.trim($('#newname').val()));
			$('#newmail').val(jQuery.trim($('#newmail').val()));
			$('#newphone').val(jQuery.trim($('#newphone').val()));
			$('#newweb').val(jQuery.trim($('#newweb').val()));
			if (newname == '') {
				alert(this.translation.poi_Error_Name);
			} else if($('#newmail').val().indexOf('@') < 0) {
				alert("Meiliaadress peab sisaldama @ märki.");
			} else {
				this.hideAll();
				$.post('/poi/change-name', {
					id: this.id,
					name: newname,
					mail: jQuery.trim($('#newmail').val()),
					phone: jQuery.trim($('#newphone').val()),
					web: jQuery.trim($('#newweb').val())
					
				}, function(data) {
					if (null != data.name) {
						myPoi.name = data.name;
						myPoi.mail = data.mail;
						myPoi.phone = data.phone;
						myPoi.web = data.web;
						myPoi.setTitle();
					}
				}, 'json');
			}
		},
		
		editDescription: function() {
			$('#descriptioncontainer').hide();
			$('#newdescription').val(this.description);
			$('#editdescriptioncontainer').show();
		},
		
		selectLanguage: function() {
			this.description = '';
			this.hideAll();
			this.language = $('#selectlanguage option:selected').val();
			this.loadDescripton();
		},
		
		loadDescripton: function() {
			$.post('/poi/load-description', {
				id: this.id,
				language: this.language
			}, function(data) {
				if (null != data.description) {
					myPoi.description = data.description;
				}
				myPoi.setDescription();
			}, 'json');
		},
		
		changeDescription: function() {
			var description = jQuery.trim($('#newdescription').val());
			$('#newdescription').val(description);
			this.description = '';
			this.hideAll();
			$.post('/poi/change-description', {
				id: this.id,
				language: this.language,
				description: description
			}, function(data) {
				if (null != data.description) {
					myPoi.description = data.description;
					myPoi.setDescription();
				}
			}, 'json');
		},
		
		deleteDescription: function() {
			this.hideAll();
			if (confirm(this.translation.poi_Confirm_Delete)) {
				$('#deletebutton').hide();
				this.description = '';
				$.post('/poi/change-description', {
					id: this.id,
					language: this.language,
					description: ''
				}, function(data) {
					if (null != data.description) {
						myPoi.description = data.description;
						myPoi.setDescription();
					}
				}, 'json');
			}
		},
		
		setDescription: function() {
			$('#description').html(this.description);
		},
		
		addPicture: function() {
			var filename = document.getElementById('picture').value;
			if (filename == '') {
				alert(this.translation.poi_Error_Filenotselected);
			} else if (! /^.*\.(jpg|jpeg|png|gif)$/i.test(filename)) {
				alert(this.translation.poi_Error_Filetype);
			} else {
				$('#addpicture').submit();
			}
		},
		
		buildPicturesList: function() {
			$('#pictureslist').empty();
			var html = '';
			var row = null;
			var picture = null;
			if(this.pictures.length > 0) {
				for (row=0; row<this.pictures.length; row++) {
					picture = this.pictures[row];
					html = '<div class="picturefloat"><a rel="fancybox" href="';
					html += this.picturesPath + 'pictures/' + this.id + '/' + picture.filename;
					html += '"><img src="' + this.picturesPath + 'thumbnails/' + this.id + '/' + picture.filename;
					html += '" /></a><br /><a href="javascript:myPoi.deletePicture(' + picture.id;
					html += ')">' + this.translation.poi_Button_Delete + '</a></div>';
					$('#pictureslist').append(html);
				}
			}
		},
		
		deletePicture: function(id) {
			this.hideAll();
			if (confirm(this.translation.poi_Confirm_Delete)) {
				$.post('/poi/delete-picture', {
					poi_id: this.id,
					picture_id: id
				}, function(data) {
					if (null != data.pictures) {
						myPoi.pictures = data.pictures;
						myPoi.buildPicturesList();
					}
				}, 'json');
			}
		},
		
		showPicture: function(file) {
			Shadowbox.open({
				content: file,
				player: 'img'
		    });
		},
		
		showAddTip: function() {
			this.hideAll();
			$('#addtipbutton').hide();
			$('#addtipcontainer').show();
		},
		
		selectTipsLanguage: function() {
			this.hideAll();
			this.tipsLanguage = $('#selecttipslanguage option:selected').val();
			this.loadTips();
		},
		
		loadTips: function() {
			$.post('/poi/load-tips', {
				poi_id: this.id,
				language: this.tipsLanguage
			}, function(data) {
				if (null != data.tips) {
					myPoi.tips = data.tips;
					myPoi.buildTipsList();
				}
			}, 'json');
		},
		
		buildTipsList: function() {
			var html = '';
			var row = null;
			for (row=0; row<this.tips.length; row++) {
				html += '<p>' + this.tips[row].text;
				html += '<br /><a href="javascript:myPoi.editTip(' + row + ')">' + this.translation.poi_Button_Edit;
				html += '</a> <a href="javascript:myPoi.deleteTip(' + this.tips[row].id + ')">' + this.translation.poi_Button_Delete;
				html += '</a></p>';
			}
			$('#tipslist').empty().html(html);
		},
		
		saveTip: function() {
			var newtip = jQuery.trim($('#newtip').val());
			$('#newtip').val(newtip);
			
			if (newtip == '') {
				alert(this.translation.poi_Error_Tip);
				return;
			} else {
				$.post('/poi/insert-tip', {
					poi_id: this.id,
					language: this.tipsLanguage,
					text: newtip
				}, function(data) {
					if (null != data.tips) {
						myPoi.tips = data.tips;
						myPoi.hideAll();
						myPoi.buildTipsList();
					}
				}, 'json');
			}
		},
		
		editTip: function(nr) {
			this.hideAll();
			this.selectedTip = nr;
			var html = '<p><textarea id="edittip" class="wide" rows="5" cols="30">' + this.tips[nr].text;
			html += '</textarea><br /><a href="javascript:myPoi.updateTip()">' + this.translation.poi_Button_Save;
			html += '</a> <a href="javascript:myPoi.hideAll()">' + this.translation.poi_Button_Cancel + '</a></p>';
			var row = $('#tipslist').find('p').eq(nr);
			row.replaceWith(html);
		},
		
		updateTip: function(id, name, value) {
			if(null != this.selectedTip) {
				var selected = this.selectedTip;
				this.selectedTip = null;
				$.post('/poi/update-tip', {
					id: this.tips[selected].id,
					language: this.tipsLanguage,
					text: $('#edittip').val(),
					poi_id: this.id
				}, function(data) {
					if (null != data.tips) {
						myPoi.tips = data.tips;
						myPoi.hideAll();
						myPoi.buildTipsList();
					}
				}, 'json');
			}
		},
		
		deleteTip: function(tip_id) {
			this.hideAll();
			if (confirm(this.translation.poi_Confirm_Delete)) {
				$.post('/poi/update-tip', {
					id: tip_id,
					language: this.tipsLanguage,
					text: '',
					poi_id: this.id
				}, function(data) {
					if (null != data.tips) {
						myPoi.tips = data.tips;
						myPoi.hideAll();
						myPoi.buildTipsList();
					}
				}, 'json');
			}
		}
};

var travelblog = {
		map: null,
		marker: null,
		markers: new Array(),
		count: 0,
		id: null,
		continent: null,
		country: null,
		pictures: null,
		picturesPath: null,
		translation: null,
		pois: {},
		popup: null,
		poinames: new Array(),
		poi: null,
		videos: null,
		prevmarker: null,
		prevlocation: null,
		
		init: function() {
			this.initMap();
			if($('#continent option:selected').val() != 0) {
				this.selectContinent();
				this.codeAddress();
			}
			this.buildPicturesList();
			this.buildVideoList();
			this.showTiny();
			//this.loadVideo();
		},
		
		initMap: function() {
			var latlng = new google.maps.LatLng(67, 24);

		    var myOptions = {
		      zoom: 5,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    
		    this.map = new google.maps.Map(document.getElementById("map_blog"),
		        myOptions);

			google.maps.event.addListener(this.map, 'click', function(event) {
				//travelblog.choosePoi(event.latLng);
				//travelblog.poinames[travelblog.poinames.length] = 0;
				travelblog.placeMarker(event.latLng, true);
				//travelblog.setLocation(event.latLng);
			});
			
			this.buildPoiList();
			this.geocoder = new google.maps.Geocoder();
		},
		
		showMap: function() {
			var latlng = new google.maps.LatLng(67, 24);

		    var myOptions = {
		      zoom: 5,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    
		    this.map = new google.maps.Map(document.getElementById("map_blog"),
		        myOptions);

			this.buildPoiList2();
			this.geocoder = new google.maps.Geocoder();
		},
		
		buildPoiList2: function() {
			for (var x = 0; x < this.poi.length; x++) {
				var p = this.poi[x];
				var latlng = new google.maps.LatLng(p.latitude, p.longitude);
				this.poinames[this.poinames.length] = p.name;
				this.showMarkers(latlng);
				this.markers[this.markers.length-1] = p.poi_id;
			}
		},
		
		buildPoiList: function() {
			for (var x = 0; x < this.poi.length; x++) {
				var p = this.poi[x];
				var latlng = new google.maps.LatLng(p.latitude, p.longitude);
				this.poinames[this.poinames.length] = p.name;
				this.placeMarker(latlng, false);
				this.markers[this.markers.length-1] = p.poi_id;
			}
		},
		
		placeMarker: function(location, load) {
				
			if(load == true) {
				var marker = new google.maps.Marker({
					//position: location,
				    draggable: true,
				    map: this.map
				});
			} else {
				var marker = new google.maps.Marker({
					position: location,
				    draggable: true,
				    map: this.map
				});
			}
			
			var length = this.markers.length;
			this.markers[length] = 0;

			
			google.maps.event.addListener(marker, 'dragend', function() {
				travelblog.loadPois(marker.getPosition(), marker, length, location);
				//travelblog.setLocation(marker.getPosition());
				//travelblog.loadPois(marker.getPosition().lat(), marker.getPosition().lng(), marker, length);
			});
			
			if(load == true) {
				this.loadPois(location, marker, length, 0);
			}
			
			google.maps.event.addListener(marker, 'click', function(event) {
				var infoWindow = new google.maps.InfoWindow({
					position: marker.getPosition(),
					content: travelblog.poinames[length]
				});
				infoWindow.open(travelblog.map);
			});
		},
		
		showMarkers: function(location) {

			var marker = new google.maps.Marker({
				position: location,
			    draggable: false,
			    map: this.map
			});
			
			var length = this.markers.length;
			this.markers[length] = 0;

			google.maps.event.addListener(marker, 'click', function(event) {
				var infoWindow = new google.maps.InfoWindow({
					position: marker.getPosition(),
					content: travelblog.poinames[length]
				});
				infoWindow.open(travelblog.map);
			});
		},
		  
		codeAddress: function() {
			    var address = this.country;
			    this.geocoder.geocode( { 'address': address}, function(results, status) {
			      if (status == google.maps.GeocoderStatus.OK) {
			    	travelblog.map.setCenter(results[0].geometry.location);
			        travelblog.setLocation(results[0].geometry.location);
			        //travelblog.marker.setPosition(results[0].geometry.location);
			      } else {
			        alert("Geocode was not successful for the following reason: " + status);
			      }
			    });
			  },
			  
		setLocation: function(location) {
			$('#latitude').val(location.lat());
			$('#longitude').val(location.lng());
		},

		
		selectContinent: function() {
			this.continent = $('#continent option:selected').val();
			this.loadCountries();
		},
		
		selectCountry: function() {
			this.country = $('#country option:selected').val();
			this.codeAddress();
		},
		
		selectPoi: function(marker, length, select) {
			if(select) {
				var value = $('#poi option:selected').val();
				var poi = this.pois[value];
				//alert(this.markers.length+" ja "+this.markers[length-1])
				this.markers[length] = poi.id;
				
				this.poinames[length] = poi.name;
				//alert(this.poinames[this.poinames.length-1]);
				var latlng = new google.maps.LatLng(poi.latitude, poi.longitude);
				marker.setPosition(latlng);
				//this.setLocation(marker.getPosition());
			} else {
				if(this.prevlocation != 0) {
					this.prevmarker.setPosition(this.prevlocation);
				}
			}
			Popup.hide('modal');
			//this.loadPois(poi.latitude, poi.longitude, marker, length);
		},
		
		loadPois: function(location, marker, length, plocation) {
			this.prevmarker = marker;
			this.prevlocation = plocation;
			$.post('/travelblog/load-pois', {
				latitude: location.lat(),
				longitude: location.lng()
			}, function(data) {
				travelblog.pois = data;
				var html = '<select id="poi" name="poi">';
				html += '<option value="null">- Vali POI -</option>';
				if(data.length > 0) {
					for(var i=0; i<data.length; i++) {
						html += '<option value="'+i+'">'+data[i].name+' - '+parseFloat(data[i].distance).toFixed(2)+' km</option>';
					}
				}
				html += '</select>';
				$('#poilist').html(html);
				$('#poi').change(function() {
					travelblog.selectPoi(marker, length, true);
				});
				Popup.showModal('modal');
			}, 'json');
		},
		
		loadCountries: function() {
			$.post('/travelblog/load-countries', {
				continent: this.continent
			}, function(data) {
				var html = '<select id="country" name="country">';
				for(var i=0; i<data.length; i++) {
					html += '<option value="'+data[i].country+'">'+data[i].country_name+'</option>';
				}
				html += '</select>';
				$('#countries').html(html);
				if(travelblog.country != null) {
					$("#country").val(travelblog.country);
				}
				$('#country').change(function() {
					travelblog.selectCountry();
				});
			}, 'json');
		},
		
		addPicture: function() {
			var filename = document.getElementById('picture').value;
			if (filename == '') {
				alert(this.translation.poi_Error_Filenotselected);
			} else if (! /^.*\.(jpg|jpeg|png|gif)$/i.test(filename)) {
				alert(this.translation.poi_Error_Filetype);
			} else {
				$('#addpicture').submit();
			}
		},
		
		saveBlog: function() {
			var json = JSON.stringify(this.markers);
			$.post('/travelblog/save-blog', {
				id: this.id,
				title: $("#title").val(),
				country: $("#country").val(),
				pois: json,
				text: tinyMCE.get('blogcontent').getContent(),
				notes: $("#notes").val()
			}, function(data) {
				travelblog.id = data.id;
				$("#id").val(travelblog.id);
			}, 'json');
		},
		
		buildPicturesList: function() {
			$('#pictureslist').empty();
			var html = '';
			var row = null;
			var picture = null;
			for (row=0; row<this.pictures.length; row++) {
				picture = this.pictures[row];
				html = '<div class="picturefloat"><a rel="fancybox" href="';
				html += this.picturesPath + 'pictures/' + this.id + '/' + picture.filename + '.jpg';
				html += '"><img src="' + this.picturesPath + 'thumbnails/' + this.id + '/' + picture.filename + '.jpg';
				html += '" /></a><br /><a href="javascript:travelblog.deletePicture(' + picture.id;
				html += ')">' + this.translation.poi_Button_Delete + '</a></div>';
				$('#pictureslist').append(html);
			}
		},
		
		buildVideoList: function() {
			$('#videogallery').empty();
			if(this.videos.length > 0) {
				var html = '<table class="objektide_tabel"><tr class="objektide_tabel_heading"><td>Video nimi</td><td align="center"></td></tr>';
				var row = null;
				var video = null;
				for (row=0; row<this.videos.length; row++) {
					video = this.videos[row];
					html += '<tr><td><strong><a rel="#voverlay" href="http://www.youtube.com/v/'+video.video_id+'?autoplay=1&rel=0&enablejsapi=1&playerapiid=ytplayer" title="'+video.title+'">'+video.title+'<span></span></a><a id="videolb" href="http://videolightbox.com">Lightbox Flash Movie by VideoLightBox.com v1.10</a></strong><br></td><td align="center"><a href="javascript:travelblog.deleteVideo('+video.id+')">Kustuta</a></td>';
				}
				html += '</table>';
				$('#videogallery').append(html);
			}
		},
		
		buildVideoList2: function() {
			$('#videogallery').empty();
			if(this.videos.length > 0) {
				var html = '<table>';
				var row = null;
				var video = null;
				for (row=0; row<this.videos.length; row++) {
					video = this.videos[row];
					html += '<tr><td><strong><a rel="#voverlay" href="http://www.youtube.com/v/'+video.video_id+'?autoplay=1&rel=0&enablejsapi=1&playerapiid=ytplayer" title="'+video.title+'">'+video.title+'<span></span></a><a id="videolb" href="http://videolightbox.com">Lightbox Flash Movie by VideoLightBox.com v1.10</a></strong><br></td></tr>';
				}
				html += '</table>';
				$('#videogallery').append(html);
			}
		},
		
		onYouTubePlayerReady: function(playerId) { 
			ytplayer = document.getElementById("video_overlay"); 
			ytplayer.setVolume(100); 
		}, 
		
		deletePicture: function(id) {
			//this.hideAll();
			if (confirm(this.translation.poi_Confirm_Delete)) {
				$.post('/travelblog/delete-picture', {
					id: this.id,
					picture_id: id
				}, function(data) {
					if (null != data.pictures) {
						travelblog.pictures = data.pictures;
						travelblog.buildPicturesList();
					}
				}, 'json');
			}
		},
		
		showPicture: function(file) {
			Shadowbox.open({
				content: file,
				player: 'img'
		    });
		},
		
		addVideo: function() {
			$.post('/travelblog/add-video', {
				title: $("#videotitle").val(),
				url: $("#videourl").val(),
				id: this.id
			}, function(data) {
				travelblog.videos = data;
				travelblog.buildVideoList();
			}, 'json');
		},
		
		deleteVideo: function(id) {
			$.post('/travelblog/delete-video', {
				vid: id,
				id: this.id
			}, function(data) {
				travelblog.videos = data;
				travelblog.buildVideoList();
			}, 'json');
		},
		
		findBlogs: function() {
			$.post('/travelblog/find-blogs', {
				keyword: $("#keyword").val()
			}, function(data) {
				travelblog.buildBlogList(data);
			}, 'json');
		},
		
		buildBlogList: function(data) {
			$('#bloglist').empty();
			if(data.length > 0) {
				var html = '<table class="objektide_tabel">';
				var row = null;
				var blog = null;
				for (row=0; row<data.length; row++) {
					blog = data[row];
					html += '<tr><td><strong><a href="/travelblog/view/id/'+blog.travelblog_id+'">'+blog.title+'<span></span></a></strong><br></td></tr>';
				}
				html += '</table>';
				$('#bloglist').append(html);
			}
		},
		
		hideModal: function() {
			$('#modal').hide();
		},
		
		showTiny: function() {
			tinyMCE.init({ 
			    theme : "simple", 
			    mode: "exact",
			    elements : "blogcontent,description", 

			   	//theme options
			    theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
			    theme_advanced_toolbar_location : "top",
			    theme_advanced_toolbar_align : "left",
			    theme_advanced_statusbar_location : "bottom",
			    theme_advanced_resizing : true

			   	
			}); 
		}
		
};

function ratePoi(rating, poi_id) {
	alert("jeee");
	if($('#identity').val() == true) {
		$.post('/poi/rate', {
			rating: rating,
			id: poi_id
		}, function(data) {
			//alert(data[0] + ", " + data[1]);
			buildRating(data, poi_id); 
		}, 'json');
	} else {
		alert("Hindamiseks palun logige sisse.");
	}
}

function showRate(rating, id) {
	$('#myrating').empty();
	var html = '<span class="hinnang">';
	for (var row=1; row<6; row++) {
		if(rating >= row) {
			html += '<a href="javascript:ratePoi('+row+','+id+')" onmouseover="javascript:showRate('+row+','+id+');"><img src="/img/star1.png" width="14" height="14" alt="*" /></a>';
		} else {
			html += '<a href="javascript:ratePoi('+row+','+id+')" onmouseover="javascript:showRate('+row+','+id+');"><img src="/img/star3.png" width="14" height="14" alt="*" /></a>';
		}
	}
	html += '</span>';
	$('#myrating').append(html);
}

var ratingdata = null;

function buildRating(data, id) {
	$('#myrating').empty();
	$('#allrating').empty();
	ratingdata = data;
	if(data.length > 0) {
		var html = '<span class="hinnang">';
		var html2 = '';
		var row = null;
		for (row=1; row<6; row++) {
			if(data[1] >= row) {
				html += '<a href="javascript:ratePoi('+row+','+id+')" onmouseover="javascript:showRate('+row+','+id+');"><img src="/img/star1.png" width="14" height="14" alt="*" /></a>';
			} else {
				html += '<a href="javascript:ratePoi('+row+','+id+')" onmouseover="javascript:showRate('+row+','+id+');"><img src="/img/star3.png" width="14" height="14" alt="*" /></a>';
			}
			if(data[0] >= row) {
				html2 += '<img src="/img/star1.png" width="14" height="14" alt="*" />';
			} else if(data[0]<row && data[0]>row-1) {
				html2 += '<img src="/img/star2.png" width="14" height="14" alt="*" />';
			} else {
				html2 += '<img src="/img/star3.png" width="14" height="14" alt="*" />';
			}
		}
		html += '</span>';
		$('#myrating').append(html);
		$('#allrating').append(html2);
	}
}


$(document).ready(function() {
	
	$('#selectlanguage').change(function() {
		myPoi.selectLanguage();
	});
	$('#selecttipslanguage').change(function() {
		myPoi.selectTipsLanguage();
	});
	$('#continent').change(function() {
		travelblog.selectContinent();
	});
	if ($('#poi_map').length > 0){
		poi.initMap();
	}
	
	$("a[rel=fancybox]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}

	});

});
Shadowbox.init();



