/**
* @author Jacob Rasmussen
*/

(function($){
	$.fn.googlemap = function(options) {
		var $this,opts;
		opts = $.extend({},$.fn.googlemap.defaults,options);
		
		return this.each(function(){
			$this = $(this);
			
			opts.init($this);						
			$this.find(opts.poiContainer + ' input:checkbox').click(function(){
				var selectedCat = $(this).val();

				opts.toggleMarkers(selectedCat,this.checked);
			});
			
		});
	};
	
	$.fn.googlemap.defaults = {
		map : null,
		visibleInfoWindow : null,
		init : function($this) {
			var opts = this;
			opts.map = new google.maps.Map($this.find(opts.mapContainer).get(0), {
				zoom : opts.zoom,
				center : new google.maps.LatLng(opts.latitude,opts.longitude),
				mapTypeId : opts.mapType,
				scaleControl : opts.scaleControl,
				mapTypeControlOptions : opts.mapTypeControlOptions
			});
			
			opts.prepareMarkers();
			$this.find(opts.poiContainer + ' input:checkbox').each(function(){
				var selectedCat = $(this).val();
				opts.toggleMarkers(selectedCat,this.checked);
			});
		},
		prepareMarkers : function () {
			var opts = this;
			$.each(opts.pois,function(catUid,catObj){
				opts.currentMarkers[catUid] = [];
				$.each(this.markers,function(){

					var m = new google.maps.Marker({
						position : new google.maps.LatLng(this.latitude,this.longitude),
						map : opts.map,
						title : this.title,
						icon : new google.maps.MarkerImage(this.icon.url,new google.maps.Size(this.icon.width,this.icon.height)),
						visible : false
					});
					opts.currentMarkers[catUid].push(m);
					
					var infoWindow = new google.maps.InfoWindow({
						content : this.content,
						size : new google.maps.Size(opts.infoWindow.width,opts.infoWindow.height)
					});
					
					google.maps.event.addListener(m, 'click', opts.openInfoWindow(infoWindow,m));					
				});
			});
		},
		toggleMarkers : function (catUid,selected) {
			if (this.currentMarkers[catUid] == undefined) {
				return;
			}

			if (this.visibleInfoWindow) {
				this.visibleInfoWindow.close();
			}
			
			$.each(this.currentMarkers[catUid], function(){
				this.setVisible(selected);
			});
		},
		openInfoWindow : function (infoWindow, marker) {
			var opts = this;
			return function(){
				if (opts.visibleInfoWindow) {
					opts.visibleInfoWindow.close();
				}
				
				infoWindow.open(opts.map, marker);
				opts.visibleInfoWindow = infoWindow;
			};
		},
		generateTriggerCallback : function (object, eventType) {},
		currentMarkers : {},
		pois : {}, 
		mapContainer : '.map',
		poiContainer : '.poi',
		latitude : 0.0,
		longitude : 0.0,
		zoom : 1,
		scaleControl : true,
		mapType : google.maps.MapTypeId.ROADMAP,
		mapTypeControlOptions : {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
		infoWindow : {width : 200,height : 300}
	};
})(jQuery);
