﻿var GMapRender = {
	// mapping of div id's to lat/long
	mapCoords: null,
		
	gmapClass: 'gmapcanvas',
	gmapCanvas: null,
	map: null,
	geocoder: null,
	init: false,
		
	init: function()
	{		
		var mapOptions = {
			zoom: 15,
			mapTypeControl: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		this.gmapCanvas = $$('.' + this.gmapClass)[0];
		this.map = new google.maps.Map(this.gmapCanvas, mapOptions);
		this.geocoder = new google.maps.Geocoder();
		this.init = true;
		
		this.populateMapCoords();
		this.displayDefault();
	},
		
	populateMapCoords: function()
	{
		this.mapCoords = {
			'contactmap': [
				new google.maps.LatLng(51.4945857, -0.1371447),
				'<p>The Society of Operations Engineers<br />22 Greencoat Place<br />London<br />SW1P 1PR</p><p>Telephone: 020 7630 1111<br />Fax: 020 7630 6677<br />Email: <a href="mailto:soe@soe.org.uk">soe@soe.org.uk</a></p>'
			]
		};
	},
		
	displayDefault: function()
	{
		var loc = this.mapCoords[this.gmapCanvas.id];
		if (loc) {
			this.map.setCenter(loc[0]);
			var iwOptions = {
				content: loc[1]
			};
			var infoWindow = new google.maps.InfoWindow(iwOptions);
			var marker = new google.maps.Marker({
				map: this.map,
				position: loc[0]
			});
			google.maps.event.addListener(marker, 'click', function(e) {
				infoWindow.open(this.map, marker);
			});
		}
	},
		
	setCentre: function(loc)
	{
		if (!this.init) {
			this.init();
		} else {
			var latlng = null;			
			if (loc instanceof String) {
				this.geocoder.geocode(
					{ 'address': loc },
					function(results, status) {
						if (google.maps.GeocoderStatus.OK == status) {
							latlng = results[0].geometry.location;
						}
					}
				);
			} else if (loc instanceof google.maps.LatLng) {
				latlng = loc;
			}
			
			if (latlng) {
				this.map.setCenter(latlng);
				var marker = new google.maps.Marker({
					map: this.map,
					position: latlng
				});
			}							
		}
	}	
}

var GMapsAPILoader = {	
	handleApiReady: function()
	{
		GMapRender.init();
	},

	bootstrap: function()
	{
		var script = document.createElement("script");
		script.type = "text/javascript";

		script.onreadystatechange= function () {
			if (("loaded" == this.readyState) || ("complete" == this.readyState)) {
				google.maps.loadScripts();
			}
		};

		script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=GMapsAPILoader.handleApiReady";
		document.body.appendChild(script);

		loaded = true;
	}	
};

document.observe("dom:loaded", function() {
	GMapsAPILoader.bootstrap();
});
