window.addEvent('load', function() {
	// Create a directions object and register a map and DIV to hold the 
	// resulting computed directions

	// Store locations and markers.
	var locations = {
		ipswich: (function() {
			var loc = new GLatLng(52.062979, 1.278856);
			var marker = new GMarker(loc);
			
			GEvent.addListener(marker, "dblclick", function() {
				map.setCenter(loc, 14);
			});
			
			return {
				loc: loc,
				address: "34 Gloster Road, Martlesham Heath, IP5 3RD",
				marker: marker
			};
		})()
	};
	
	// Create map display.
	var map = new GMap2(document.getElementById("map_canvas"));
	map.setCenter(locations.ipswich.loc, 10);
	map.addControl(new GLargeMapControl());

	var directions = new GDirections(map, $("route"));

	// Function to display driving directions to both stores from
	// the given postcode.
	function addDrivingDirections(postcode, loc) {
		directions.load("from: " + postcode + " to: " + loc.address);
	}
	
	function removeMarkers() {
		map.removeOverlay(locations.ipswich.marker);
	}

	var loc = null;
	
	function directionsFromForm() {
		// Check if the postcode is there on page load.
		var postcode = $("postcode").value;
		if (postcode && loc) {
			postcode += ", UK";
			addDrivingDirections(postcode, loc);
			return true;
		} else {
			map.addOverlay(locations.ipswich.marker);
			return false;
		}
	}
	
	directionsFromForm();
	
	// Capture submit events on the form, and just load the map directly instead.
	$E("#map form").addEvent('submit', function(e) {
		var e = new Event(e);
		removeMarkers();
		loc = locations.ipswich;
		directionsFromForm();
		e.preventDefault();
		return false;
	});
});
