var map;
var gdir;
var geocoder = new GClientGeocoder();
var toAddress = "2600 S 11th St, St. Louis, Mo";
var addressMarker;
var marker;

function initialize() {
    if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions_canvas"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        var lat_long = new GLatLng(38.60174623769639, -90.21174430847168);
		
		var map_icon = new GIcon();

		map_icon.image = "/images/map_icon.png";
		map_icon.shadow = "";
		map_icon.iconSize = new GSize(32, 32);
		map_icon.shadowSize = new GSize(1, 1);
		map_icon.iconAnchor = new GPoint(6, 20);
		map_icon.infoWindowAnchor = new GPoint(5, 1);

		marker=new GMarker(lat_long, map_icon);
		
        map.setCenter(lat_long, 13);
		map.addOverlay(marker);
        map.addControl(new GSmallMapControl());
	}
}
    
function setDirections(address) {
    geocoder.getLatLng( address, function(point) {
        if (!point) {
            alert(address + " not found, please enter the City and State also");
        } else {
            gdir.loadFromWaypoints([point, toAddress]);
			map.removeOverlay(marker);
        }
    }
);
}

function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    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.\n Error code: " + gdir.getStatus().code);
	   
    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.\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...
}