// According to the Google Maps API Terms of Service you are required display a Google map
// when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html
var geocoder, location1, location2, gDir;

function initialize() {
	geocoder = new GClientGeocoder();
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", function() {
		var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
		var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
		document.getElementById('results').innerHTML = '<strong>Start: </strong>' + location1.address + '<br /><strong>Finish: </strong>' + location2.address + '<br /><br /><strong>Driving Distance: </strong>' + (Math.round(drivingDistanceMiles*100)/100) + ' miles (' + (Math.round(drivingDistanceKilometers*100)/100) + ' kilometers)';
	});
}

function showLocation() {
	geocoder.getLocations(document.forms[0].txtStartLocation.value, function (response) {
		if (!response || response.Status.code != 200){
			alert("Sorry, we were unable to geocode the first address");
		}
		else{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			geocoder.getLocations(document.forms[0].txtEndLocation.value, function (response) {
				if (!response || response.Status.code != 200){
					alert("Sorry, we were unable to geocode the second address");
				}
				else{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					gDir.load('from: ' + location1.address + ' to: ' + location2.address);
				}
			});
		}
	});
}
