var clickHandler;
var map;
var gdir;
var lat;
var lng;
var locations = Array();
var bounds;
var markers = Array();
var names = Array();

var maxSize = "666px", minSize = "388px";

$(document).ready(function() {
		
	$("select.inputItinerario").change(actualizarDireccionesGmap);		
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("gmapItinerario"));
        map.addControl(new GLargeMapControl());
 	    map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(43.111, 5.776), 5);
        
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
	    GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap, Esa


		$("#enviar").click(function() {
	         
  			 var inputFrom = $("input[@name=from]").val(); 
			 var inputTo = $("input[@name=daddr]").val(); 
			
			 if (inputFrom != "" && inputTo != "" ) {
				 $("#gmapItinerario").width(minSize); 
				 $("#directions").show(); 
				 map.clearOverlays();
				 map.checkResize(); 
			 
				 var inputLng = $("input[@name=lng]").val();

			 var arrPos = $("select.inputItinerario").val().split(",");	
			
				 setDirections(inputFrom, inputTo, inputLng);
			 }
			 else {
				 alert(errorEmptyDirection);
				 $("input[@name=from]").focus();
			 }

			// addMarker(arrPos[0], arrPos[1], $("input[@name=daddrname]").val());
			 return false;
			 }
	     );
		 $("select.inputItinerario").trigger("change");
    }     
});

function buildItinerary(){
	       
	 $("#enviar").trigger("click");
	/*
	var inputFrom = $("input[@name=from]").val(); 
	 var inputTo = $("input[@name=daddr]").val(); 
	
	 if (inputFrom != "" && inputTo != "" ) {
		 $("#gmapItinerario").width(minSize); 
		 $("#directions").show(); 
		 map.clearOverlays();
		 map.checkResize(); 
	 
		 var inputLng = $("input[@name=lng]").val();

	 var arrPos = $("select.inputItinerario").val().split(",");	
	
		 setDirections(inputFrom, inputTo, inputLng);
	 }
	 else {
		 alert(errorEmptyDirection);
		 $("input[@name=from]").focus();
	 }
*/
	// addMarker(arrPos[0], arrPos[1], $("input[@name=daddrname]").val());
	 return false;
}

function actualizarDireccionesGmap() {
   map.clearOverlays();
   $("#gmapItinerario").width(maxSize);
   $("#directions").hide();
   map.checkResize();
   var valSelect = $(this).val();
   if(valSelect != "") {
      var objSelect = $(this).get(0);
      var labelTxt = objSelect[objSelect.selectedIndex].text;
	  var arrPos = valSelect.split(",");
      $("input[@name=daddr]").val(valSelect + "(" + labelTxt + ")");
      $("input[@name=daddrname]").val(objSelect[objSelect.selectedIndex].text);
	  addMarker(arrPos[0], arrPos[1], labelTxt);
   }
}
    
function setDirections(fromAddress, toAddress, locale) {
  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.");
   */
   alert(errorFindDirections);
   $("select.inputItinerario").trigger("change");
}

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 addMarker(strLat, strLon, strNom) {

	// iconos
	var icono = new GIcon();
	icono.image = "/images/marker.png";
	icono.shadow = "/images/marker_shadow.png";
	icono.iconSize = new GSize(26, 30);
	icono.shadowSize = new GSize(39, 30);
	icono.iconAnchor = new GPoint(6, 20);
	icono.infoWindowAnchor = new GPoint(5, 1);

	var point = new GLatLng(strLat, strLon);

	locations.push(point);

	objMark = new GMarker(point);
    map.addOverlay(objMark);
	addInfoHTML(objMark, strNom);
 
    zoomShowAll();
}


function addInfoHTML(marker, html) {
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
}


function zoomShowAll() {
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);

	jQuery.each(locations, function() {
        bounds.extend(this);
    });   
 
	map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
}

/**
* The add-on code for draggable markers
* @author Esa 2008
*/
var newMarkers = [];
var latLngs = [];
var icons = [];

// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used

function onGDirectionsAddOverlay(){ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++){
		map.removeOverlay(newMarkers[i]);
	}

	// iconos
	var icono = new GIcon();
	icono.image = "/images/marker.png";
	icono.shadow = "/images/marker_shadow.png";
	icono.iconSize = new GSize(26, 30);
	icono.shadowSize = new GSize(39, 30);
	icono.iconAnchor = new GPoint(6, 20);
	icono.infoWindowAnchor = new GPoint(5, 1);

	// 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]);
		map.addOverlay(newMarkers[i]);

		//Bind 'click' event to original markers 'click' event
		copyClick(newMarkers[i], originalMarker);

		// Now we can remove the original marker safely
		map.removeOverlay(originalMarker);
	}

	function copyClick(newMarker,oldMarker){
		GEvent.addListener(newMarker, 'click', function(){
		  GEvent.trigger(oldMarker,'click');
		});
	}
}

window.onunload = GUnload;
