// JavaScript Document

// JavaScript Document
  //<![CDATA[
var map;
var listadirencontradas;
var directionsPanel;
var directions;
var listamarcas= new Array();
var mySpace = new GLatLngBounds;
var amarker;
var sw;
var cIcon = new GIcon();
cIcon.image = '/mapa/img/icobolagoogle.png';
cIcon.iconSize = new GSize(36,36);
cIcon.iconAnchor = new GPoint(18,18);
cIcon.infoWindowAnchor = new GPoint(18, 0);
markerOptions = { icon:cIcon };


function adddirecciones(id){
	
	geocoder = new GClientGeocoder();

	geocoder.getLatLng(listamarcas[id].dir,function(point)
				{
					if (!point)
					{
						if (listamarcas[id].sw){

						listamarcas[id].dir = listamarcas[id].dir.replace(/[0-9].*/g, '' );
						listamarcas[id].dir = listamarcas[id].dir.replace(/-.*\,/g, ',' );
						listamarcas[id].sw = false;
						adddirecciones(id);
						
						}
						

					  //alert(direccion + " not found");
	        	    } 
					else 
					{
	            	  
		              listamarcas[id].marca = new GMarker(point, markerOptions);
					  
					  GEvent.addListener(listamarcas[id].marca , "click", function() {
						listamarcas[id].marca.openInfoWindowHtml(listamarcas[id].info);
						
	});
		              map.addOverlay(listamarcas[id].marca );
					  mySpace.extend(listamarcas[id].marca.getPoint());
					  map.setCenter (mySpace.getCenter(),map.getBoundsZoomLevel(mySpace));
		             // marker.openInfoWindowHtml(info);
	    		    	        }
	    	      });
}

function adddireccionesP(id)
{
	listamarcas[id].marca = new GMarker(new GLatLng(listamarcas[id].punto[0], listamarcas[id].punto[1]), markerOptions);
	GEvent.addListener(listamarcas[id].marca , "click", function(){
						marker.openInfoWindowHtml(listamarcas[id].info);
						});
	map.addOverlay(listamarcas[id].marca);
	mySpace.extend(listamarcas[id].marca.getPoint());
	map.setCenter (mySpace.getCenter(),map.getBoundsZoomLevel(mySpace));
	// marker.openInfoWindowHtml(info);
}
	    	     
function repasadirecciones()
{
	for (var i = 0; i < listamarcas.length; i++)
	{
		listamarcas[i].sw = true;
		if(listamarcas[i].punto[0]!= null && listamarcas[i].punto[1] != null )
		{
			if(listamarcas[i].punto[0] > 0 && listamarcas[i].punto[1] > 0 )
			{
				adddireccionesP(i);
			}
			else
			{
				adddirecciones(i);
			}
		}
		else
		{
			adddirecciones(i);
		}
	}
}


function initialize(prov,pob)
{
	document.getElementById("route").style.visibility = "visible"; 
	map = new GMap2(document.getElementById("callejero"));
        
		map.setMapType(G_SATELLITE_MAP);
        var customUI = map.getDefaultUI();
        // Remove MapType.G_HYBRID_MAP
        map.setUI(customUI);
		map.removeMapType(G_PHYSICAL_MAP);
	var publisher_id = "ca-pub-9901108854508450";

	var adsManagerOptions = {
			maxAdsOnMap : 4,
			style: 'adunit',
			// The channel field is optional - replace this field with a channel number 
			// for Google AdSense tracking
			channel: '7899605428'  
		};

	adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
	//adsManager.enable();

	//map.addControl(new GSmallMapControl());
	//map.addControl(new GMapTypeControl());
	directions = new GClientGeocoder();
	directions.getLatLng("almeria" + ", " + "carboneras", function (point){
												map.setCenter(new GLatLng(36.997712,-1.890378), 15);;	
											});

	repasadirecciones();
    gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
	//setDirections("San Francisco", "Mountain View", "en_US");
}


function direcciones(address)
{
	directions.getLocations(address, addToMap);
}


function setDirections(fromAddress, toAddress )
{
	locale = 'es';
	gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
}



function handleErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (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: " + 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 (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}


function addToMap(response)
{
	if (response && response.Status.code == 200)
	{
		listadirencontradas = response;
		if (response.Placemark.length > 1)
		{
			var texto ;
		
			texto =   "<select id='Ldirecciones' onChange='ShowDireccion(this[this.selectedIndex].value)' size='" + response.Placemark.length + "' >";
			for (i=0;i<response.Placemark.length;i++)
			{ 
				texto += 	"<option label='" + response.Placemark[i].address +"' value='" + i + "' >"  + response.Placemark[i].address + "</option>";
			} 
			texto += '</select>';
			document.getElementById("listdirections").innerHTML = texto;
		}
		else
		{
			ShowDireccion(0);
		}
	}
	else
	{
		alert ("no se encuentra coincidencia");
	}
}


function ShowDireccion(indice)
{
	map.clearOverlays();
	//listadirencontradas.Placemark[indice].address
	var p = listadirencontradas.Placemark[indice].Point.coordinates;
	var marker = new GMarker(new GLatLng(p[1],p[0]));
	map.addOverlay(marker);
	marker.openInfoWindowHtml(listadirencontradas.Placemark[indice].address); 
	GEvent.addListener(marker,"click", function() { 
											marker.openInfoWindowHtml(listadirencontradas.Placemark[indice].address); 
										});
	//var p = result.Placemark[0].Point.coordinates;
	map.setCenter(new GLatLng(p[1],p[0]),14);
}


function createMarker(point,address) { 
       // h_icon.image = icon; 
	   marker = new GMarker(point)
        map.addOverlay(marker); 
        GEvent.addListener(marker,"click", function() { 
          marker.openInfoWindowHtml(address); 
        }); 
        //bounds.extend(point); 
      //  map.addOverlay(marker); 

} 
//]]>

