	
	
	/* Resetea los overlays (GMarker, GPolyline, GPolygon) cargados por la ficha personalizada */
	function resetFichaOverlays() {		
		if (fichaOverlays!= null) {
			/* Saco esos overlays del mapa */
			for (i=0; i<fichaOverlays.length; i++) {
				mapGM.removeOverlay(fichaOverlays[i]);
			}
			/* Vacio el array */
			fichaOverlays = [];			
		}
	}


	/* Control personalizado para hacer zoom con un rectangulo */
	/* Libreria opensource (No pertence al API Oficial de Google Maps) */
	function setupDragZoom() {
		//Estilos del rectangulo
		var boxStyleOpts = {
			opacity: .3,
			border: "2px dashed red"
		};

		//Estilos del boton y tiempo que tarda en desaparecer el rectangulo despues de hacer zoom
		var otherOpts = {
			buttonHTML: "<img style='position: absolute;' src='utilGM/dragZoomFiles/lupa.gif' />",
			buttonZoomingHTML: "<img style='position: absolute;' src='utilGM/dragZoomFiles/lupa_act.gif' />",
			buttonStartingStyle: {width: '0px', height: '0px'},
			overlayRemoveTime: 500
		};
		mapGM.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}));
		//Coloco el nuevo control a 50px por la izq, 72 por arriba
		new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 72));
		//Hack -> En este mapa en particular no se situa bien la capa oscura que marca el zoom activado (por el resize???)
		document.getElementById("gzoom-map-cover").style.marginTop="-40px";
		document.getElementById("gzoom-map-cover").style.marginRight="-3px";
	}


	/* Capa WMS: contiene el nombre y un valor booleano indicando si esta activa en el mapa o no */
	function capaWMS(nombre,activa) {
    	this.nombre = nombre
	    this.activa = activa
	}


	/* Crea un GMarker con sus listeners */
	function createMarker(point, featureType, geoid, displayText) { 
		marker = new GMarker(point,{icon: myicon, title: displayText});	
		fichaOverlays.push(marker);
		var last = fichaOverlays.length;
		GEvent.addListener(fichaOverlays[last-1], "click", function() {
			 popupGMWindow('GoToElementoMapa.do?feature='+featureType+'&geoid='+geoid,600,400);
		});	
		//Cambio el color del marker al pasar el raton por encima
	    GEvent.addListener(fichaOverlays[last-1], "mouseover", function() {
          	fichaOverlays[last-1].setImage(iconUrlOver);
        });
        GEvent.addListener(fichaOverlays[last-1], "mouseout", function() {
          	fichaOverlays[last-1].setImage(iconUrlDefault);
        });		   		    
		mapGM.addOverlay(fichaOverlays[last-1]);	
		
		/* ------------------------------------------------------------------------------------------------------------------------------------
			Abrimos un pop-up igual que en el applet porque las infoWindows(maximizable) de los GMarker no siempre quedan bien:
				- La ventana no se adapta al tamano de la tabla porque este no se puede predecir antes de renderizar la pagina 
		   		- Si recupero la pagina de forma asincrona, la css nueva estropea los estilos del sidebar
		   		- Construir el HTML en el controlador y devolverlo directamente sigue sin solucionar el problema del tamano de la ventana
		   ------------------------------------------------------------------------------------------------------------------------------------ */
		/*
		GEvent.addListener(fichaOverlays[last-1], 'click', function() {
          	var maxContentDiv = document.createElement('div');
	        maxContentDiv.innerHTML = 'Loading...'
          	fichaOverlays[last-1].openInfoWindowHtml("<div style='padding:5px'>Click maximize button for more details!</div>",
            	{maxContent: maxContentDiv, 
             	maxTitle: "Detalles"});

            var iw = mapGM.getInfoWindow();
            GEvent.addListener(iw, "maximizeclick", function() {
            	GDownloadUrl('GoToElementoMapa.do?feature='+featureType+'&geoid='+geoid, function(data) {
              	maxContentDiv.innerHTML = data;
            });
          });
        }); 
		*/	
	}


	/* Crea un GPolygon con sus listeners */
	function createPolygon(points, color, strokeWeight, strokeOpacity, opacity, featureType, geoid, displayText) {
		var polygon = new MyGPolygon(points,color,strokeWeight,strokeOpacity,color,opacity, displayText);
		fichaOverlays.push(polygon);
		var last = fichaOverlays.length;
		GEvent.addListener(fichaOverlays[last-1], "click", function(point) {
			 popupGMWindow('GoToElementoMapa.do?feature='+featureType+'&geoid='+geoid,600,400);
	    });
   		//Cambio el estilo del polygon al pasar el raton por encima
	    GEvent.addListener(fichaOverlays[last-1], "mouseover", function() {
	    	fichaOverlays[last-1].setStrokeWeight(strokeWeight*2);polygon.setFillOpacity(opacity/1.5)
	    });
   	    GEvent.addListener(fichaOverlays[last-1], "mouseout", function() {
   	    	fichaOverlays[last-1].setStrokeWeight(strokeWeight);polygon.setFillOpacity(opacity)
   	    });   	    	   	
		mapGM.addOverlay(fichaOverlays[last-1]);
	}


	/* Crea un GPolyline con sus listeners */
	function createPolyline(points, color, strokeWeight, strokeOpacity, featureType, geoid, displayText) {
		var polyline = new MyGPolyline(points,color,strokeWeight,strokeOpacity, displayText);      
		fichaOverlays.push(polyline);
		var last = fichaOverlays.length;
		GEvent.addListener(fichaOverlays[last-1], "click", function(point) {
			 popupGMWindow('GoToElementoMapa.do?feature='+featureType+'&geoid='+geoid,600,400);
	    });
   		//Cambio el estilo de la polyline al pasar el raton por encima
	    GEvent.addListener(polyline,"mouseover", function() {
	    	fichaOverlays[last-1].setWeight(strokeWeight*1.5);
	    });
   	    GEvent.addListener(polyline,"mouseout", function() {
   	    	fichaOverlays[last-1].setWeight(strokeWeight);
   	    });
   	    
   		mapGM.addOverlay(fichaOverlays[last-1]);
	}
	
	
	
	function ObtieneNombre() {	
		var nivel = mapGM.getZoom();	
		// NucCal: 1-2 Km
		if (nivel == 15) {
			return 'NucCall';
		}
		// Núcleo: 2-5 Km
		if (nivel == 14) {
			return 'Nucleo';
		}
		// MunNuc: 5-10 Km
		if (nivel == 13) {
			return 'MunNuc';
		}
		// Municipio: 10-25 Km
		if (nivel == 12) {
			return 'Municipio';
		}
		// Comarca: 25-45 Km
		if (nivel == 11) {
			return 'Comarca';
		}
		// ProcCom: 45-120 Km
		if (nivel == 10) {
			return 'ProCom';
		}
		// Provincia: 120-250 Km
		if (nivel == 9) {
			return 'Provincia';
		}
		// Todo: 250 Km
		if (nivel == 8) {
			return 'Todo';
		}		
		// Calle: < 1 Km
	    else {
			return 'Calle';
		}
	}
	

	/* Construye la peticion GetMap que se visualiza como un overlay sobre el mapa de Google Maps */
	function creaCapaWMS(url, nombre, estilo, mapName, mapRef) {
		var newTileAux= new GTileLayer(new GCopyrightCollection(""),8,17);
		newTileAux.myBaseURL=url;
		newTileAux.myLayers=nombre;
		//newTileAux.myStyles=estilo;
		newTileAux.getTileUrl=CustomGetTileUrl;
		newTileAux.myMapname=mapName;
		//newTileAux.getOpacity=function() { return 0.6; };
		/* Importante para que se vean las capas transparentes en IE6 */
		newTileAux.isPng=function() { return true; };  
		var newTileOverlayAux=new GTileLayerOverlay(newTileAux);
	
		//Si ya esta cargado el overlay lo quito
		eliminaCapaWMS();
	
		//Pongo el nuevo
		wmsOverlay=newTileOverlayAux;
		mapRef.addOverlay(wmsOverlay);
	}


	/* Elimina el overlay con las capas WMS */
	function eliminaCapaWMS() {
		if (wmsOverlay!=null) {
			mapGM.removeOverlay(wmsOverlay);
			wmsOverlay=null;
		}
	}


	/* Se invoca cuando cambia algun checkbox de la barra lateral (para anadir/eliminar capas) */
	function recargaCapa(nombreCapa, valor) {
		var capasIndiv=nombreCapa.split(',');
		
		for (i=0;i<capasIndiv.length;i++){
			
			var capaGoogle = capasIndiv[i].replace("eiel:","google:");
			
			if(valor) {
				arrayCapas[capaGoogle].activa=true;
			}
			else {
				 arrayCapas[capaGoogle].activa=false;
			}
		}
		//Recupero las capas activas ordenadas por prioridad
		var capasActivasActuales = getCapasActivasGetMap(",");
		//alert(capasActivasActuales);
		if (capasActivasActuales != null && capasActivasActuales != "") {
			creaCapaWMS(wmsUrl,capasActivasActuales, null, "mapGM", mapGM);
		} else {
			eliminaCapaWMS();
		}
	}
	
	
	/* Devuelve una lista de capas activas actuales en el mapa, con el separador pedido 
			- ',' para el GetMap que pinta en Google Maps 
			- ';' para Google Earth
	 */
	function getCapasActivasGetMap(separador){
	    capasActivasGetMap = "";
		first=true;
		for (i=0;i<arrayCapasOrdenadas.length;i++) {
		 	capaActual=arrayCapasOrdenadas[i];
			if (arrayCapas[capaActual].activa) {
				if (!first) capasActivasGetMap += separador + arrayCapasOrdenadas[i];
				else {
					capasActivasGetMap += arrayCapasOrdenadas[i];
					first=false;
				}
			}
		}
		return capasActivasGetMap;
	}

	
	/* Recalcula el tamano del mapa cuando se redimensiona la ventana del navegador */
	function resizeMapaParse() {
		var x, y;
		x= 500;
		y= 500;
		if (self.innerHeight) { // MOS
			y = self.innerHeight;
			x = self.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) { // IE6 Strict
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		} else if (document.body.clientHeight) { // IE quirks
			y = document.body.clientHeight;
			x = document.body.clientWidth;
		}
		x = x - 195;
		//y = y - 184;
		y = y - 25; //Ya no tengo la barra de herramientas
		document.getElementById("mapGM").style.width = x;
		document.getElementById("mapGM").style.height = y;
	
		mapGM.checkResize();	
	}


	/* Recalcula el tamano del mapa cuando se redimensiona la ventana del navegador */
	function resizeMapa() {
		var x, y;
		x= 500;
		y= 500;
		if (self.innerHeight) { // MOS
			y = self.innerHeight;
			x = self.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) { // IE6 Strict
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		} else if (document.body.clientHeight) { // IE quirks
			y = document.body.clientHeight;
			x = document.body.clientWidth;
		}
		x = x - 195;
		//y = y - 184;
		y = y - 25; //Ya no tengo la barra de herramientas
		document.getElementById("mapGM").style.width = x;
		document.getElementById("mapGM").style.height = y;
	}

	
	/* Devuelve la lista de capas activas en el mapa separadas por ';' para mostrar en Google Earth */
	function getActiveLayerNames(){	
		return this.getCapasActivasGetMap(";");	
	}


	function cambiaVisibilidad(elemento){
		var visibilidad = document.getElementById(elemento).style.display;

		var nombreSolapa = 'solapa'+elemento;
		if (visibilidad!='block') {
			document.getElementById(elemento).style.display='block';
			document.getElementById(nombreSolapa).style.background='#6caac6';
		} else{
			document.getElementById(elemento).style.display='none';
			document.getElementById(nombreSolapa).style.background='#0091b5';
		}
	}
	
	
	
	function changeImageSrc(imagen, src) {
		document.images[imagen].src=src;
	}


	function popupGMWindow(url,width,height) {
		options = "resizable=yes,scrollbars=yes,status=no,width="+width+",height="+height+",";
		options += "menubar=no,toolbar=no,location=no,directories=no";
		var newWin = window.open(url, 'ventanaDatos', options);
		if(newWin!=null){
			newWin.focus();
		}else{
			alert("Para poder visualizar los datos de las entidades del mapa debe deshabilitar el bloqueador de pop-ups");
		}
	}


	function popupWindow(url) {
		options = "resizable=yes,scrollbars=yes,status=no,width=800,height=600,";
		options += "menubar=no,toolbar=no,location=no,directories=no";
		var newWin = window.open(url, 'ventanaDatos', options);
		if(newWin!=null){
			newWin.focus();
		}else{
			alert("Para poder visualizar los datos de las entidades del mapa debe deshabilitar el bloqueador de pop-ups");
		}
	}


	function parteNombre(palabra) {
		var numeroCaracteres = 15
		var palabras = palabra.split(" ");
		palabra="";
		for(i=0;i<palabras.length;i++){
			var palabraAux = palabras[i];
			if(palabraAux.length>numeroCaracteres){
				if(palabraAux.indexOf("-")>0){
					palabraAux = palabraAux.replace("-","- ");
				}else{
					palabraAux = palabraAux.substring(0,numeroCaracteres)+" "+palabraAux.substring(numeroCaracteres,palabraAux.length);
				}
			}
			palabra = palabra + palabraAux + " ";
		}
		document.write(palabra);
	}
	
	
