 google.load("maps", "2.x");
 var geocoder;
 var map;
 var dir;
 var address;
 var holdAddress;
// Call this function when the page has been loaded
function initialize() {
    map = new google.maps.Map2(document.getElementById(GMap.mapID));

    if (GMap.dirID) {
      panel = document.getElementById(GMap.dirID);
      dir = new GDirections(map, panel);
    }
    map.addControl(new GSmallMapControl());
    // Create new geocoding object
    geocoder = new GClientGeocoder();
    // Retrieve location information, pass it to addToMap()
    geocoder.getLocations(GMap.loc, addToMap);
    GEvent.addListener(dir, "load", onDirLoad); //Handler if you want to do more after dirs. load
    //window.onunload=GUnload; //TODO: Make sure this works!
    
   var ErrorMessage =  "Sorry, address not understood";

   if(GMap.helpID)
     GEvent.addListener(dir, "error", onErrorReturned);
   else
     GEvent.addListener(dir, "error", function() {alert(ErrorMessage + "\nGoogle Error: " + dir.getStatus().code)});
}


var ErrorMsgCnt = 0;
var ErrorMessage = ["Sorry, I don't understand","Try being less specific","",
                  "I'm just a dumb computer..."];
function HelpMessage() {
  if(ErrorMsgCnt >= ErrorMessage.length || ErrorMsgCnt < 0)
    ErrorMsgCnt = 0;
  ErrorMsgCnt += 1;

  if (ErrorMsgCnt == 3)
    return "Try <a href=\"http://maps.google.com/maps?q=from: " + address + " to: 988%20S%20green%20bay%20rd%2C%20neenah%2C%20wi\">Google Maps</a> for more help";
  else
    return ErrorMessage[ErrorMsgCnt-1];
}

function onErrorReturned() {
  //callback for errors
  var timeStamp = new Date().toString();
  $.post('./log.php', {'msg':timeStamp+' ERROR,'+holdAddress+'\n'});
  document.getElementById(GMap.helpID).innerHTML = HelpMessage();
}

function onDirLoad(){
  //callback for successful directions
  var timeStamp = new Date().toString();
  $.post('./log.php', {'msg': timeStamp + ' SUCCESS,'+holdAddress+'\n'});
  $('#'+GMap.helpID).html("Scroll down for you directions.");
}

function addToMap(response)
 {
    // Retrieve the object
    place = response.Placemark[0];
    // Retrieve the latitude and longitude
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    // Center the map on this point
    map.setCenter(point, GMap.zoom);
    // Create a marker
    marker = new GMarker(point);
    // Add the marker to map
    map.addOverlay(marker);
    // Add address information to marker
    //marker.openInfoWindowHtml("Mighty Sales &amp; Service");
 }

google.setOnLoadCallback(initialize);

function getDirections(start) {
  holdAddress = start;
  dir.load(start + " to " + GMap.loc);
}
