//<![CDATA[

var map;
var gdir;
var marker;
var localSearch = new GlocalSearch();

google.load("maps", "2.x");

// Call this function when the page has been loaded
function initialize(){
	if (GBrowserIsCompatible()) {
		map = new google.maps.Map2(document.getElementById("map-canvas"));
		gdir = new GDirections(map, document.getElementById("directions"));
		marker = new GMarker(new GLatLng(52.62188, 1.2968));
		map.setCenter(new google.maps.LatLng(52.62188, 1.2968), 13);
		map.addControl(new GLargeMapControl());
		map.addOverlay(marker);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
	}
}

// Call this function when a user submits the 'get directions' form
function usePointFromPostcode(postcode, callbackFunction) {
	localSearch.setSearchCompleteCallback(null, 
		function() {
			if (!postcode || postcode == 'your postcode') {
				alert("Please enter a postcode");
			}
				else if (localSearch.results[0]) {    
					var resultLat = localSearch.results[0].lat;
					var resultLng = localSearch.results[0].lng;
					var point = new GLatLng(resultLat,resultLng);
					callbackFunction(point);
				}
					else {
						alert("We couldn't find your location.\n\nPlease ensure you have entered a valid postcode.");
					}
		});  
	localSearch.execute(postcode + ", UK");
}

// Call this function to load new Google directions for given coordinates
function setDirections(point) {
	gdir.load("from: Your Location@" + point.lat() + " " + point.lng() + " to: Digital Overload@52.622 1.29566", {
		"getSteps": true,
		"locale": 'en'
	});
}

// Handle errors from Google directions
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("We couldn't find your location.\n\nYour address may be relatively new, or incorrect.");
	}
		else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
			alert("Google Maps is currently unresponsive. Please try again later.\n\nError code: " + gdir.getStatus().code);
		}
			else if (gdir.getStatus().code == G_GEO_BAD_KEY || gdir.getStatus().code == G_GEO_BAD_REQUEST || gdir.getStatus().code == G_GEO_MISSING_QUERY) {
				alert("Unfortunately, this feature is currently disabled. Please try again later.\n\nError code: " + gdir.getStatus().code);
			}
				else {
					alert("An unknown error occurred. Your address may be too far from the UK.\n\nPlease try again.");
				}
}

// Call this function to remove 
function onGDirectionsLoad() {
	map.removeOverlay(marker);
}

google.setOnLoadCallback(initialize);

//]]>