﻿/**
 * @autor : Iván Rodríguez Espada
 * @data  : 03/03/2008
 * @description : Geolocalizador que en base al campo de búsqueda indicado devuelve una lista de resultados.
 */
 
 /**
  * IMPORTANTE: Debe asignarse desde la página a la variable 
  * 'tipoSeccion' el valor de tipo de seccion 
  *	Valores posibles: tetd, rendicion, volcan
  */
 
var CAN = {};

CAN.Maps = {
	CountryCode : [],
	AdministrativeArea : [],
	SubAdministrativeArea : [],
	Locality : [],
	//--desarrollo
	//URI         			 : ['/markers1.xml?tipo='],
	//Presentación Fernando 04/04/2008
    //URI	        		 : ['/appsext/AppTETD08/GoogleMarkersEstatico.xml?tipo='],
   	//Definitivo(creacción xml en tiempo real)
	URI : '/google-markers.aspx?tipo=',

	map : null,

	markerManager : null,
	bounds : null,
	
	//icon : null,
	icons : new Object(),
	msg : null,
	
	/**
	 * G_NORMAL_MAP
	 * G_SATELLITE_MAP
	 * G_HYBRID_MAP
	 * G_PHYSICAL_MAP
	 * G_MOON_ELEVATION_MAP
	 * G_MOON_VISIBLE_MAP
	 * G_MARS_ELEVATION_MAP
	 * G_MARS_VISIBLE_MAP
	 * G_MARS_INFRARED_MAP
	 * G_SKY_VISIBLE_MAP
	 */
	//mapType 						 : G_NORMAL_MAP,
	
	// Opciones del mapa
	enableMapTypeControl     : false,
	enableContinuousZoom	 : true,
	enableDoubleClickZoom    : true,
	enableScrollWheelZoom    : true,
	enableGoogleBar          : false,
	enableOverviewMapControl : true,
	enableLargeMapControl    : true,
	
	//Niveles de zoom mínimo y máximo soportados por el mapa
	MIN_ZOOM_LEVEL : 2,
	MAX_ZOOM_LEVEL : 13,
	//Niveles de zoom en relación al área geográfica
	MIN_COUNTRYS_ZOOM_LEVEL : 2, //MIN_ZOOM_LEVEL
	MAX_COUNTRYS_ZOOM_LEVEL : 13, //MAX_ZOOM_LEVEL
	MIN_ADMINISTRATIVE_AREA_ZOOM_LEVEL : 5,
	MAX_ADMINISTRATIVE_AREA_ZOOM_LEVEL : 13, //MAX_ZOOM_LEVEL
	MIN_SUBADMINISTRATIVE_AREA_ZOOM_LEVEL : 8,
	MAX_SUBADMINISTRATIVE_AREA_ZOOM_LEVEL : 13, //MAX_ZOOM_LEVEL
	MIN_LOCALITY_ZOOM_LEVEL : 10,
	MAX_LOCALITY_ZOOM_LEVEL : 13, //MAX_ZOOM_LEVEL

    precargarImagen : function(imagen)
    {
        if (document.images)
        {
            var image = new Image();            
            image.src = imagen;
        }
    },
	
	// Crea un icono y lo añade a la colección de iconos
	addIcon : function(name, image)
	{
	    CAN.Maps.precargarImagen(image);
	    
	    var icon = new GIcon();
	    
        icon.image = image;

        icon.iconSize = new GSize(12, 14);														         
        icon.iconAnchor = new GPoint(12, 14);
        icon.infoWindowAnchor = new GPoint(9, 2);
        //Sombra del marker eliminada para mejorar rendimiento
        //icon.shadow = "/imgs/ico.shadow50.png";
        //icon.shadowSize = new GSize(37, 19);
        //icon.infoShadowAnchor = new GPoint(18, 25);        
        CAN.Maps.icons[name] = icon;
	},
		
	//Crea el marker y lo inicializa con los datos pasados por parámetro
	createMarker : function(numProjects, value, latitude, longitude, tag, id)
	{
	    var point = new GLatLng(latitude, longitude);
	    var icon = CAN.Maps.icons[tag];
		
		var options =
		{
		    name: id,
		    title: value,
		    icon: icon,
        	labelText: numProjects,
	        labelOffset: new GSize(0, -25),
	        labelClass: "num"
		};

		var marker = new LabeledMarker(point, options);
        				
		GEvent.addListener(marker, "click", function()
		{
  			window.location = '?levelType=' + tag + '&value=' + value;
		});
		
		return marker;
	},
    
    loadMarkerManager : function()
    {
	    CAN.Maps.markerManager = new MarkerManager(CAN.Maps.map);
			
	    CAN.Maps.markerManager.addMarkers(
	        CAN.Maps.CountryCode,
	        CAN.Maps.MIN_COUNTRYS_ZOOM_LEVEL,
	        CAN.Maps.MAX_COUNTRYS_ZOOM_LEVEL);
	    
	    CAN.Maps.markerManager.addMarkers(
	        CAN.Maps.AdministrativeArea,
	        CAN.Maps.MIN_ADMINISTRATIVE_AREA_ZOOM_LEVEL,
	        CAN.Maps.MAX_ADMINISTRATIVE_AREA_ZOOM_LEVEL);
	    
	    CAN.Maps.markerManager.addMarkers(
	        CAN.Maps.SubAdministrativeArea,
	        CAN.Maps.MIN_SUBADMINISTRATIVE_AREA_ZOOM_LEVEL,
	        CAN.Maps.MAX_SUBADMINISTRATIVE_AREA_ZOOM_LEVEL);
	    
	    CAN.Maps.markerManager.addMarkers(
	        CAN.Maps.Locality,
	        CAN.Maps.MIN_LOCALITY_ZOOM_LEVEL,
	        CAN.Maps.MAX_LOCALITY_ZOOM_LEVEL);
	        
	    CAN.Maps.markerManager.refresh();
    },
		
	init : function() {
		if (GBrowserIsCompatible()) {
            // Creación de los diferentes iconos que tendrán los puntos a dibujar
            /*
            CAN.Maps.addIcon("Countrys", "/imgs/ico.flecha-roja-abajo.png");
            CAN.Maps.addIcon("AdministrativeAreas", "/imgs/ico.flecha-verde-abajo.gif");
            CAN.Maps.addIcon("SubAdministrativeAreas", "/imgs/ico.flecha-morada-abajo.gif");
            CAN.Maps.addIcon("Locality", "/imgs/ico.flecha-azul-abajo.gif");
            */
         CAN.Maps.addIcon("Countrys", "/imgs/ico.flecha-rojo-abajo.gif");
			CAN.Maps.addIcon("AdministrativeAreas", "/imgs/ico.flecha-rojo-abajo.gif");
			CAN.Maps.addIcon("SubAdministrativeAreas", "/imgs/ico.flecha-rojo-abajo.gif");
			CAN.Maps.addIcon("Locality", "/imgs/ico.flecha-rojo-abajo.gif");
			
			// Configuración de los niveles máximos y mínimos de zoom
			G_NORMAL_MAP.getMinimumResolution = function() {return CAN.Maps.MIN_ZOOM_LEVEL;}
			G_NORMAL_MAP.getMaximumResolution = function() {return CAN.Maps.MAX_ZOOM_LEVEL;}
			
			//Barra "LocalSearch" - inicio
			var div = new Element('div');			
			var opts = {resultList : div, suppressInitialResultSelection : true, showOnLoad: true, 
			onMarkersSetCallback: function(markers) {
				for(var i = 0; i < markers.length; i++) {
					markers[i]['marker'].hide();
				}
			}, 
			onGenerateMarkerHtmlCallback : function(marker, node, result) {
				marker.hide();	
				marker.closeInfoWindow();			
				return node;
			},			
			onSearchCompleteCallback : function(gs) {
				return null;
			}};
			//Barra "LocalSearch" - fin

			this.map = new GMap2($('map'), {googleBarOptions: opts});
			GEvent.addListener(this.map, 'load', function() {
				CAN.Maps.msg.hide(); // Oculta el mensaje de cargando...
			});
			
			var msg = function(msg) {
				this.hidden = false;
				this.msg   = msg;
			};
			msg.prototype = new GOverlay();
			msg.prototype.initialize = function(map) {
				var div = document.createElement("div") ;
				div.innerHTML = this.msg;
				div.style.position = "absolute" ;
				div.style.margin = "10px";
				this.div_ = div;
				this.map_ = map;
				//map.getPane(G_MAP_MAP_PANE).appendChild(div);				
				map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div);
				var z = 10000000000;
          	this.div_.style.zIndex = z;
			}
			msg.prototype.remove = function() {
				console.log(this.div_);
				this.div_.parentNode.removeChild(this.div_);
			}			
			msg.prototype.redraw = function(force) {
	      }
   	   msg.prototype.show = function() {
				if (this.div_) {
					this.div_.style.display="";
					this.redraw();
				}
				this.hidden = false;
			}      
      	msg.prototype.hide = function() {
        		if (this.div_) {
          		this.div_.style.display="none";
        		}
        		this.hidden = true;
      	}
			
			//Añade info "Cargando..." mientras se prepara el mapa
			CAN.Maps.msg = new msg("Cargando...");			
			this.map.addOverlay(CAN.Maps.msg);
			
	  		if(CAN.Maps.enableLargeMapControl)
	  			this.map.addControl(new GLargeMapControl());
	  			
	  		if(CAN.Maps.enableOverviewMapControl)	
				this.map.addControl(new GOverviewMapControl());
			
			if(CAN.Maps.enableMapTypeControl)	
				this.map.addControl(new GMapTypeControl());
			
			if(CAN.Maps.enableContinuousZoom)
				this.map.enableContinuousZoom();
				
			if(CAN.Maps.enableDoubleClickZoom)
      		    this.map.enableDoubleClickZoom();
      	
      	    if(CAN.Maps.enableScrollWheelZoom)
	      	    this.map.enableScrollWheelZoom();

            if(CAN.Maps.enableGoogleBar)
                this.map.enableGoogleBar();
	      	
          	new GKeyboardHandler(this.map);

            this.map.savePosition();
  			
  			this.map.setCenter(
  			    new GLatLng(43.2917022705, -2.1622467041), 
  			    CAN.Maps.MIN_ZOOM_LEVEL, G_NORMAL_MAP);
		    
			GDownloadUrl(CAN.Maps.URI + tipoSeccion, function(data) 
		    {
			    //console.log(xmls);
			    var xml = GXml.parse(data);
			    var markers = xml.documentElement.getElementsByTagName("marker");
			    //CAN.Maps.markers = xml.documentElement.getElementsByTagName("marker");
			    //console.log(CAN.Maps.markers.length);
						
			    for (var i = 0; i < markers.length; i++) 
			    {
				    //Identificación del marker
				    var tag = markers[i].parentNode.tagName;
				    var id = i + 1;
				    
                    //Decodificación XML (extrae los valores de XML)
				    var numProjects = markers[i].getAttribute("NumberOfProjects");
				    var value = markers[i].getAttribute("Value");
				    var latitude = parseFloat(markers[i].getAttribute("Latitude"));
				    var longitude = parseFloat(markers[i].getAttribute("Longitude"));
				    
				    //Generar marker
				    var marker = CAN.Maps.createMarker(numProjects, value, latitude, longitude, tag, id);
				
				    //Añadir marker al grupo correspondiente
				    if(tag == "Countrys")
				    {
				        CAN.Maps.CountryCode.push(marker);
				    }
				    else if(tag == "AdministrativeAreas")
				    {
				        CAN.Maps.AdministrativeArea.push(marker);
				    }
				    else if(tag == "SubAdministrativeAreas")
				    {
				        CAN.Maps.SubAdministrativeArea.push(marker);
				    }
				    else if(tag == "Locality")
				    {
				        CAN.Maps.Locality.push(marker);
				    }
				}//for												
			    
                CAN.Maps.loadMarkerManager();

			});//GDownloadUrl
		}
	}
};//CAN.Maps

window.addEvent('load', function() {
	setTimeout('CAN.Maps.init()', 0);
});

window.addEvent('unload', function() {
    GUnload();
});
