var map;
var gdir;
var geocoder = new GClientGeocoder();
var addressMarker;

function initialize() {
  if (GBrowserIsCompatible()) {      
    map = new GMap2(document.getElementById("map_canvas"));
    document.getElementById("directions").innerHTML = "";
	 if (document.getElementById("fromAddress").value) {
	    gdir = new GDirections(map, document.getElementById("directions"));
	    GEvent.addListener(gdir, "load", onGDirectionsLoad);
	    GEvent.addListener(gdir, "error", handleErrors);
	    setDirections(document.getElementById("fromAddress").value, document.getElementById("toAddress").value);
	 }
	 else {
	 	setLocation(document.getElementById("toAddress").value);
	 	map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
	 }  
  }
}

function setLocation(address) {
	geocoder.getLatLng(
    address,
    function(latlng) {
      if (!latlng) {
        alert(address + " not found");
      } else {
        map.setCenter(latlng, 15);
        var marker = new GMarker(latlng);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
      }
    }
  );

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

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("Het ingevoerde adres is onbekend");
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("Er is een onbekende fout opgetreden, waardoor de route niet kan worden berekend");
  
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("Er is een oError 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...
}
