//<![CDATA[
var localSearch = new GlocalSearch();
var map;
var gdir;
var waypoints = new Array(2);
var goto = "BD16 2LZ";
GDirectionsOptions.locale("en");

// Load in the basic map
function loadmap() 
{ if (GBrowserIsCompatible())
   { document.getElementById("getDistance").innerHTML = "";
      document.getElementById("directions").innerHTML = "";
      var map = new GMap2(document.getElementById("mapcanvas"));
      map.setCenter(new GLatLng(53.8480,-1.8365), 16);
      map.addControl(new GLargeMapControl());
      var point = new GLatLng(53.8480,-1.8390);
      map.addOverlay(new GMarker(point));
   }
}

// Load route plan
function loadroute(rfrom)
{ if (GBrowserIsCompatible())
   { document.getElementById("getDistance").innerHTML = "";
      document.getElementById("directions").innerHTML = "";
      map = new GMap2(document.getElementById("mapcanvas"));
      map.addControl(new GLargeMapControl());
      gdir = new GDirections(map, document.getElementById("directions"));       
      GEvent.addListener(gdir, "load", onGDirectionsLoad);
      GEvent.addListener(gdir, "error", handleErrors);
      // get the geo ip of the users suspected current location
      localSearch.setSearchCompleteCallback(null, processResults);
      localSearch.execute(rfrom + ", UK");
      localSearch.execute(goto +", UK");
   }
}

// Set waypoints
function processResults() 
{ if (!localSearch.results) { alert("Address not found!"); }
   if (localSearch.results[0]) 
   { var resultLat = localSearch.results[0].lat;
      var resultLng = localSearch.results[0].lng;
      var point = new GLatLng(resultLat,resultLng);
      if (typeof(waypoints[0]) != 'undefined')
      { waypoints[1] = point.toUrlValue();
         gdir.loadFromWaypoints(waypoints);	
         waypoints = new Array(2);
      } 
		else { waypoints[0] = point.toUrlValue(); }
   }
   else 
   { alert("Address not found!"); localSearch.execute(goto +", UK"); }
}

function onGDirectionsLoad()
{ // some interesting options comment out if not needed
  document.getElementById("getDistance").innerHTML = gdir.getDistance().html;
}

function handleErrors()
{ if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) alert("Geographic location not found >> " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) alert("Server Error >> " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) alert("HTTP q parameter missing >>  " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_KEY) alert("Invalid key >> " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)  alert("Bad Request >> " + gdir.getStatus().code);
   else alert("An unknown error occurred >> " + gdir.getStatus().code);
 	 }
//]]>
