// Funcionalidad Principal
var mapaGoogle = {
	datos: {
		mapa: null,
		gdir: null,
		geocoder: null,
		icono: null,
		anchoMiniDefecto: 130,
		altoMiniDefecto: 130,
		direcciones: new Array(),
		controles: new Array(),
		puntos: new Array(),
		cargaDefectoUbicacionActual: false,
		cargaDefectoUbicacionDefecto: false,
		longitudDefecto: -3.7010192,
		latitudDefecto: 40.417416,
		zoomDefecto: 13,
		urlIcono: "../includes/img/iconos/marker.png",
		urlIconoAqui: "../includes/img/iconos/marker-aqui.png",
		urlSombraIcono: "../includes/img/iconos/sombraMarker.png",
		idMapa: "caja2Mapa",
		idDirecciones: "rutaAPunto",
		grupoSeleccionado: null
	},
	
	funciones: {
		mapaCargado: function(){
			var auxi = document.getElementById(mapaGoogle.datos.idMapa);
			
			if(!auxi)
				return false;
				
			mapaGoogle.datos.mapa = new GMap2(auxi);
			mapaGoogle.datos.mapa.setCenter(new GLatLng(0, 0), mapaGoogle.datos.zoomDefecto);
						
			mapaGoogle.datos.geocoder = new GClientGeocoder();

			var controles = mapaGoogle.datos.controles;
			for(var i=0; i<controles.length; i++){
				mapaGoogle.datos.mapa.addControl(controles[i]); 
			}
			
			if(mapaGoogle.datos.urlIcono != ""){
				mapaGoogle.datos.icono = mapaGoogle.funciones.generaIcono(mapaGoogle.datos.urlIcono);
			}

			if(mapaGoogle.datos.idDirecciones != ""){
				mapaGoogle.datos.gdir = new GDirections(mapaGoogle.datos.mapa, document.getElementById(mapaGoogle.datos.idDirecciones));
				GEvent.addListener(mapaGoogle.datos.gdir, "load", mapaGoogle.funciones.direccionCargada);
				GEvent.addListener(mapaGoogle.datos.gdir, "error", mapaGoogle.funciones.manejadorErrores);
			}

			var direcciones = mapaGoogle.datos.direcciones;
			for(var i=0; i<direcciones.length; i++){
				var dir = direcciones[i];
				mapaGoogle.funciones.anadePunto(dir.lon, dir.lat, mapaGoogle.datos.icono, dir.texto, mapaGoogle.datos.markerDraggable);
				if(i==0){
					mapaGoogle.datos.mapa.setCenter(point, (dir.zoom==null?mapaGoogle.datos.zoomDefecto:dir.zoom)); 
					marcador.openInfoWindowHtml(dir.texto);
				}
			}
			
			if(mapaGoogle.datos.cargarUbicacionActual){
				var posicionActual = mapaGoogle.funciones.obtenerUbicacionActual();
				if(posicionActual){
					var iconoAqui = mapaGoogle.funciones.generaIcono(mapaGoogle.datos.urlIconoAqui);
					var marcador = mapaGoogle.funciones.nuevoMarcador(posicionActual.point, iconoAqui, posicionActual.texto, mapaGoogle.datos.markerDraggable);
					mapaGoogle.datos.mapa.addOverlay(marcador);
					mapaGoogle.datos.mapa.setCenter(posicionActual.point, (posicionActual.zoom==null?mapaGoogle.datos.zoomDefecto:posicionActual.zoom)); 
					//marcador.openInfoWindowHtml(posicionActual.texto);
				}
			}
			
			if(mapaGoogle.datos.cargaDefectoUbicacionDefecto){
				var latlng = new google.maps.LatLng(mapaGoogle.datos.latitudDefecto, mapaGoogle.datos.longitudDefecto);
				var iconoAqui = mapaGoogle.funciones.generaIcono(mapaGoogle.datos.urlIconoAqui);
				var marcador = mapaGoogle.funciones.nuevoMarcador(latlng, iconoAqui, "Posición por defecto", mapaGoogle.datos.markerDraggable);
				mapaGoogle.datos.mapa.addOverlay(marcador);
				mapaGoogle.datos.mapa.setCenter(latlng, mapaGoogle.datos.zoomDefecto); 
				//marcador.openInfoWindowHtml(posicionActual.texto);
			}
			
			//Ahora en funcion de los limites del mapa, cargamos los puntos que correspondan
			mapaGoogle.cargaDatosMapaLimitesActuales();
			
			//Tenemos que poner el evento al mapa para cuando se arrastre, actualizar los nuevos puntos, o al hacer zoom
			GEvent.addListener(mapaGoogle.datos.mapa, "dragend", function() {
				muestraEspere();
				mapaGoogle.cargaDatosMapaLimitesActuales();
			});
			GEvent.addListener(mapaGoogle.datos.mapa, "zoomend", function() {
				muestraEspere();
				mapaGoogle.cargaDatosMapaLimitesActuales();
			});

			return true;
		},
		
		generaIcono: function(url){
			var icono = new GIcon();
			icono.image = url;
			icono.shadow = mapaGoogle.datos.urlSombraIcono;
			icono.iconSize = new GSize(25, 40);
			icono.shadowSize = new GSize(50, 52);
			icono.iconAnchor = new GPoint(14, 52);
			icono.infoWindowAnchor = new GPoint(25, 10);
			
			return icono;
		},
		
		anadePunto: function(lon, lat, texto, icono, markerDraggable){
			//No podemos poner puntos repetidos
			var point = new GLatLng(lon, lat);
			var marcador = mapaGoogle.funciones.nuevoMarcador(point, (icono==null?mapaGoogle.datos.icono:mapaGoogle.funciones.generaIcono(icono)), texto, (markerDraggable==null?false:markerDraggable));
			mapaGoogle.datos.mapa.addOverlay(marcador);
			mapaGoogle.datos.puntos.push(marcador);
			
			return marcador;
		},
		
		calculaRuta: function(fromAddress, toAddress, locale){
			mapaGoogle.datos.gdir.load("from: " + fromAddress + " to: " + toAddress,{"locale": (locale==null?"es":locale)});
		},
		
		manejadorErrores: function(){
			ocultaEspere();
			if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + mapaGoogle.datos.gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + mapaGoogle.datos.gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_MISSING_QUERY)
				alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + mapaGoogle.datos.gdir.getStatus().code);
			//else if (mapaGoogle.datos.gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
			//	alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_BAD_KEY)
				alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + mapaGoogle.datos.gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("A directions request could not be successfully parsed.\n Error code: " + mapaGoogle.datos.gdir.getStatus().code);
			else 
				alert("An unknown error occurred.");
		},
		
		direccionCargada: function(){
			window.location.href += '#direccion';
		},
		
		nuevoMarcador: function(point, icono, texto){
			var marker;
	
			if(icono==null)
				marker = new GMarker(point);
			else
				marker = new GMarker(point,icono);
				
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(texto);
			});
			
			return marker;
		},

		obtenerUbicacionActual: function(){
			if (google.loader.ClientLocation) {
				var latlng, auxi;
				latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
				auxi = "Usted se encuentra aquí: ";
				if (google.loader.ClientLocation.address.country_code == "US" && google.loader.ClientLocation.address.region) {
					auxi += google.loader.ClientLocation.address.city + ", " + google.loader.ClientLocation.address.region.toUpperCase();
				} else {
					auxi += google.loader.ClientLocation.address.city + ", " + google.loader.ClientLocation.address.country_code;
				}
				//alert(auxi+"-"+google.loader.ClientLocation.latitude+"-"+google.loader.ClientLocation.longitude);
				return {point:latlng, texto:auxi, zoom:13};
			}else{
				return false;
			}
		},
		
		getLimitesMapa: function(){
			var auxi = mapaGoogle.datos.mapa.getBounds();
			
			return {no: auxi.getSouthWest(), se: auxi.getNorthEast()};
		},
		
		getCenterMapa: function(){
			var auxi = mapaGoogle.datos.mapa.getCenter();
			
			return {latitud: auxi.lat(), longitud: auxi.lng()};
		},
				
		marcarDireccion: function(direccion, borrarAnteriores, zoom) {
			if (direccion == "") {
				alert("Debe especificar una dirección");
			} else {
				mapaGoogle.datos.geocoder.getLatLng(direccion,
					function(point) {
				    	if (!point) {
				    		alert("No se encuentra la dirección: " + direccion);
				    	} else {
				    		if (borrarAnteriores) {
				    			mapaGoogle.datos.marcadores = new Array();
				    			mapaGoogle.datos.mapa.clearOverlays();
				    		}
							//Calculamos los puntos cercanos del mapa
							setTimeout("mapaGoogle.cargaDatosMapaLimitesActuales();",500);
							mapaGoogle.datos.mapa.setCenter(point, (zoom==null?mapaGoogle.datos.zoomDefecto:zoom)); 

							var marcador = mapaGoogle.funciones.nuevoMarcador(point, null, direccion);
							//marcador.openInfoWindowHtml(direccion);
							return marcador;
				    	}
				  	}
				);
			}		
		}
	},
	
	nuevaDireccion: function(longitud, latitud, t, z){
		mapaGoogle.datos.direcciones.push({lon:longitud, lat:latitud, texto:t, zoom:z});
	},
		
	vistaMiniatura: function(an, al){
		var Tsize = new GSize((an==null?mapaGoogle.datos.anchoMiniDefecto:an), (al==null?mapaGoogle.datos.altoMiniDefecto:al));
		mapaGoogle.datos.controles.push(new GOverviewMapControl(Tsize));
	},
	
	controlMapaPequenio: function(){
		mapaGoogle.datos.controles.push(new GSmallMapControl());
	}, 
	
	controlMapaGrande: function(){
		mapaGoogle.datos.controles.push(new GLargeMapControl());
	}, 
	
	controlTipoMapa: function(){
		mapaGoogle.datos.controles.push(new GMapTypeControl());
	},
	
	setMapaSatelite: function(){
		mapaGoogle.datos.mapa.setMapType(G_SATELLITE_MAP);
	},
	
	setMapaHibrido: function(){
		mapaGoogle.datos.mapa.setMapType(G_HYBRID_MAP);
	},
	
	cargaDefectoUbicacionActual: function(){
		mapaGoogle.datos.cargarUbicacionActual = true;
	},
	
	cargaDefectoUbicacionDefecto: function(){
		mapaGoogle.datos.cargaDefectoUbicacionDefecto = true;
	},
	
	cambiaDireccion: function(indice, event){
		if(indice<0 || indice>=mapaGoogle.datos.direcciones.length)
			return false;
	
		var dir = mapaGoogle.datos.direcciones[indice];
		mapaGoogle.datos.mapa.setCenter(new GLatLng(dir.lon, dir.lat), (dir.zoom==null?mapaGoogle.datos.zoomDefecto:dir.zoom)); 
		if(event!=null)
			event.preventDefault();
	}, 
	
	cargaDatosMapaLimitesActuales: function(){
		var centro = mapaGoogle.funciones.getCenterMapa();
		var limites = mapaGoogle.funciones.getLimitesMapa();
		var url = "../api/js.php?latitud="+centro.latitud+"&longitud="+centro.longitud+"&nolat="+limites.no.lat()+"&nolong="+limites.no.lng()+"&swlat="+limites.se.lat()+"&swlong="+limites.se.lng()+"&sspn="+mapaGoogle.datos.mapa.getBounds().toSpan().toUrlValue();
		var puntos = mapaGoogle.datos.puntos;
		
		//Ahora en función de los grupos seleccionados generamos el parametro de grupos
		if(jQuery('div#mapaAdministracionGrande').length > 0){
			var strGrupos = "todos";
		}else{
			var strGrupos = "-1";
			if(mapaGoogle.datos.grupoSeleccionado == null){
				var grupos = jQuery('input.selectorGrupo');
				for(i=0; i<grupos.length; i++){
					var grupo = grupos[i];
					if(grupo.checked){
						strGrupos += ","+grupo.value;
					}
				}
			}else{
				strGrupos += ","+mapaGoogle.datos.grupoSeleccionado;
			}
		}
		url += "&grupos="+strGrupos;
		//alert(url);

		//Eliminamos los puntos anteriores
		for(i=0; i<puntos.length; i++){
			mapaGoogle.datos.mapa.removeOverlay(puntos[i]);
		}
		mapaGoogle.datos.mapa.puntos = new Array();

		//Cargamos los nuevos puntos
		jQuery.getScript(url, function(){
			//jQuery('#caja2Categorias').html(url);
		});
	}
};


/* Datos Propios */
//mapaGoogle.controlMapaPequenio();
//mapaGoogle.vistaMiniatura();
//mapaGoogle.cargaDefectoUbicacionActual();
mapaGoogle.cargaDefectoUbicacionDefecto();

/* Eventos */
window.onload = mapaGoogle.funciones.mapaCargado;
window.onunload = GUnload;
