if (typeof MooTools == 'undefined') {
	throw 'MooTools is required for Mercurytide.GoogleMaps.';
}

if (typeof Mercurytide == 'undefined') var Mercurytide = {};

Mercurytide.GoogleMaps = {

	enabled: true,
	apiKey: null,
	
	required: false,
	
	domLoaded: false,
	loadCalled: false,
	apiLoaded: false,
	
	callbacks: [],
	
	loadIfRequired: function() {
		Mercurytide.GoogleMaps.domLoaded = true;
		if (Mercurytide.GoogleMaps.callbacks.length > 0) {
			Mercurytide.GoogleMaps.load();
		}
	},
	
	load: function() {
		if (!Mercurytide.GoogleMaps.enabled) return;
		if (Mercurytide.GoogleMaps.loadCalled) return;
		Mercurytide.GoogleMaps.loadCalled = true
		
		if (Mercurytide.GoogleMaps.apiKey == null) {
			throw 'Mercurytide.GoogleMaps.apiKey has not been defined.';
		} else if (Mercurytide.GoogleMaps.apiKey == '') {
			throw 'Mercurytide.GoogleMaps.apiKey is blank -- is ' + location.host + ' correctly configured?';
		}
		
		new Asset.javascript('http://maps.google.com/maps?file=api&v=2&key=' + Mercurytide.GoogleMaps.apiKey + '&async=2&callback=Mercurytide.GoogleMaps.loaded');
	},
	
	loaded: function() {
		Mercurytide.GoogleMaps.apiLoaded = true;
		Mercurytide.GoogleMaps.callbacks.each(function(callback) {
			callback();
		});
		Mercurytide.GoogleMaps.callbacks = [];
	},
	
	whenLoaded: function(callback) {
		if (Mercurytide.GoogleMaps.apiLoaded) {
			callback();
		} else {
			Mercurytide.GoogleMaps.callbacks.push(callback);
			Mercurytide.GoogleMaps.required = true;
		}
		if (Mercurytide.GoogleMaps.domLoaded) Mercurytide.GoogleMaps.load();
	},
	
	/**
	 * Wrapper to the standard enableScrollWheelZoom function to ensure that
	 * the map container's scroll wheel event doesn't propogate and cause the
	 * whole page to scroll. 
	 */
	enableScrollWheelZoom: function(map) {
		map.enableScrollWheelZoom();
		var stop = function(e) { new Event(e).stop(); } 
		$(map.getContainer()).addEvent('DOMMouseScroll', stop);
		$(map.getContainer()).addEvent('mousewheel', stop); 
	}
	
}

window.addEvent('load', Mercurytide.GoogleMaps.loadIfRequired);
