(function($) {  // Start our namespace

	/*
	 * Custom jQuery plugin to load in a Google Map with some data
	 */
	$.fn.googleMap = function(options) {

        var kmlUrl = 'http://sunskool.demo.areeba.com.au/Schools.kml';

        // check if we are on the live site - if so, make sure the google map data url is right
        var pos = location.href.indexOf("sunskool.com");
        if (pos>0) { kmlUrl = 'http://www.sunskool.com/Schools.kml'; }
       	
		// Options
		settings = jQuery.extend({
		    mapData:                kmlUrl,
			mapDataCache:			false,
			mapInitZoom:			10,
			mapInitLocation:		{
										latitude: -37.817683,
										longitude: 144.959729
									},
			mapAddControls:			true,
			mapAddMiniMapControls: 	true,
			mapAddTypeControls:		true,
			errorMessageMap:		'Your browser does not support Google Maps'
		}, options);
		
		// Make sure we have the correct scope
		var $el = this;
		
		// Check to see if we can run a google map
		if (GBrowserIsCompatible()) {

			// See if we want to cache the loaded data
			var queryString = '';
			if (!settings.mapDataCache) {
				queryString = '?noCache=' + Math.floor(Math.random()*999999);
			}

			// Initialize the map
			var map = new GMap2($el[0]);

            // Callback function to use kml to center map when ready
			var geoCallback = function() {
			    geoXml.gotoDefaultViewport(map);
			}

			// Get the XML file (in KML format)
			var geoXml = new GGeoXml(settings.mapData + queryString, geoCallback);
			
			// See if we want to add the zoom / pan controls
			if (settings.mapAddControls) {
				map.addControl(new GLargeMapControl());
			}
			
			// See if we want to add the map / satellite / hybrid controls
			if (settings.mapAddTypeControls) {
				map.addControl(new GMapTypeControl());
			}
		
			// See if we want to add a mini map as well
			if (settings.mapAddMiniMapControls) {
				map.addControl(new GOverviewMapControl());
			}
			
			// Centre the map - in the mean time until callback from kml is done
			map.setCenter(new GLatLng(settings.mapInitLocation.latitude,settings.mapInitLocation.longitude), settings.mapInitZoom);
			
			// Add the KML data
			map.addOverlay(geoXml);
			
			// The infowindow contents can be modified as it opens
			GEvent.addListener(map,'infowindowprepareopen', settings.openWindowFunction);
			
		} else {
		
			// We don't have Google Maps support so let the user know
			$el.html('<div class="message"><p>'+ settings.errorMessageMap +'</p></div>');
		}
		
		// Return this so we can chain
		return $el;

	 };
	 
})(jQuery); // End our namespace
