/**************************************************************************************************/
/*
/*		File:
/*			scripts.js
/*		Description:
/*			This file contains Javascript for the front-end aspects of the plugin.
/*		Date:
/*			Added on November 1st 2010
/*		Copyright:
/*			Copyright (c) 2009 Matthew Praetzel.
/*		License:
/*			License:
/*			This software is licensed under the terms of the GNU Lesser General Public License v3
/*			as published by the Free Software Foundation. You should have received a copy of of
/*			the GNU Lesser General Public License along with this software. In the event that you
/*			have not, please visit: http://www.gnu.org/licenses/gpl-3.0.txt
/*
/**************************************************************************************************/

(function($) {

	pigm = {
		
		queue : [],
		mapsLoaded : false,
		maps : [],
		timer : [],
		marked : [],
		categories : [],
		overlay : function (m,o) { this.setMap(o.maps[m].map); },
		marker : null,
		defaults : {
			toggle : {}
		},
		
		init : function (o) {
			var th = this;
			
			$.extend(th.defaults,o);
			
			th.addToQueue(th.loadGoogleMaps);
			th.addToQueue(function () {
				//create overlay
				th.overlay.prototype = new google.maps.OverlayView();
				th.overlay.prototype.onAdd = function() { };
				th.overlay.prototype.onRemove = function() { };
				th.overlay.prototype.draw = function () {
					
				};
				th.removeFromQueue();
			});
			th.addToQueue(th.createMap);
			$('.pigm_categories').each(function() {
				$(this).find('li').each(function () {
					$(this).bind('click',function () {
						th.addCategory(th.getID($(this).parents('.pigm_instance').attr('class'),'pigm'),th.getID($(this).attr('class'),'cat'));
					});
				});
			});
		},
		loadGoogleMaps : function () {
			var th = this;
			$('head').append('<script type="text/javascript" src="http://www.google.com/jsapi?key='+google_maps_api+'"></script>');
			var t = (new Date())/1000;
			th.timer['gmap'] = setInterval(function () {
				if(window['google']) {
					clearInterval(th.timer['gmap']);
					google.load('maps','3',{ callback:function(){},'other_params':'sensor=true&key='+google_maps_api });
					th.timer['gmap'] = setInterval(function () {
						if(google.maps.Map) {
							clearInterval(th.timer['gmap']);
							th.removeFromQueue();
							th.mapsLoaded = true;
						}
						else if((t+20) < (new Date())/1000) {
							clearInterval(th.timer['gmap']);
							th.removeFromQueue();
						}
					},100);
				}
				else if((t+20) < (new Date())/1000) {
					clearInterval(th.timer['gmap']);
					th.removeFromQueue();
				}
			},100);
		},
		createMap : function () {
			var th = this;
			$('.pigm_instance').each(function () {
				var m = th.maps.length;
				th.maps[m] = {};
				th.maps[m].node = this;
				th.maps[m].locs = [];
				th.categories[m] = [];
				th.marked[m] = [];
				
				//set master class
				$(this).addClass('pigm'+m);
				
				//bounds
				th.maps[m].bounds = new google.maps.LatLngBounds();
				
				var c = $(this).find('.pigm').attr('class').split(' ');
				for(k in c) {
					if(/^(single-)[0-9]+$/.test(c[k])) {
						var single = c[k].replace('single-','');
						break
					}
				}

				//add points
				if($(this).find('.pigm').hasClass('single') && typeof(pigm_multiple) == 'undefined') {
					th.maps[m].single = true;
					var n = th.maps[m].locs.length;
					th.maps[m].locs[n] = {};
					th.maps[m].locs[n].title = pigm_single.title;
					th.maps[m].locs[n].url = pigm_single.url;
					th.maps[m].locs[n].addy = pigm_single.addy;
					th.maps[m].locs[n].point = new google.maps.LatLng(pigm_single.lat,pigm_single.lng);
				}
				else if(single) {
					th.maps[m].single = true;
					var n = th.maps[m].locs.length;
					th.maps[m].locs[n] = {};
					for(k in pigm_multiple) {
						if(k == single) {
							th.maps[m].locs[n].title = pigm_multiple[k].title;
							th.maps[m].locs[n].url = pigm_multiple[k].url;
							th.maps[m].locs[n].addy = pigm_multiple[k].addy;
							th.maps[m].locs[n].point = new google.maps.LatLng(pigm_multiple[k].lat,pigm_multiple[k].lng);
							break;
						}
					}
				}
				else {
					for(k in pigm_all) {
						th.categories[m][k] = true;
						for(i in pigm_all[k]) {
							if(!th.marked[m][i]) {
								var n = th.maps[m].locs.length;
								th.maps[m].locs[n] = {};
								th.maps[m].locs[n].id = i;
								th.maps[m].locs[n].point = new google.maps.LatLng(pigm_all[k][i].lat,pigm_all[k][i].lng);
								th.maps[m].locs[n].title = pigm_all[k][i].title;
								th.maps[m].locs[n].addy = pigm_all[k][i].addy;
								th.maps[m].locs[n].vis = true;
								th.marked[m][i] = true;
							}
						}
					}
				}

				//center
				var p = th.maps[m].locs[0].point;
				
				//create map
				th.maps[m].map = new google.maps.Map($(this).find('.pigm').get(0),{ zoom:15,center:p,mapTypeId:google.maps.MapTypeId.ROADMAP });

				//add listeners
				google.maps.event.addListener(th.maps[m].map,'bounds_changed',function() {
					google.maps.event.trigger(th.maps[m].map,'resize');
					th.setInfo(m);
				});
				
				google.maps.event.addListener(th.maps[m].map,'resize',function () {
					th.maps[m].map.setCenter(th.maps[m].map.getCenter());
				});
				
				//add custom info window
				th.maps[m].info = $(this).find('.pigm').append('<div class="pigm_window"><div class="pigm_info"></div><div class="pigm_side"><a class="pigm_close"></a></div></div>').find('.pigm_window');
				eval("th.maps[m].info.find('.pigm_close').bind('click',function () { th.closeInfo("+m+"); })");
				th.maps[m].info.open = null;
				
				//extend bounds
				if(!th.maps[m].single) {
					th.maps[m].map.fitBounds(th.maps[m].bounds);
				}
				
				//set view
				th.maps[m].view = new th.overlay(m,th);
				var t = (new Date())/1000;
				
				var hc = $(this).find('.pigm').hasClass('no-info');
				
				th.timer[m] = setInterval(function () {
					if(th.maps[m].view.getProjection()) {
						th.maps[m].pro = th.maps[m].view.getProjection();
						clearInterval(th.timer[m]);
						//open info
						if(th.maps[m].single && !hc) {
							th.openInfo(m,0);
						}
					}
					else if((t+5) < (new Date())/1000) {
						clearInterval(th.timer[m]);
					}
				},100);
				
				//add markers
				th.addMarkers(m);
				
				
				//th.openMarkers(m);
			
			});
			
			th.removeFromQueue();
		},
		addMarkers : function (m) {
			var th = this;
			for(var n=0;n<this.maps[m].locs.length;n++) {
				th.maps[m].locs[n].mark = new google.maps.Marker({
					position : th.maps[m].locs[n].point,
					map : th.maps[m].map,
					visible : true
					//shape : 'rect'
				});
				
				//info window
				/*
				th.maps[m].locs[n].info = new google.maps.InfoWindow({
					content : '<h2>'+th.maps[m].locs[n].title+'</h2>'
				});
				*/
				
				//set marker
				th.setMarker(m,n);
				
				//extend bounds				
				th.maps[m].bounds.extend(th.maps[m].locs[n].point);
			}
		},
		displayMarkers : function (m,a) {
			this.marked[m] = [],a = a ? a : false;
			
			
			for(var n=0;n<this.maps[m].locs.length;n++) {
				if(a) {
					this.maps[m].locs[n].vis = true;
					this.marked[m][i] = true;
				}
				else {
					for(k in this.categories[m]) {
						var i = this.maps[m].locs[n].id;
						if(this.categories[m][k]) {
							if(!pigm_all[k][i]) {
								this.maps[m].locs[n].vis = false;
								break;
							}
							if(pigm_all[k][i]) {
								this.maps[m].locs[n].vis = true;
								this.marked[m][i] = true;
							}
						}
						else if(!this.marked[m][i]) {
							this.maps[m].locs[n].vis = false;
						}
					}
				}
				
				if(this.maps[m].locs[n].vis == false) {
					this.maps[m].locs[n].mark.setMap(null);
				}
				else if(!this.maps[m].locs[n].mark.getMap()) {
					this.maps[m].locs[n].mark.setMap(this.maps[m].map);
				}
			}
			this.closeInfo(m);
			
		},
		hideMarkers : function (m) {
			for(var n=0;n<this.maps[m].locs.length;n++) {
				this.maps[m].locs[n].mark.setMap(null);
			}
		},
		setMarker : function (m,n) {
			var th = this;
			google.maps.event.addListener(th.maps[m].locs[n].mark,'click',function() {
				if(th.maps[m].info.open == n && th.maps[m].info.open !== null) {
					th.addToQueue(function () { th.closeInfo(m); });
					th.maps[m].info.open = null;
				}
				else if(th.maps[m].info.open !== null) {
					th.addToQueue(function () { th.closeInfo(m); });
					th.addToQueue(function () { th.openInfo(m,n);th.removeFromQueue(); });
				}
				else {
					th.openInfo(m,n);
				}
			});
		},
		openInfo : function (m,n) {
			//this.maps[m].view = new this.overlay(m,this);
			//this.maps[m].pro = this.maps[m].view.getProjection();
			this.maps[m].info.open = n;
			this.maps[m].info.find('.pigm_info').html('<div><h2><a href="'+this.maps[m].locs[n].url+'">'+this.maps[m].locs[n].title+'</a></h2>'+this.address(m,n)+this.directions(m,n)+'</div>');
			var t = this.setInfo(m,true);
			this.maps[m].info.css({ opacity:0,display:'block' }).animate({ opacity:1,top:t-10 },{duration:350,queue:false,easing:'easeOutExpo'});
		},
		setInfo : function (m,o) {
			if(this.maps[m].info.open !== null) {
				var p = this.maps[m].pro.fromLatLngToContainerPixel(this.maps[m].locs[this.maps[m].info.open].point);
				var t = o ? p.y-47 : p.y-57;
				this.maps[m].info.css({ top:t,left:p.x+13 });
				return t;
			}
		},
		closeInfo : function (m) {
			var th = this;
			th.maps[m].info.animate({ opacity:0,top:th.maps[m].info.position().top+10 },{ duration:350,queue:false,easing:'easeOutExpo',complete:function () { th.maps[m].info.css({ display:'none' });th.removeFromQueue(); } });
			th.maps[m].info.open = null;
		},
		openMarkers : function (m) {
			for(k in this.maps[m].locs) {
				//this.maps[m].locs[k].info.open(this.maps[m].map,this.maps[m].locs[k].mark);
			}
		},
		address : function (m,n) {
			var s = '<p>'+this.maps[m].locs[n].addy.line1+'<br />';
			s += this.maps[m].locs[n].addy.line2.length > 0 ? this.maps[m].locs[n].addy.line2+'<br />' : '';
			s += this.maps[m].locs[n].addy.city+', '+this.maps[m].locs[n].addy.state+' '+this.maps[m].locs[n].addy.zip;
			s += this.maps[m].locs[n].addy.country.length > 0 ? '<br />'+this.maps[m].locs[n].addy.country : '';
			return s+'</p>';
		},
		directions : function (m,n) {
			var s = '';
			for(k in this.maps[m].locs[n].addy) {
				if(this.maps[m].locs[n].addy[k].length > 0) {
					s += s.length > 0 ? '+' : '';
					s += this.maps[m].locs[n].addy[k].replace(/\s/g,'+');
				}
			}
			return '<a href="http://maps.google.com/maps?q='+s+'" target="_blank">Click here for directions.</a>';
		},
		showAllCategories : function (m) {
			for(i in this.categories[m]) {
				this.categories[m][i] = true;
			}
			this.displayMarkers(m,true);
			return this;
		},
		resetCategories : function (m) {
			for(i in this.categories[m]) {
				this.categories[m][i] = false;
			}
			return this;
		},
		addCategory : function (m,i) {
			var th = this;
			if(th.categories[m][i]) {
				th.categories[m][i] = false;
				$('pigm'+m).find('cat'+i).removeClass('pigm_active');
			}
			else {
				th.categories[m][i] = true;
				$('pigm'+m).find('cat'+i).addClass('pigm_active');
			}
			this.toggle_categories(m,i);
			th.displayMarkers(m);
		},
		toggle_categories : function (m,i) {
			for(l in this.defaults.toggle) {
				if($.inArray(i,this.defaults.toggle[l]) != -1) {
					for(k in this.categories[m]) {
						if($.inArray(k,this.defaults.toggle[l]) != -1 && k != i) {
							this.categories[m][k] = false;
						}
					}
				}
			}
		},
		getID : function (c,n) {
			var c = c.split(' ');
			var r = new RegExp("^("+n+")[0-9]+$");
			for(k in c) {
				if(r.test(c[k])) {
					return c[k].replace(n,'');
				}
			}
			return false;
		},
		addToQueue :
		function (f,a) {
			this.queue.push([f,a]);
			if(!this.iq) {
				this.startQueue();
			}
		},
		startQueue :
		function () {
			if(this.queue.length > 0) {
				this.iq = true;
				var a = this.queue[0][1] ? this.queue[0][1] : [];
				this.queue[0][0].apply(this,a);
				return;
			}
			this.iq = false;
		},
		removeFromQueue :
		function () {
			this.queue.splice(0,1);
			this.startQueue();
		}
		
	};

})(jQuery);
