function CMap(){
	
	var map;
	
	var CenterLat 	= 42.599851; 
	var CenterLon 	= -5.572815;//-3.713379;
	var StartScale 	= 12;
	
	var gmapNavControl;
	var gmapScaleControl;
	var gmapOverviewControl;
	var gmapDragZoomControl;
	
	var myMapLayer      = [];			// Holds the kml layer displayed in the Maps COM.
    var myEarthLayer    = [];			// Holds the kml layer displayed in the GE API.
    var ge  			= null;			// The instance of the GE API.
    
    var markers = [];
    var infoWindows = [];
    var markerListeners = [];
	
	var ultimaCapaCargada = 1;
	
	this.init = function ()
	{
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("mapDiv"), {mapTypes: [G_PHYSICAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP,G_NORMAL_MAP,G_SATELLITE_3D_MAP]});       

			//var yCont = new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(25,25));
			//map.addControl(new GMapTypeControl());
			//zCont = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(25,75));
			//gmapNavControl = new GLargeMapControl();			
			//map.addControl(gmapNavControl,zCont);
			//gmapScaleControl = new GScaleControl();
			//map.addControl(gmapScaleControl);			
			//gmapOverviewControl = new GOverviewMapControl();
			//map.addControl(gmapOverviewControl);		
   
			map.setCenter(new GLatLng(CenterLat, CenterLon), StartScale,G_SATELLITE_3D_MAP);
			map.enableContinuousZoom();
			map.enableScrollWheelZoom();
			
			map.setUIToDefault();  
				
			// Boton zoom a rectangulo
			var otherOpts = {
				buttonStartingStyle: {background: '#FFF'},
				buttonHTML: '<img title="Seleccionar zoom" src="./images/icon/dragZoom/zoom-button.gif">',
				buttonStyle: {width:'24px', height:'24px'},
				buttonZoomingHTML: '<img title="Seleccionar zoom" src="./images/icon/dragZoom/zoom-button-activated.gif">',
				buttonZoomingStyle: {width:'24px', height:'24px'},
				backButtonHTML: '<img title="Zoom anterior" src="./images/icon/dragZoom/zoom-button-less.gif">',
				backButtonStyle: {display:'none',width:'24px', height:'24px'},
				backButtonEnabled: true,
				overlayRemoveTime: 1500
			}
			gmapDragZoomControl = new DragZoomControl({}, otherOpts, {});
			zrPos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(80,25));
			map.addControl(gmapDragZoomControl, zrPos);	
			
			map.getEarthInstance(getEarthInstance);
			
			this.startupEarthLayer();
		}
	}
	//-----------------------------------------------------------------------------------------
    // Get the instance of the GE API map - ge is global, so it can be used anywhere needed.
    //-----------------------------------------------------------------------------------------
    var getEarthInstance = function(object) {
    	ge = object;
	    var navControl = ge.getNavigationControl(); 
		navControl.setVisibility(ge.VISIBILITY_AUTO);
	}
    // Lanzado al pulsar uno de los checkbox de las capas	  
	this.changeLayer = function(idLayer,checked){
		if(idLayer<100){ // idLayer < 100 = capa a mostrar en el mapa
			//console.debug(idLayer);
			myKMLURL = listaKml.getElto(idLayer).getUrl();
	        changePolys(idLayer,myKMLURL,true,checked);
		} else if (idLayer>=100 && idLayer<1000){ // idLayer >= 100 y < 1000 = mapa base
			if(checked=true){
				switch(idLayer){
					case 100:
						map.setMapType(G_PHYSICAL_MAP);
					break;
					case 101:
						map.setMapType(G_SATELLITE_MAP);
					break;
					case 102:
						map.setMapType(G_HYBRID_MAP);
					break;
					case 103:
						map.setMapType(G_NORMAL_MAP);
					break;					
					case 104:
						map.setMapType(G_SATELLITE_3D_MAP);
					break;					
				}
			}
		} else if (idLayer>=1000 && idLayer<10000){ // idLayer >= 1000 = capa de "la tierra"
			cambiaCapaEarth(idLayer,checked);
		}
	}
	this.centerItem = function(lat,lon){
		var latlng;
		if(lat>lon){
			latlng = new GLatLng(lat,lon);
		} else {
			latlng = new GLatLng(lon,lat);
		}
    	//console.debug(lat + " - " + lon);
    	map.setCenter(latlng,15);
    }
	
	// NOTE: We can't immediately add the polygon to the Earth layer because it may not have
	//       finished loading, causing an 'object not found' error to be thrown.  The
	//       startupEarthLayer catches and handles the error.
	this.startupEarthLayer = function () {
		var myKMLURL;
		try {
	            // Acciones al inicializar el mapa
                myKMLURL = listaKml.getElto(1).getUrl();
					changePolys(1,myKMLURL,true,true);
	            /*myKMLURL = listaKml.getElto(2).getUrl();
					changePolys(2,myKMLURL,false,true);
				myKMLURL = listaKml.getElto(4).getUrl();
					changePolys(4,myKMLURL,false,true);
				myKMLURL = listaKml.getElto(5).getUrl();
					changePolys(5,myKMLURL,false,true);*/
				// Fronteras
				cambiaCapaEarth(1001,true);
		}
		catch(err) { setTimeout("objMap.startupEarthLayer()",2000);}
	}
	this.detectMapType = function() {
	      var myMapType = this.map.getCurrentMapType();
	      var myTypeName = myMapType.getName();
	      return myTypeName;
	}
	//-----------------------------------------------------------------------------------------
    // changePolys - Replaces polygons on Map and Earth layers.
    // If kmlURL is null it only deletes the existing polygon.  The two calls to removePoly...
    // check to see if the global variables are set; if they are not null there is a
    // polygon displayed, so it is deleted and the global variable is set to null.
    // New polygons are loaded after the delete if kmlURL is set, by setting myMapLayer or
    // myEarthLayer in addPolyToMap or addPolyToEarth, respectively.  Since these are global
    // variables, we can toggle them at will by calling this routine with or without kmlURL.
    // The flyToIt variable is a boolean that's passed through to the routines that add the
    // .kml layers to the map or earth map types.  If it's set to true, the map or Earth api
    // will zoom to the extent of the .kml layer using either gotoDefaultViewport(map) for the
    // regular map types, or set flyToView(true) for the Earth map type.
    //-----------------------------------------------------------------------------------------
    var changePolys  = function(id, kmlURL, flyToIt, checked) {
	  if(ultimaCapaCargada!=0){
		map.clearOverlays();
		removePolyFromEarth(ultimaCapaCargada);
		//console.debug("remove " + ultimaCapaCargada);
		ultimaCapaCargada=id;
		//console.debug("nueva " + ultimaCapaCargada + " - " + myKMLURL);
	  }
      if(kmlURL != null)            {
            if(checked){
             	myEarthLayer[id]= addPolyToEarth(kmlURL, flyToIt);
             	addPolyToMap(id,kmlURL, flyToIt);
            } else {
              	removePolyFromEarth(id);
              	removePolyFromMap(id);
            }
        }        
    }
    
    //-----------------------------------------------------------------------------------------
    // addPolyToMap - Adds a polygon kml to the Google Maps COM.  If flyToIt is true we zoom.
    //-----------------------------------------------------------------------------------------
    var addPolyToMap = function(id,kmlURL, flyToIt) {
      	myMapLayer[id] = new GGeoXml(kmlURL);
      	map.addOverlay(myMapLayer[id]);
      	//if (flyToIt == true) { myMapLayer.gotoDefaultViewport(this.map); }
    }

    //-----------------------------------------------------------------------------------------
    // removePolyFromMap - Removes a polygon on the Google Maps COM
    //-----------------------------------------------------------------------------------------
    removePolyFromMap = function(id) {
      	if (myMapLayer[id] != null)
         	{map.removeOverlay(myMapLayer[id]);
          	myMapLayer[id] = null;
        }
    }
    //-----------------------------------------------------------------------------------------
    // addPolyToEarth - Add networked kml file to the GE API - this is Google's getNL routine.
    //-----------------------------------------------------------------------------------------
    addPolyToEarth = function(kmlURL, flyToIt){
     	var nl = ge.createNetworkLink("");
      	if (flyToIt == true) { nl.setFlyToView(true); }  // Zooms to the .kml view extent...
      	var link = ge.createLink("");
      	link.setHref(kmlURL);
      	nl.setLink(link);
      	ge.getGlobe().getFeatures().appendChild(nl);
      	return nl;
    }

    //-----------------------------------------------------------------------------------------
    // removePolyFromEarth - Removes a polygon from the GE API
    //-----------------------------------------------------------------------------------------
    removePolyFromEarth = function(id) {
      	if (myEarthLayer[id] != null)
        	{ge.getGlobe().getFeatures().removeChild(myEarthLayer[id]);
          	myEarthLayer[id]=null;
        }
    }
    // Cambia las opciones específicas de las capas de Google Earth
    var cambiaCapaEarth = function(idLayer,checkeado){
        switch(parseInt(idLayer)){
           case 1000:
             ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, checkeado);
           break;
           case 1001:
             ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, checkeado);
           break;
           case 1002:
             ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, checkeado);
           break;
           case 1003:
             ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, checkeado);
           break;
        }
    }
    var cargaMarkers = function(idLayer, checked){
    	var store = objGrid1.getStore();
    	auxGlobal = store;
    	icon = new GIcon();
        icon.shadow = './images/icon/transparente.png';
        icon.iconSize = new GSize(20,20);
        icon.shadowSize = new GSize(1, 1);
        icon.iconAnchor = new GPoint(10, 10);
        icon.infoWindowAnchor = new GPoint(10, 1);
        var point;
        var infoHTML;
    	for(var i=0;i<store.data.length;i++){

        	icon.image = './images/icon/wwtp.png';
        	//console.debug(store.data.items[i].data.CALIDAD);
    	    if(store.data.items[i].data.CALIDAD == "Muy deficiente"){
    	       	icon.image = './images/icon/red.png';
    	    }else if(store.data.items[i].data.CALIDAD == "Insuficiente"){
    	      	icon.image = './images/icon/orange.png';
    	    }else if(store.data.items[i].data.CALIDAD == "Adecuada"){
    	       	icon.image = './images/icon/green.png';
    	    }       
    	    
    		//console.debug(store.data.items[i].data.LOCALIDAD);
    		if(store.data.items[i].data.LAT < store.data.items[i].data.LON){
            	point = new GLatLng(store.data.items[i].data.LON,store.data.items[i].data.LAT);
    		} else {
    			point = new GLatLng(store.data.items[i].data.LAT,store.data.items[i].data.LON);
    		}
    		markers[store.data.items[i].data.ID_PU] = new GMarker(point,icon);
    		//infoHTML = getInfoWindow(store.data.items[i].data);
    		//markers[store.data.items[i].data.ID_PU].bindInfoWindowHtml(infoHTML);

    		map.addOverlay(markers[store.data.items[i].data.ID_PU]);
    	}
    	auxGlobal= store;
    }
    var getInfoWindow = function(data){
    	
    	var auxnom08 = data.NOM / data.POB * 100;
    	
    	var ret='<style type="text/css"> .Estilo1 {font-family: Verdana, Arial, Helvetica, sans-serif}';
    	ret=ret+'.Estilo2 {font-size: x-small} .Estilo3 {font-family: Verdana, Arial, Helvetica, sans-serif; ';
    	ret=ret+'font-size: 9px; } .Estilo4 {font-size: x-small; font-family: Verdana, Arial, Helvetica, ';
    	ret=ret+'sans-serif; } .Estilo5 { font-size: 36px; color: #CCFF66; } .Estilo7 {font-size: 36px; ';
    	ret=ret+'color: #66CCFF; } .Estilo8 {font-size: 36px; color: #CCCC66; } .Estilo9 {font-size: 36px; ';
    	ret=ret+'color: #CC99FF; } .Estilo11 { font-size: 36px; color: #FF9999; } .Estilo12 { font-family: ';
    	ret=ret+'Verdana, Arial, Helvetica, sans-serif; font-weight: bold; font-size: 13px; } .Estilo14 ';
    	ret=ret+'{font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold; } </style> <table ';
    	ret=ret+'width="429" border="0"> <tr> <td colspan="4"><p align="center" class="Estilo12">Atlas del ';
    	ret=ret+'saneamiento y depuraci&oacute;n de provincia de Le&oacute;n</p></td></tr><tr><td width="163">';
    	ret=ret+'<a href="http://www.dipuleon.es"></a></td><td colspan="3"><div align="right">';
    	ret=ret+'<a href="http://www.dipuleon.es"><img src="http://www.fundacion-fundaspe.com/imagenes/patrocinadores/dipuleon.jpg" ';
    	ret=ret+'alt="Diputaci&oacute;n de Le&oacute;n" width="131" height="68" border="0" longdesc="Diputaci&oacute;n ';
    	ret=ret+'de Le&oacute;n"></a></div></td></tr><tr><td class="Estilo2"><div align="right" class="Estilo1">';
    	ret=ret+'<span class="Estilo2">Municipio:</span></div></td><td colspan="3"><span class="Estilo1">' + data.MUNICIPIO;
    	ret=ret+'</span></td></tr><tr><td class="Estilo2"><div align="right" class="Estilo1"><span class="Estilo2">';
    	ret=ret+'Localidad:</span></div></td><td colspan="3"><span class="Estilo14">' + data.LOCALIDAD + '</span></td>';
    	ret=ret+'</tr><tr><td colspan="4" class="Estilo2"><div align="right"><hr /></div></td></tr><tr>';
    	ret=ret+'<td align="center" class="Estilo12"><div align="left">Poblaci&oacute;n</div></td></tr><tr>';
    	ret=ret+'<td height="42" class="Estilo2"><div align="right" class="Estilo1">Nomenclator  2008:</div>';
    	ret=ret+'</td><td width="72" class="Estilo1"><div align="right">' + data.NOM + '</div></td><td width="180" ';
    	ret=ret+'colspan="2" rowspan="2" class="Estilo1"><img src="http://chart.apis.google.com/chart?chs=250x100&amp;';
    	ret=ret+'chd=t:' + auxnom08 + ',100&amp;chco=4d89f9|c6d9fd&amp;cht=bhg&amp;chl=0|100%"alt="Población" width="180" ';
    	ret=ret+'height="78" /></td></tr><tr><td height="23" class="Estilo2"><div align="right" class="Estilo4">';
    	ret=ret+'Poblaci&oacute;n estacional m&aacute;xima:</div></td><td class="Estilo1"><div align="right">' + data.POB;
    	ret=ret+'</div></td></tr><tr><td colspan="4" class="Estilo4"><div align="center"><hr /></div></td>';
    	ret=ret+'</tr><tr><td colspan="4" class="Estilo12"></td></tr><tr><td colspan="4" ';
    	ret=ret+'class="Estilo4" align="center"></div></td></tr><tr><td height="31" class="Estilo2">&nbsp;</td><td colspan="3" ';
    	ret=ret+'class="Estilo1"><a href="http://localhost/mapti/pdfs/' + data.ID_PU + '.pdf" class="Estilo2">Descargar anexo ';
    	ret=ret+'fotogr&aacute;fico en pdf <img src="http://fullreset.es/ijm/vino_pdfs/pdf_ico.gif" alt="pdf" width="20" ';
    	ret=ret+'height="18" longdesc="pdf"></a></td></tr><tr><td height="31" colspan="4" class="Estilo2"><hr /></td></tr>';
    	ret=ret+'<tr><td colspan="4" ><p align="justify" ><font style="font-size:9px;font-family:Verdana, Arial, Helvetica, ';
    	ret=ret+'sans-serif">Situaci&oacute;n  actual de los sistemas de saneamiento y depuraci&oacute;n en la provincia de ';
    	ret=ret+'Le&oacute;n (2004/2005)<br />ATLAS DEL SANEAMIENTO Y DEPURACI&Oacute;N DE PROVINCIA DE LE&Oacute;N, creado ';
    	ret=ret+'en la FASEII del proyecto: &ldquo;An&aacute;lisis de la situaci&oacute;n del sistema de depuraci&oacute;n ';
    	ret=ret+'de agua residual de los municipios de Le&oacute;n con menos de 20.000 habitantes&rdquo;, Proyecto de ';
    	ret=ret+'Investigaci&oacute;n financiado por la Diputaci&oacute;n Provincial de Le&oacute;n y desarrollado por el ';
    	ret=ret+'Instituto de Medio Ambiente, Recursos Naturales y Biodiversidad de la Universidad de Le&oacute;n.</font>';
    	ret=ret+'</td></tr></table><p>&nbsp;</p>';
    	
    	return ret;
    }
} 

