var map;
var mapMarker;
var navegaPorAJAX = false;
var panoShown;

$(document).ready(function() {
	$.historyInit(cambioURL, "jquery_history.html");	
	$("#btnBuscar").click(buscar);	
	$("#txtBuscar").keyup(function(key) { if (key.keyCode==13) buscar(); });
	$("#txtEmail").click(function(){
		this.value="";
	});

	$("#linkBeta").click(function() {
		var txt = $("#txtEmail")[0].value;
		if (txt.indexOf("@")>3) {
			alert("Gracias por suscribirte a la beta de Mapplo. Te enviaremos proximamente la invitacion a la version beta");
			$.getJSON("agregar.php?email=" + txt);
		}
		return false;
	});
//	if (window.location.href.indexOf("ajax")>1) {
	var IE = /*@cc_on!@*/false;
	if (!IE) {
		navegaPorAJAX = true;
		navegaAJAX("a");
		if (window.location.href.indexOf("#")>1) {
			// Viene con URL definida
			cargarAJAX(location.href.substring(location.href.indexOf("#")+1));
		}
	}	
});


function azar() {
	if (window.location == "http://www.mapplo.com") {
		window.location.reload(true);
	} else {
		window.location = "http://www.mapplo.com"
	}
}

function cambioURL(url) {
	loadAJAX(url);
}

function navegaAJAX(selector) {
	var links = $(selector);
	for(var i=0; i<links.length; i++) {
		if ((links[i].target == "") && (links[i].href.substring(0, 4)!="mail") && (links[i].href.substring(0, 4)!="java") && (links[i].href.indexOf("/#")==-1)) {
			links[i].onclick = function(){
				cargarAJAX(decodeURI(this.href.substring(this.href.indexOf("=") + 1)));
				return false;
			}
		}
	}	
}

function actualizarURL(url) {
	var scriptURL;
	if (location.href.indexOf("#")>0) {
		scriptURL = location.href.substring(0, location.href.indexOf("#"));
	} else {
		scriptURL = location.href;
	}
	location.href = scriptURL + "#" + url;
	if (url=="/") {
		cambioURL();		
	}
}

function cargarAJAX(url){
	$("#breadcrumb").html("Por favor espere...").addClass("espere");
	$("#espere").fadeIn();
	actualizarURL(url);
}

function loadAJAX(url) {
	$.getJSON("g.php", {u: url, a: Math.random()}, function(r) {
		$("#breadcrumb").removeClass("espere");
		$("#espere").fadeOut();

		if (r.ok) {
			document.title = r.title;
			$("#breadcrumb").html(r.breadcrumb);
			//$("#breadcrumb").effect("highlight", {}, 1000);
			$("#central").html(r.modulos_central);
			if (r.panorama != null) {
				if (panoShown == false) {
					$("#panorama").fadeIn();
				}
				panoURL = r.panorama.panoURL;
				direccion = r.panorama.direccion;
				barrio = r.panorama.barrio;
				latitud = r.panorama.latitud;
				longitud = r.panorama.longitud;
				siguientePano = r.panorama.siguientePano;
				anteriorPano = r.panorama.anteriorPano;
				if (map != undefined) {
					definirPuntoMapa();
				}
				playerLoaded();
			} else {
				$("#panorama").slideUp();
				panoShown = false;
				firstTime = true;
			}
			navegaAJAX("#breadcrumb a, #central a");
			
		} else {
			alert("Ocurrió un error");
		}
	} ); 
}

function buscar() {
	var txt = $("#txtBuscar")[0].value;
	if (txt!="" && txt!="buscar ...") {
		if (navegaPorAJAX) {
			 cargarAJAX("buscar/" + txt);
		} else {
			window.location = "?url=buscar/" + encodeURI(txt);					
		}
	}
}

var firstTime = true;

function playerLoaded() {
	if (firstTime) {
		setTimeout(actualizarPano, 1000);
	} else {
		actualizarPano();
	}
}

function actualizarPano(){
	panoShown = true;
	
	var player = $('#mapploPlayer')[0];
	var adicional = "";
	if (firstTime) { 
		adicional = "lookat(90,0);zoomto(45)";
	} else {
		adicional = "lookat(90,0);zoomto(45)";			
	}
	player.call("loadpano(null,sphere=" + panoURL + ",keepbase|KEEPHOTSPOTS);" + adicional);
	player.call("plugin[cortina].setcalle(" + direccion.replace(",", "") + "," + barrio.replace(",", "") + ")");
	firstTime = false;
}

function proxima() {
	if (siguientePano.indexOf("///")>0) 
	  alert('No hay mas panoramas por ahora... ');
	 else  
	 if (navegaPorAJAX)
	 	cargarAJAX(siguientePano.substring(siguientePano.indexOf("=")+1));
	  else
	  	window.location = siguientePano;
}

function anterior() {
	if (anteriorPano.indexOf("///")>0) 
	  alert('No hay mas panoramas por ahora en esta calle... falta poco');
	 else  	
		 if (navegaPorAJAX) 
		 	cargarAJAX(anteriorPano.substring(anteriorPano.indexOf("=")+1));
		  else	 
	  		window.location = anteriorPano;
}

function showMap() {
		
		var player = $("#mapploPlayer")[0];
		player.width = 589;
		player.call("set(plugin[openmapa].visible, false)");
		player.call("set(plugin[closemapa].visible, true)");
		$("#gmapa").show();

	    var latlng = new google.maps.LatLng(latitud, longitud);
    	var myOptions = {
      		zoom: 15,
      		center: latlng,
      		mapTypeId: google.maps.MapTypeId.ROADMAP
    	};
        if (map == undefined) {
	    	map = new google.maps.Map(document.getElementById("gmapa"), myOptions);
		}
		definirPuntoMapa();
}

function definirPuntoMapa(){

	  var myLatLng = new google.maps.LatLng(latitud, longitud);
	  map.setCenter(myLatLng);
	  if (mapMarker == null) {
	  	mapMarker = new google.maps.Marker({
	  		position: myLatLng,
			icon: 'img/pano_marker.png',
			draggable: true,
	  		map: map
	  	});
	    google.maps.event.addListener(mapMarker, 'dragend', function() {
	       var geocoder = new google.maps.Geocoder();
			geocoder.geocode({'latLng': mapMarker.getPosition()}, 
				function(results, status) {
			        if (status == google.maps.GeocoderStatus.OK) {
			          if (results[0]) {
					  	var ciudad = results[0].address_components[2].short_name;
			            var calle = results[0].address_components[1].short_name;
						var numeracion = results[0].address_components[0].short_name;
						if (numeracion.indexOf("-")>0) {
							numeracion = numeracion.substring(0, numeracion.indexOf("-"));
						}
						/*if (ciudad.indexOf("Buenos Aires")  0) {
							alert("No disponemos de panoramas en " + ciudad);
							mapMarker.setPosition(myLatLng);
						}
						else {*/
							cargarAJAX("buscar/" + calle + " " + (parseInt(numeracion)+20));
						//}
			          }
			        } else {
			          alert("Geocoder failed due to: " + status);
			        }
	     	 	});		   
	    });		
	  } else {
	  	mapMarker.setPosition(myLatLng);
	  }
}

function closeMap() {
	$("#gmapa").hide();
	var player = $("#mapploPlayer")[0];
	player.width = 789;
	player.call("set(plugin[openmapa].visible, true)");
	player.call("set(plugin[closemapa].visible, false)");
	
}

function comercios() {
	window.open("comercios.html", "_blank", "width=850,height=600,scrollbars=1");
}
