var map;
var gdir;
var geocoder = null;
var addressMarker;

function initialize() {
  if (GBrowserIsCompatible()) {      
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(lat,long), 13);
	map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
	
	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
	
	geocoder = new GClientGeocoder();
	showAddress(toAddress, lat, long);
  }
}

function showAddress(address, lat, long) {
	
	if (geocoder && (!lat || !long)) {
		geocoder.getLatLng(
		  address,
		  function(point) {
			if (!point) {
			  alert(address + " not found");
			} else {
			  map.setCenter(point, 13);
			  var marker = new GMarker(point);
			  map.addOverlay(marker);
			}
		  }
		);
	}
	
	else {
		var point = new GPoint(long, lat);
		var marker = new GMarker(point, G_DEFAULT_ICON);
		map.addOverlay(marker);
	}
}

function setDirections(fromAddress, toCapps) {
	if ( toCapps )
		gdir.load("from: " + fromAddress + " to: " + toAddress);
	else
		gdir.load("from: " + toAddress + " to: " + fromAddress);
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	 alert("The specified location could not be found. This may be due to the fact that the address is relatively new, or it may be incorrect.");

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.");
   
   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.");
 
   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.");

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("A directions request could not be successfully parsed.");

   else alert("An unknown error occurred.");
   
}

function onGDirectionsLoad(){ 
}