 google.load("maps", "2.x");

 function gmapper(GMap) {

   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","Still can't find that."];
  function HelpMessage() {
    if(ErrorMsgCnt > ErrorMessage.length || ErrorMsgCnt < 0)
      ErrorMsgCnt = 0;

    var msg;
    if (ErrorMsgCnt == ErrorMessage.length)
      msg =  "Try <a href=\"http://maps.google.com/maps\">Google Maps</a> for more help";
    else
      msg = ErrorMessage[ErrorMsgCnt];

    ErrorMsgCnt += 1;

    return msg;
  }

  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();
    $('#'+GMap.helpID).html("Scroll down for your 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);

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