var map;
var gdir;

window.addEvent('domready', function() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		var qsa = new GLatLng(51.383308,-2.361829);
		map.addControl(new GLargeMapControl());
		gdir = new GDirections(map, document.getElementById("route"));
		GEvent.addListener(gdir, "error", handleErrors);
		setGoToGoogle("");
		
		if ($('directionsfrom').value != $('directionsfrom').title) {
			getDirections($('directionsfrom').value)
		} else {
			map.setCenter(qsa, 17);
			map.addOverlay(new GMarker(qsa));
		}
	}
});

function getDirections(location) {
	if (location != "") {
		gdir.load(location+" to Quiet Street Antiques, Quiet Street, Bath");
		setGoToGoogle(location);
	} else {
		alert('AGH!');
	}
}

function setGoToGoogle(driving) {
	if (driving == "") {
		url = "http://maps.google.co.uk/maps?f=q&hl=en&q=Quiet+Street+Antiques&sll=51.383308,-2.361829&sspn=0.007205,0.01693&ie=UTF8&ll=51.383955,-2.361825&spn=0.007205,0.01693&z=16&iwloc=A";
	} else {
		url = "http://maps.google.co.uk/maps?f=d&hl=en&geocode=&saddr="+driving+"&daddr=Quiet+Street+Antiques,+Quiet+Street,+Bath&mra=pe&mrcr=0&sll=51.746221,-1.933374&sspn=0.914903,2.167053&ie=UTF8&t=h&z=10";
	}
	$('goToGoogle').href = url;
}

function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("We couldn't find the place you want to travel from, or couldn't find a driving route. Try being less specific. (Due to licencing laws postcodes won't work).\n\nAlternatively you can use the link at the bottom of the page 'See in Google Maps' to try your search again using Google Maps directly.");
	   else alert("Something went wrong when we tried to find directions for you. Please use the 'See in Google Maps' link at the bottom of the page.");
	   
	}
