var map;
var localSearch = new GlocalSearch();

var gdir;
var directionsPanel;
var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);


var toAddress = ""; 
var fromAddress = "";


function convertPostCodeToPoint() {
}

function usePointFromPostcode(fromPostCode,toPostCode, callbackFunction) {

   // alert("From " + fromPostCode + " to " + toPostCode);


    localSearch.setSearchCompleteCallback(null,
			function() {
			    if (localSearch.results[0]) {
			        var locale = "en";
			        var resultLat = localSearch.results[0].lat;
			        var resultLng = localSearch.results[0].lng;

			        if (fromAddress == "") {
			            fromAddress = resultLat + "," + resultLng; // The starting postcode.
			            
			            //alert("From Add set to " + fromAddress);
			        }
			        else if (toAddress == "") {
			            toAddress = resultLat + "," + resultLng; // The starting postcode.
			            

			            //alert("To Add set to " + toAddress);

			            setDirections(fromAddress, toAddress, locale);

			            fromAddress = "";
			            toAddress = ""; 
			        }
			    }
			    else {
			        alert("Postcode not found");
			    }

			});

			localSearch.execute(fromPostCode + ", UK"); //find the lat and long of this post code
			localSearch.execute(toPostCode + ", UK"); //find the lat and long of this post code
			
}
/*
function ShowDirections(from, to)
{
    setDirections(from, to, "en_UK");
}*/

function placeMarkerAtPoint(lat,lng)
{
	//var marker = new GMarker(point,icon);
	//map.addOverlay(marker);

	var default_view = new GLatLng(lat,lng); 
	map.setCenter(default_view, 13);
	addressMarker = new GMarker(default_view);
	map.addOverlay(addressMarker);
}

function PlaceMarkerAtPostCode(postcode) {

    localSearch.setSearchCompleteCallback(null,
			function() {
			    if (localSearch.results[0]) {
			        var locale = "en";
			        var resultLat = localSearch.results[0].lat;
			        var resultLng = localSearch.results[0].lng;

			        //var point = resultLat + "," + resultLng; // The starting postcode.

			        placeMarkerAtPoint(resultLat, resultLng);

			    }
			    else {
			        alert("Postcode not found");
			    }

			});

			localSearch.execute(postcode + ", UK"); //set marker point
}

    function setDirections(fromAddress, toAddress, locale) 
    {
   // alert("from: " + fromAddress + " to: " + toAddress + " locale: " + locale);
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

function setCenterToPoint(point)
{
	map.setCenter(point, 17);
}

function showPointLatLng(point)
{
	alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}

function mapLoad() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));

        //map.addControl(new GLargeMapControl());		// Add large zoom and pan controls.
        //map.addControl(new GSmallZoomControl());		// Add small zoom controls.
        map.addControl(new GSmallMapControl()); 		// Add small zoom an pan controls.
        //map.addControl(new GMapTypeControl());		// Adds the buttons for type for view.
        map.addControl(new GOverviewMapControl()); 	// Collapsible overview map.
        //map.addControl(new GScaleControl());			// Adds scale.

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        /*var default_view = new GLatLng(52.151119, -2.090746); // wr10 2ea
        map.setCenter(default_view, 13);
        // map.removeOverlay(addressMarker);
        addressMarker = new GMarker(default_view);
        map.addOverlay(addressMarker);
        */
    }
}

/*function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		
		//google.load("maps", "2", {"callback" : mapsLoaded});
		
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_HYBRID_MAP);
		
		//directions initialisation
		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 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 addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);

