﻿var map;
var gdir;
var geocoder = null; 
var puntoInicial;

window.onload = function load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("slideMapa"));
		gdir = new GDirections(map, document.getElementById("indicaciones"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); 
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.addMapType(G_SATELLITE_3D_MAP);		

        map.setCenter(new GLatLng(41.595298,-0.936263), 16, G_HYBRID_MAP);
		map.enableScrollWheelZoom(); 

		var icon = new GIcon();
		icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);

		var point = new GLatLng(41.595298,-0.936263);
		puntoInicial = new GMarker(point, icon);
		map.addOverlay(puntoInicial);

		map.openInfoWindowHtml(new GLatLng(41.595298,-0.936263),"<p><font color='#0041ad'><strong><font size='3' face='Arial, Helvetica, sans-serif'>Remagua, S.L.</font></strong></font></p><font size='2' face='Arial, Helvetica, sans-serif'>C/ Brazal Almotilla, 23 </font><br/><font size='2' face='Arial, Helvetica, sans-serif'>50410 Cuarte de Huerva (ZARAGOZA)</font>");

  	}
}

function obtenerIndicaciones(){
		
		var calle = document.getElementById('cuadroCalle');
		var numero = document.getElementById('cuadroNumero');
		var provincia = document.getElementById('cuadroProvincia');
		
		var error = false;
		if(!error && calle.value == ""){
			alert("Por favor, introduzca una calle");
			error = true;
		}
		if(!error && provincia.value ==""){
			alert("Por favor, introduzca una provincia");
			error = true;
		}
		if (!error){
			if (setDirections(calle.value + ", " + numero.value + ", "+ provincia.value, '41.595298,-0.936263', 'es_ES') == true)
			{
			map.removeOverlay(puntoInicial);
		    map.closeInfoWindow();
			map.setMapType(G_NORMAL_MAP);
			var mapa = document.getElementById('slideMapa');
			mapa.style.width = '751px';
			var direcciones = document.getElementById('indicaciones');
			direcciones.style.display = 'block';	
			}			
		}
	}

function setDirections(fromAddress, toAddress, locale) {
		
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale , "getSteps":true});
	  return true;
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("La dirección solicitada no se ha podido localizar. Por favor, verifique los datos introducidos y vuelva a intentarlo." );
	   else alert("Ha ocurrido un error al procesar su solicitud. Vuelva a intentarlo más tarde.");	  
	   		    //map.openInfoWindow();
			var mapa = document.getElementById('slideMapa');
			mapa.style.width = '966px';
			var direcciones = document.getElementById('indicaciones');
			direcciones.style.display = 'none';		   
	}
	
	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load() results.
	}

	var newMarkers = [];
	var latLngs = [];
	var icons = [];
	
	// Note the 'addoverlay' GEvent listener added inside initialize() function

	function onGDirectionsAddOverlay(){ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++) 
	{map.removeOverlay(newMarkers[i]);
	}

	// Loop through the markers and create draggable copies
	for (var i=0; i<=gdir.getNumRoutes(); i++) 
		{
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:''});
		map.addOverlay(newMarkers[i]);

		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i], "dragend", function()
		  {
		var points = [];
		for (var i=0; i<newMarkers.length; i++) 
			{
		points[i]= newMarkers[i].getLatLng();
			}
		gdir.loadFromWaypoints(points);
		  });

		//Bind 'click' event to original hidden marker
		copyClick(newMarkers[i],originalMarker);
		
		// hide or remove the original marker
		//originalMarker.hide();
		map.removeOverlay(originalMarker);
		}
		
		function copyClick(newMarker,oldMarker){
		GEvent.addListener(newMarker, 'click', function()
		  {GEvent.trigger(oldMarker,'click');
		  });
		}
	}
