// Funcionalidad Principal
var mapaGoogle = {
	datos: {
		mapa: null,
		geocoder: null,
		gdir: null,
		icono: null,
		anchoMiniDefecto: 130,
		altoMiniDefecto: 130,
		latitudDefecto: 37.40210783811313,
		longitudDefecto: -6.004800796508789,
		direcciones: new Array(),
		marcadores: new Array(),
		controles: new Array(),
		zoomDefecto: 15,
		urlIcono: "../includes/img/iconos/marker.png",
		urlSombraIcono: "../includes/img/iconos/sombraMarker.png",
		idMapa: "mapaGoogle",
		idLatitud: "idLatitud",
		idLongitud: "idLongitud",
		idDirecciones: "rutaAClinica",
		destino: 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(mapaGoogle.datos.latitudDefecto, mapaGoogle.datos.longitudDefecto), 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 = new GIcon();
				mapaGoogle.datos.icono.image = mapaGoogle.datos.urlIcono;
				mapaGoogle.datos.icono.shadow = mapaGoogle.datos.urlSombraIcono;
				mapaGoogle.datos.icono.iconSize = new GSize(28, 52);
				mapaGoogle.datos.icono.shadowSize = new GSize(50, 52);
				mapaGoogle.datos.icono.iconAnchor = new GPoint(14, 52);
				mapaGoogle.datos.icono.infoWindowAnchor = new GPoint(25, 10);
			}

			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];
				var point = new GLatLng(dir.lat, dir.lon);
				var marcador = mapaGoogle.funciones.nuevoMarcador(point, mapaGoogle.datos.icono, dir.titulo, dir.direccion, dir.arrastrable, dir.centrar);
				//mapaGoogle.datos.mapa.addOverlay(marcador);
				/*if(i==0){
					mapaGoogle.datos.mapa.setCenter(point, (dir.zoom==null?mapaGoogle.datos.zoomDefecto:this.zoom)); 
					marcador.openInfoWindowHtml(dir.texto);
				}*/
			}
			
			mapaGoogle.setMapaHibrido();
			
			return true;
		},
		
		calculaRuta: function(fromAddress, toAddress, locale) {
			if (fromAddress == null || fromAddress == "") {
				alert("Debe indicar una dirección de origen");
				return;
			}
			if (toAddress == null || toAddress == "") {
				alert("No ha seleccionado ningún destino");
				return;
			}
			mapaGoogle.datos.gdir.load("from: " + fromAddress + " to: " + toAddress,{"locale": (locale==null?"es":locale)});
		},
		
		manejadorErrores: function(){
			if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("No pudo encontrarse la localización geográfica correspondiente a una de las direcciones especificadas. Esto puede deberse a que la dirección es relativamente nueva, o incorrecta.\n Código de error: " + mapaGoogle.datos.gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("La petición de la ruta no ha podido ser procesada debido a causas desconocidas.\n Código de error: " + 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 (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("La clave proporcionada no es válida o no se corresponde con el dominio para el que fue concedida. \n Código de error: " + mapaGoogle.datos.gdir.getStatus().code);
			else if (mapaGoogle.datos.gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("Una de las direcciones no ha podido ser interpretada correctamente.\n Código de error: " + mapaGoogle.datos.gdir.getStatus().code);
			else 
				alert("Se ha producido un error desconocido.");
		},
		
		direccionCargada: function(){
			
		},
		
		nuevoMarcador: function(point, icono, titulo, direccion, arrastrable, centrar, zoom){
			var zoom = zoom==null?15:zoom;
			
			if(icono==null)
				var marcador = mapaGoogle.datos.marcador = new GMarker(point, {draggable: arrastrable});
			else
				var marcador = mapaGoogle.datos.marcador = new GMarker(point, {icon: icono , draggable: arrastrable});
				
			GEvent.addListener(mapaGoogle.datos.marcador , "click", function() {
				// Muestro la dirección y centro el mapa en el marcador
				marcador.openInfoWindowHtml("<b>" + titulo + "</b><br />" + direccion);				
				mapaGoogle.datos.mapa.setCenter(marcador.getLatLng(), 15);
				mapaGoogle.datos.destino = direccion;
			});
			
			if (arrastrable) {
				GEvent.addListener(marcador, "dragstart", function() {
		          	mapaGoogle.datos.mapa.closeInfoWindow();
		        });
		        GEvent.addListener(marcador, "dragend", function() {
		          	var lat = document.getElementById(mapaGoogle.datos.idLatitud);
		          	if (lat) {
		          		lat.value = marcador.getLatLng().lat();		          		
		          	}
		          	var lng = document.getElementById(mapaGoogle.datos.idLongitud);
		          	if (lng) {
		          		lng.value = marcador.getLatLng().lng();		          		
		          	}
		        });
		    }
			
			var lat = document.getElementById(mapaGoogle.datos.idLatitud);
          	if (lat) {
          		lat.value = point.lat();		          		
          	}
          	var lng = document.getElementById(mapaGoogle.datos.idLongitud);
          	if (lng) {
          		lng.value = point.lng();		          		
          	}
			
			mapaGoogle.datos.mapa.addOverlay(marcador);
			
			if (centrar) {
				mapaGoogle.datos.mapa.setCenter(point, zoom);
				// Además de centrar el mapa en el marcador, asigno su posición como destino para el cálculo de rutas
				mapaGoogle.datos.destino = direccion;			
			}
			
			mapaGoogle.datos.marcadores.push(marcador);
			
			return marcador;
		}, 
				
		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();
				    		}
							mapaGoogle
						    return mapaGoogle.funciones.nuevoMarcador(point, mapaGoogle.datos.icono, direccion, true, true, zoom);
				    	}
				  	}
				);
			}		
		}
		
	},
	
	nuevaDireccion: function(latitud, longitud, title, dir, z, drag, c) {
		mapaGoogle.datos.direcciones.push({lat:latitud, lon:longitud, titulo:title, direccion:dir, zoom:z, arrastrable: drag, centrar: c});
	},
		
	vistaMiniaturaTam: 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));
	},
	
	vistaMiniatura: function(){
		mapaGoogle.datos.controles.push(new GOverviewMapControl());
	},
	
	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);
	},
	
	activaZoomRaton: function(){
		mapaGoogle.datos.mapa.enableScrollWheelZoom();
	},
	
	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();
	}
};


/* Datos Propios */
//mapaGoogle.activaZoomRaton();
mapaGoogle.controlMapaGrande();
mapaGoogle.controlTipoMapa();

/* Eventos */
window.onload = mapaGoogle.funciones.mapaCargado;
window.onunload = GUnload;
