var map;
var directions;
var directionsPanel;

function process(form) {
	
	// == obtain the data
	var from = form.from.value;
	var to = form.to.value;
	
	//alert('from' + from + 'to' + to);
	// Set the directions up
	
	directions.clear();
	directions.load("from: "+ from + " to: " + to);
	map.closeInfoWindow();
	//alert("test: " + directions.getNumRoutes());
	//if(directions.getStatus() == undefined){
		//alert("Sorry, directions couldn't be calculated. Please make sure your to and from address are correct.");
	//}
	return false;
}


function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		directionsPanel = document.getElementById("map_text");
		directions = new GDirections(map, directionsPanel);
		var strLoc = document.getElementById("locations").value;
		var arrLoc = strLoc.split(" || ");
		
		var strName = document.getElementById("location_names").value;
		var arrName = strName.split(" || ");
		
		var geocode = new GClientGeocoder();
		geocode.getLatLng(arrLoc[0], function callbackLatLng(point) {
			map.setCenter(point, 13);
		});

		var url = window.location.href;
		
		for (i = 0; i < arrLoc.length - 1; i++) {

			if (arrLoc[i] != "") {
				var str = arrLoc[i];
				var name = arrName[i]
				var iwform = '<b>Get Directions to: </b> '+name+'<br>'
						+ '<form action="'+url+'" name="directions_frm" onsubmit="return process(this)" method="post">'
						+ ' <input type="hidden" name="year" value="'+document.getElementById('year').value+'" /><br>'
						+ ' From:<input type="text" name="from" /><br>'
						+ ' To:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="to" value="' + str
						+ '"/><br>' + ' <input type="submit" value="Submit" />'
						+ '<\/form>';

				geocode.getLatLng(str, (function breakReference(arg) {
					return function callback(point) {
						var marker = new GMarker(point);
						marker.bindInfoWindow(arg);
						map.addOverlay(marker);
						// document.write(i + " - " + str + "<br/>");

					};
				})(iwform));

			}
		}

		map.setUIToDefault();
		

	}
}



window.onload = initialize;

