/**
 * Plugin: jquery.GoogleMaps
 * 
 * 
 * Updated Version: 1.0.2
 * (c) Copyright 2010, David Turner
 *
 * Description: jQuery plugin for displaying maps via Google Maps API v3
 * 
 * History:
 * 1.0.1 - Support for multiple map instances
 * 1.0.2 - Replace google geocode PAI with AJAX Search API to allow mapping fo rmore than 10 locations per map
 * 
 **/


(function($){
	
	$.fn.GoogleMap = function(locations, titles, details, icons,options) {
		
		// Set pluign defaults
		var defaults = {  
			type: 0,
			navControls:true,
			navControlsOpt:1,
			typeControls:false,
			typeControlsOpt:1,
			width: '100%',
			height: '300px',
			zoom: 3,
			clickable: true,
			tooltip: true,
			tipsuffix: ' (click for more)',
			icon: '/images_site/icons/marker.png'
		};  
		var options = $.extend(defaults, options); 
		
		// Select map type
		var maptype = getGoogleMapID(options.type);
		
		// Select map controls
		var navControlsOpt = getNavControlsID(options.navControlsOpt);
		
		// Select map controls
		var typeControlsOpt = getTypeControlsID(options.typeControlsOpt);
		
		// Set Map defaults
		var apiDefaults = {
			mapTypeId: maptype,
			navigationControl: options.navControls,
			navigationControlOptions: {
				style: navControlsOpt
			},
			mapTypeControl: options.typeControls,
			mapTypeControlOptions: {
					style: typeControlsOpt
			},
			zoom: options.zoom
		}
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			
			// Initialise Map variables
			//var apiCenter = new google.maps.LatLng(53.800651,-4.064941);
			var apiMap = new google.maps.Map($e.get(0), $.extend(apiDefaults, { bounds: apiBounds}));
 			var apiBounds = new google.maps.LatLngBounds();

			// Add map class to user div
			if (!$e.hasClass('mapGoogle')) {
				$e.addClass('mapGoogle');
				$e.css('width', options.width);
				$e.css('height', options.height);
			}

			
			// Loop through locations adding markers
			if (locations) {
				if (locations.length > 0) {
					var i = 0;
					while (i < locations.length) {
						// Plot location
						getGeoCode(apiBounds, apiMap, i);
						i = i+1;
					}
				}
			}
		});
		
		// Geocode address and plot markers	
		function getGeoCode(apiBounds, apiMap, index) {
			
			// Check for valid address array
			if (locations && index >= 0) {
				
				// Get Lat/Long values from address
				localsearchGeocode({ address: locations[index] ,bounds:apiBounds,map:apiMap}, function(results, status) {
					
					if (status == 200 && results.b && results.c) {
						//console.log(results);
						
						if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
									
							// Create tooltip text
							var title = '';
							if (options.tooltip) title = titles[index] + options.tipsuffix;

							if(icons[index]!="DEFAULT"){
								var useIcon = icons[index]; 
							}else{
								var useIcon = options.icon;
							}
							//console.log(useIcon);
							// Add marker to map
							var apiMarker = new google.maps.Marker({
								position: results,
								map: apiMap,
								title: title,
								icon: useIcon,
								shadow: useIcon.replace(/[.]{1}/,'_shadow.')
							});
							//console.log(title);
							// Create info window
							var apiInfoWindow = new google.maps.InfoWindow({
								content: details[index]
							});
					
							// Create 'click' event and attach info window to marker
							if (options.clickable)
								google.maps.event.addListener(apiMarker, 'click', function() {
									apiInfoWindow.open(apiMap, apiMarker);
								});
							}
							
						
					}
				});
			}
		}

		// Convert map type to Google Map ID
		function getGoogleMapID(map) {
			var mapid = google.maps.MapTypeId.ROADMAP;

			switch (map) {
				case 1:
					mapid = google.maps.MapTypeId.SATELLITE;
					break;
				case 2:
					mapid = google.maps.MapTypeId.HYBRID;
					break;
				case 3:
					mapid = google.maps.MapTypeId.TERRAIN;
					break;
			}

			return mapid;
    }
		
		
		// Switch nav controls type Google Map ID
		function getNavControlsID(map) {
			var controlid = google.maps.NavigationControlStyle.SMALL ;

			switch (map) {
				case 1:
					controlid = google.maps.NavigationControlStyle.SMALL;
					break;
				case 2:
					controlid = google.maps.NavigationControlStyle.ZOOM_PAN;
					break;
				case 3:
					controlid = google.maps.MapTypeControlStyle.ANDROID;
					break;
				case 4:
					controlid = google.maps.MapTypeControlStyle.DEFAULT;
					break;
			}

			return controlid;
    }
		
		
		// Switch type controls type Google Map ID
		function getTypeControlsID(map) {
			var controlid = google.maps.NavigationControlStyle.DEFAULT;

			switch (map) {
				case 1:
					controlid = google.maps.NavigationControlStyle.DEFAULT;
					break;
				case 2:
					controlid = google.maps.MapTypeControlStyle.DROPDOWN_MENU;
					break;
				case 3:
					controlid = google.maps.MapTypeControlStyle.HORIZONTAL_BAR;
					break;
			}

			return controlid;
    }

		
		//better geocoder - using google ajax search api
		function localsearchGeocode(location,callbackFunction) {
			
			
			
			//set up Google AJAX Search api
			var localSearch = new GlocalSearch();
			
			localSearch.setSearchCompleteCallback(null,
				function() {
					//
					
					if (localSearch.results[0]) {
						//console.log(localSearch.results[0]);
						var resultLat = localSearch.results[0].lat;
						var resultLng = localSearch.results[0].lng;
						var point = new google.maps.LatLng(resultLat,resultLng);
						

						location['bounds'].extend(point);

						location['map'].fitBounds(location['bounds']);

						//console.log(location['address']+" found!");
						callbackFunction(point,localSearch.completionStatus);
					}else{
						//console.log(location['address']+" not found!");
						location['address'] = location['address'].replace(/[^,]+,/,'');
						if(location['address']!=""){
							localsearchGeocode(location,callbackFunction);
						}
						//
						
					}
				});  
				
			localSearch.execute(location['address'].replace('UNITED KINGDOM','UK'));
		}
	};
	
	
	
	
})(jQuery);



