
var infowindow = new google.maps.InfoWindow();

(function($){
	$.fn.googleMap = function(locations, options){
		var defaults = {
			zoom: 0,
			draggable: true,
			navigationControl: true,
			mapTypeControl: true,
			scaleControl: false,
			scrollwheel: true,
			bgColor: '#0080A7',
			showInfoWindow: true
		};
		var options = $.extend(defaults, options);
		var mapOptions = {
			draggable: options.draggable,
			navigationControl: options.navigationControl,
			navigationControlOptions: {
				style: google.maps.NavigationControlStyle.DEFAULT,
        		position: google.maps.ControlPosition.TOP_LEFT
			},
			mapTypeControl: options.mapTypeControl,
			mapTypeControlOptions: {
				mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE],
				style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        		position: google.maps.ControlPosition.TOP_RIGHT
			},
			scaleControl: options.scaleControl,
			scaleControlOptions: {
				position: google.maps.ControlPosition.LEFT
			}, 
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: options.scrollwheel,
			zoom: options.zoom,
			backgroundColor: options.bgColor
		}
		
		return this.each(function(i, e){
			var $e = $(e);
			var mapCenter = new google.maps.LatLng(0, 0);
			var map = new google.maps.Map($e.get(0), $.extend(mapOptions, {
				center: mapCenter
			}));
			var bounds = new google.maps.LatLngBounds();
			
			for (var i = 0; i < locations.length; i++) {
				var loc = locations[i];
				var point = new google.maps.LatLng(loc[1], loc[2]);
				bounds.extend(point);
				var m = addMarker(point, loc[0], map, loc[3], options.showInfoWindow);
				m.setMap(map);
			}
			
			if (options.zoom > 0) {
				map.setCenter(bounds.getCenter());
				map.setZoom(options.zoom);
			}
			else {
				map.fitBounds(bounds);
			}
			
		});
		
		function addMarker(point, text, map, imgIcon, showInfoWindow){
			var marker = new google.maps.Marker({
				position: point,
				icon: imgIcon
			});
			if(showInfoWindow === true){
				google.maps.event.addListener(marker, 'click', function(){				
					infowindow.close();
					infowindow.setContent(text);
					infowindow.open(map, marker);
				});	
			}			
			return marker;
		}
		
	};
})(jQuery);

