/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// Global constants and variables
var mapMinZoom = 4;
var mapMaxZoom = 14;
var opacity = 0.85;
var mapInitLat = 35.87;
var mapInitLong = -7.53;
var mapInitZoom = 4;
var mapBoundsSpain = new GLatLngBounds(new GLatLng(35.0351514998, -9.63102756269), new GLatLng(44.1038778978, 5.08104007001));
var mapBoundsCanaryIsland = new GLatLngBounds(new GLatLng(27.2900525871, -21.3777606911), new GLatLng(29.5276992697, -13.0012394878));
var mercator = new GMercatorProjection(mapMaxZoom+1);

var tileLayerSpainGSM;
var tileLayerSpainUTMS;
var tileLayerCanaryIslandGSM;
var tileLayerCanaryIslandUMTS;
var overlaySpainGSM;
var overlaySpainUMTS;
var overlayCanaryIslandGSM;
var overlayCanaryIslandUMTS;
var map;
var temp;
var zoomBars;
var panLeft;
var panRight;
var panUp;
var panDown;
var zoomSelDiv;
var divZoomIn;
var divZoomOut;
var divUpArrow;
var divRightArrow;
var divDownArrow;
var divLeftArrow;
var moveUpListener;
var moveLeftListener;
var moveDownListener;
var moveRightListener;


/**
 * Function: geocodeKey
 * If enter was pressed, geocode
 **/
function geocodeKey(e)
{

	var keynum;

	if(window.event) { //IE
		keynum = e.keyCode
	}
	else if(e.which) {// Netscape/Firefox/Opera
		keynum = e.which
	}
	//13 ascii for carriage return
	if (keynum == 13) {
		geocode();
	}
}

/**
 * Function: geocode
 * Get geographic code for a given address
 **/
function geocode()
{
	var address = document.getElementById("donde").value + ", spain";

	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode("ES");

	geocoder.getLocations(address, processLocations);
}

/**
 * Function: processLocations
 * Process the geocode search results
 **/
function processLocations(result)
{
	if (!result || result.Status.code != 200) {
		document.getElementById("quisiste_decir").innerHTML=
			"<P>Lo sentimos, su b&uacute;squeda no ha devuelto ning&uacute;n resultado.</P>";

	} else {
		// ===== If there was a single marker =====

		if (result.Placemark.length == 1) {
			var p = result.Placemark[0].Point.coordinates;
			place(p[1],p[0]);
		}

		// Less than 3 markers, "Did you mean" list.
		else if (result.Placemark.length < 3) {

			document.getElementById("quisiste_decir").innerHTML = "<P id='opciones_busqueda'>Quisiste decir:";

			// Loop through the results
			for (var i=0; i<result.Placemark.length; i++) {

				var p = result.Placemark[i].Point.coordinates;

				document.getElementById("quisiste_decir").innerHTML
					+= "<a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"</a><br/>";
			}

			document.getElementById("quisiste_decir").innerHTML += "</P>";
		}
		else
		{
			document.getElementById("quisiste_decir").innerHTML =
				"<P>Lo sentimos, su b&uacute;squeda ha devuelto demasiados resultados. Int&eacute;ntelo de nuevo.</P>";
		}


	}
}

/**
 * Function: place
 * Center the map at given coordinates
 **/
function place(lat, lng) 
{
	var point = new GLatLng(lat,lng);
	map.setCenter(point,14);
	adjustCurrentZoom();
	document.getElementById("quisiste_decir").innerHTML = "";
}


/**
 * Function: goTo
 * Center the map at region's coordinates
 **/
function goTo() 
{
	var val = document.getElementById("comunidades").value;
	var currentZoom = map.getZoom();

	if (val == 0) {
		return;
	} else if (val == 1) { // Canarias

		//map.panTo(new GLatLng(28,272120, -15.806278));
		map.setCenter(new GLatLng(28.272120, -15.806278), 7);

	} else if (val == 2) { // Madrid

		map.setCenter(new GLatLng(40.457090, -3.68944), 8);

	} else if (val == 3) { // Catalu�a

		map.setCenter(new GLatLng(41.842124, 1.866443), 7);

	} else if (val == 4) { // Asturias

		map.setCenter(new GLatLng(43.321808, -5.940076), 8);


	} else if (val == 5) { // Galicia

		map.setCenter(new GLatLng(42.825391, -7.923149), 7);


	} else if (val == 6) { // Valencia

		map.setCenter(new GLatLng(39.409731, -0.529413), 7);


	} else if (val == 7) { // Andalucia

		map.setCenter(new GLatLng(37.385567, -4.665814), 7);

	} else if (val == 8) { // Cantabria

		map.setCenter(new GLatLng(43.225126, -3.990950), 8);

	} else if (val == 9) { // Pais Vasco

		map.setCenter(new GLatLng(43.035163, -2.584692), 8);

	} else if (val == 10) { // Navarra

		map.setCenter(new GLatLng(42.757167, -1.755110), 8);

	} else if (val == 11) { // La Rioja

		map.setCenter(new GLatLng(42.278731, -2.564511), 8);

	} else if (val == 12) { // Arag�n

		map.setCenter(new GLatLng(41.516808, -0.450173), 7);

	} else if (val == 13) { // Castilla y Le�n

		map.setCenter(new GLatLng(41.839777, -4.701337), 7);

	} else if (val == 14) { // Extremadura

		map.setCenter(new GLatLng(39.119448, -6.081020), 7);

	} else if (val == 15) { // Castilla La Mancha

		map.setCenter(new GLatLng(39.554427, -2.803736), 7);

	} else if (val == 16) { // Murcia

		map.setCenter(new GLatLng(38.032276, -1.435140), 8);

	} else if (val == 17) { // Islas Baleares

		map.setCenter(new GLatLng(39.549816, 2.981277), 7);

	} else if (val == 18) { // Ceuta

		map.setCenter(new GLatLng(35.894050, -5.319567), 13);

	} else if (val == 19) { // Melilla

		map.setCenter(new GLatLng(35.293621, -2.938414), 13);
	}

	adjustCurrentZoom();
}

/**
 * Function: changeCoverage
 * Changes the coverage type to be shown
 **/
function changeCoverage(coverageType)
{
	if (coverageType == 'gsm') {
		// Hide umts layers
		overlaySpainUMTS.hide();
		overlayCanaryIslandUMTS.hide();
		
		// Show gsm layers
		overlaySpainGSM.show();
		overlayCanaryIslandGSM.show();
	}
	
	else if (coverageType == 'umts') {
		// Hide gsm layers
		overlaySpainGSM.hide();
		overlayCanaryIslandGSM.hide();			
		
		// Show umts layers
		overlaySpainUMTS.show();
		overlayCanaryIslandUMTS.show();	
	}
}

/**
 * Function: load
 * Load the map from Google
**/
function load()
{
    // Check compatibility
    if (GBrowserIsCompatible()) {        
		
		/** Create tile layers:
		  * - For Spain GSM
		  * - For Spain UMTS/HSDPA
		  * - For Canary Island GSM
		  * - For Canary Island UMTS/HSDPA
		  **/
		  
		//****** SPAIN GSM ********  
		tileLayerSpainGSM = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
		tileLayerSpainGSM.getTileUrl = function(tile,zoom) {
			              if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
			                  return "gmapscov_files/images/none.png";
			              } 
			              var ymax = 1 << zoom;
			              var y = ymax - tile.y -1;
			              var tileBounds = new GLatLngBounds(
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
			              );
			              if (mapBoundsSpain.intersects(tileBounds)) {
								return "gmapscov_files/tiles/gsm/Spain/" + zoom+"/"+tile.x+"/"+y+".png";								
			              } else {
			                  return "gmapscov_files/images/none.png";
			              }
			          }
		// IE 7-: support for PNG alpha channel
		// Unfortunately, the opacity for whole overlay is then not changeable, either or...
		tileLayerSpainGSM.isPng = function() { return true;};
		
		tileLayerSpainGSM.getOpacity = function() {  
			if( navigator.userAgent.indexOf ("MSIE 7") != -1) 
				return 1.0;
			else
				return opacity;  
		}
		/*************************/
		
		
		//****** SPAIN UMTS ********  
		tileLayerSpainUMTS = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
		tileLayerSpainUMTS.getTileUrl = function(tile,zoom) {
			              if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
			                  return "gmapscov_files/images/none.png";
			              } 
			              var ymax = 1 << zoom;
			              var y = ymax - tile.y -1;
			              var tileBounds = new GLatLngBounds(
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
			              );
			              if (mapBoundsSpain.intersects(tileBounds)) {
								return "gmapscov_files/tiles/umts/Spain/" + zoom+"/"+tile.x+"/"+y+".png";								
			              } else {
			                  return "gmapscov_files/images/none.png";
			              }
			          }
		// IE 7-: support for PNG alpha channel
		// Unfortunately, the opacity for whole overlay is then not changeable, either or...
		tileLayerSpainUMTS.isPng = function() { 			
			return true;			
		};
		
		tileLayerSpainUMTS.getOpacity = function() { 
			if( navigator.userAgent.indexOf ("MSIE 7") != -1) 
				return 1.0;
			else
				return opacity; 
		}		
		/**************************/
		
		//****** CANARY ISLAND GSM ********  
		tileLayerCanaryIslandGSM = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
		tileLayerCanaryIslandGSM.getTileUrl = function(tile,zoom) {
			              if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
			                  return "gmapscov_files/images/none.png";
			              } 
			              var ymax = 1 << zoom;
			              var y = ymax - tile.y -1;
			              var tileBounds = new GLatLngBounds(
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
			              );
			              if (mapBoundsCanaryIsland.intersects(tileBounds)) {
							return "gmapscov_files/tiles/gsm/CanaryIsland/" + zoom+"/"+tile.x+"/"+y+".png";							  						 
			              } else {
			                return "gmapscov_files/images/none.png";
			              }
			          }
		// IE 7-: support for PNG alpha channel
		// Unfortunately, the opacity for whole overlay is then not changeable, either or...
		tileLayerCanaryIslandGSM.isPng = function() { return true;};
		
		tileLayerCanaryIslandGSM.getOpacity = function() {  
			if( navigator.userAgent.indexOf ("MSIE 7") != -1) 
				return 1.0;
			else
				return opacity; 
		}			
		/********************************/
		
		//****** CANARY ISLAND UMTS ********
		tileLayerCanaryIslandUMTS = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
		tileLayerCanaryIslandUMTS.getTileUrl = function(tile,zoom) {
			              if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
			                  return "gmapscov_files/images/none.png";
			              } 
			              var ymax = 1 << zoom;
			              var y = ymax - tile.y -1;
			              var tileBounds = new GLatLngBounds(
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
			                  mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
			              );
			              if (mapBoundsCanaryIsland.intersects(tileBounds)) {
								return "gmapscov_files/tiles/umts/CanaryIsland/" + zoom+"/"+tile.x+"/"+y+".png";								
			              } else {
								return "gmapscov_files/images/none.png";
			              }
			          }
		// IE 7-: support for PNG alpha channel
		// Unfortunately, the opacity for whole overlay is then not changeable, either or...
		tileLayerCanaryIslandUMTS.isPng = function() { return true;};
		
		tileLayerCanaryIslandUMTS.getOpacity = function() {   
			if( navigator.userAgent.indexOf ("MSIE 7") != -1) 
				return 1.0;
			else
				return opacity;  
		}			
		/*********************************/
		
		// Now, we can add the overlays to the map
		overlaySpainGSM = new GTileLayerOverlay( tileLayerSpainGSM );
		overlaySpainUMTS = new GTileLayerOverlay( tileLayerSpainUMTS );
		overlayCanaryIslandGSM = new GTileLayerOverlay( tileLayerCanaryIslandGSM );
		overlayCanaryIslandUMTS = new GTileLayerOverlay( tileLayerCanaryIslandUMTS );
		
		
		// Limit zoom levels
		G_PHYSICAL_MAP.getMinimumResolution = function () { return 4 };
        G_NORMAL_MAP.getMinimumResolution = function () { return 4 };
        G_SATELLITE_MAP.getMinimumResolution = function () { return 4 };
        G_HYBRID_MAP.getMinimumResolution = function () { return 4 };

        G_PHYSICAL_MAP.getMaximumResolution = function () { return 14 };
        G_NORMAL_MAP.getMaximumResolution = function () { return 14 };
        G_SATELLITE_MAP.getMaximumResolution = function () { return 14 };
        G_HYBRID_MAP.getMaximumResolution = function () { return 14 }; 
		
		
		// Create map
		map = new GMap2(document.getElementById("map"));
		
		// Set type and center
        map.setMapType(G_HYBRID_MAP);
		map.setCenter(new GLatLng(mapInitLat,mapInitLong), mapInitZoom);
		
		// Add  controls
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
				
		// Add overlays
		map.addOverlay( overlaySpainGSM );
		map.addOverlay( overlaySpainUMTS );
		map.addOverlay( overlayCanaryIslandGSM );
		map.addOverlay( overlayCanaryIslandUMTS );
		
		// Hide umts layers by default
		overlaySpainUMTS.hide();
		overlayCanaryIslandUMTS.hide();
		
		// Show gsm layers by default
		overlaySpainGSM.show();
		overlayCanaryIslandGSM.show();

        //changeCoverage('umts');
		
		// hack for ie
		// correctPNG();
    }
    else {
        alert('Browser not compatible with Google Maps');
    }
}


