/**
 * Plugin: jquery.sp-googlemap
 * 
 * Version: 1.0.0
 * (c) Copyright 2009, Light Rock Systems Ltd
 * 
 * Description: jQuery plugin for simplified Google Maps API v3
 * 
 * History:
 * 
 **/

(function($){
    
    var current = null; 
    
	$.fn.spGoogleMap = function(addresses, titles, details, options) {
        
        // Set current instance
        var self = this;
        if (!current) {
            current = self;
        }
		
		// Set pluign defaults
		var defaults = {  
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			lat: 0,  
			lng: 0,  
			zoom: 10,
			tipSuffix: ' (click for more)'
		};  
		var options = $.extend(defaults, options); 
		
		// Initialise Map variables
		var apiCenter = new google.maps.LatLng(options.lat, options.lng);
		var apiMap = new google.maps.Map(this.get(0), $.extend(options, { center: apiCenter }));
		var apiGeocoder = new google.maps.Geocoder();
		
		// Functions
		$.extend(self, {
            
            initialise: function() {
		
				// Loop through addresses adding markers
				if (addresses) {
					if (addresses.length > 0) {
						var i = 0;
						while (i < addresses.length) {
							self.geocode(i++);
						}
					}
				}
			},
			geocode: function(index) {
				
				// Check for valid address array
				if (addresses && index >= 0) {
				
					// Get Lat/Long values from address
					apiGeocoder.geocode({ address: addresses[index] }, function(results, status) {
			
						if (status == google.maps.GeocoderStatus.OK && results.length) {
				
							if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
					
								apiMap.setCenter(results[0].geometry.location);
					
								// Add marker to map
								var apiMarker = new google.maps.Marker({
									position: results[0].geometry.location,
									map: apiMap,
									title: titles[index] + options.tipSuffix
								});
					
								// Create info window
								var apiInfoWindow = new google.maps.InfoWindow({
									content: details[index]
								});
					
								// Create 'click' event and attach info window to marker
								google.maps.event.addListener(apiMarker, 'click', function() {
									apiInfoWindow.open(apiMap, apiMarker);
								});
							}
						}
					});
				}
			}
		});
		
		// Load the map		
		function load() {
			self.initialise();
			return self;
        }
        
        load();
		
		//return this.each(function() {
		//});
	};
})(jQuery);