/**
 * @author dao
 */
window.addEvent('load', function(){
	if (GBrowserIsCompatible()) initialize();
	$('originForm').addEvent('submit', function(e){
		new Event(e).stop();
		setOrigin(this.from.value);
	});
});

window.addEvent('unload', function(){
	if (GBrowserIsCompatible()) {
		GUnload();
	}
});

var map;
var mapDiv = 'map';
var mapZoom = 16;
var centerLat = 43.17665626201315;
var centerLng = -90.0690507888794;
var mapInfo = "The Bank";

var gdir;
var gdirMap;
var gdirPanel;
var gdirMapDiv = 'gdirMap';
var gdirDiv = 'gdirPanel';
var destination = "134 W Jefferson St, Spring Green, WI";
var origin = "Madison, WI";

function initialize(){
	map = new GMap2(document.getElementById(mapDiv));
	center = new GLatLng(centerLat, centerLng);
	map.setCenter(center, mapZoom);
	map.addControl(new GSmallZoomControl());
	marker = new GMarker(center);
	map.addOverlay(marker);

/*
// open info window with mapInfo html content on click. 
  GEvent.addListener(marker, "click", function(){
		     marker.openInfoWindowHtml(mapInfo);
	});
*/
	
	gdirMap = new GMap2(document.getElementById(gdirMapDiv));
	gdirPanel = document.getElementById(gdirDiv);
	gdir = new GDirections(gdirMap, gdirPanel);
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
	GEvent.addListener(gdir, "addoverlay", onGDirectionsOverlay);
	setOrigin(origin);
}

function setOrigin(origin){
	gdir.load("from: " + origin + " to: " + destination);
}

function onGDirectionsLoad(){
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
}

function onGDirectionsOverlay(){
	updateScroll(scrollDiv); // defined in menu.js
}

function handleErrors(){
	switch (gdir.getStatus().code) {
		case G_GEO_UNKNOWN_ADDRESS:
			error = "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;
		case G_GEO_SERVER_ERROR:
			error = "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;
		case G_GEO_MISSING_QUERY:
			error = "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;
		case G_GEO_BAD_KEY:
			error = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
		case G_GEO_BAD_REQUEST:
			error = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
		default:
			error = "An unknown error occurred.";
	}
	alert(error);
}
