// JavaScript Document



var GGL = {
	friend: {
		init:function() {
			if($$("home")) {
				var sl = $$("home").elmsByClass('sitelinks').first();
				GGL.util.insertBegin(sl,document.createTextNode(' - '));
				var ln = sl.create('a',{"href":"#"},false,'Send a Giggle to a Friend');
				GGL.util.insertBegin(sl,ln);
				ln.addEvent('click',GGL.friend.show);
			}
			


//			<a href="#">Send Giggle to a Friend</a> - <a href="#">Set as Homepage</a> - 

		},

		show:function(e) {
			var h,f,mp;
			mp = GGL.util.mousePos(e);
			GGL.pd(e);
			h = $$("home");
			if($$("friendform")) {
				f = $$("friendform");
				f.innerHTML = '';
			} else {
				f = h.create('form',{"action":"/","method":"post","id":"friendform"},false);
				f.style.top = (mp.y-80)+'px';
				f.style.left = mp.x+'px';
			}

			f.create('label',{"for":"to"},true,'Your Friend\'s Name & E-mail:');
			f.create('input',{"type":"text","name":"to","id":"to"},true);
			f.create('label',{"for":"from"},true,'Your Name & E-mail');
			f.create('input',{"type":"text","name":"from","id":"from"},true);
			var btns = f.create('div',{"className":"btnzone"},true); // should clear the buttons below the inputs
			btns.create('input',{"type":"submit","value":"Send"},true);
			btns.create('input',{"type":"button","value":"Cancel"},true).addEvent('click',GGL.friend.cxl);
			btns.create('img',{"src":"/images/loading-small.gif","width":"16","height":"16","alt":""},true).addClass('loading').addClass('hidden');
			
			f.addEvent('submit',GGL.friend.send);
			
			h.addContent(f);

			f.style.width = f.offsetWidth+'px';
			GGL.util.trackAction('tellFriend/form');
			
		},

		send:function(e) {
			GGL.pd(e);
			var f = $$("friendform");
			if(!f.processing) {
				var data = '';
				data += '&to='+$$("to").value;
				data += '&from='+$$("from").value;
				f.ajax({"url":"/api/tellfriend.php","method":"POST","params":data,"callback":GGL.friend.showResult});
				f.processing = true;
				f.elmsByClass('loading').removeClass('hidden');
			}
		},

		showResult:function(rt) {
			var r,f;
			f = $$("friendform");
			f.processing = false;
			f.elmsByClass('loading').addClass('hidden');
			r = eval('('+rt+')'); 
			if(!r.friend) {
				// this means there was probably malicious intent
				GGL.friend.cxl();
			} else if(!r.friend.errors) {
				f.replaceContent('<p>Your friend has been told about GiggleSearch.org.  Be sure to mention it again next time you speak!</p>');
				setTimeout(GGL.friend.cxl,2500);
				GGL.util.trackAction('tellFriend/success');
			} else {
				if(r.friend.errors.to) {
					GGL.util.showErr(decodeURIComponent(r.friend.errors.to),$$("to"));
				}

				if(r.friend.errors.from) {
					GGL.util.showErr(decodeURIComponent(r.friend.errors.from),$$("from"));
				}

				if(r.friend.errors.mail) {
					GGL.util.showErr('Sorry, there was a problem with the mailserver.',$$("to"));
				}
				GGL.util.trackAction('tellFriend/error');
			}
		},

		cxl:function(e) {
			GGL.pd(e);
			$$("friendform").hide({duration:300,remove:true});
		}

	},

	homepage: {
		init:function() {
			if($$("home") && "undefined" !== typeof BrowserDetect) {
				var sl = $$("home").elmsByClass('sitelinks').first();
				GGL.util.insertBegin(sl,document.createTextNode(' - '));
				var ln = sl.create('a',{"href":"#"},false,'Set GiggleSearch as your homepage');
				GGL.util.insertBegin(sl,ln);
				ln.addEvent('click',GGL.homepage.show);
			}

		},
		
		show:function(e) {

			var instruction,mp,h,f;
			if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 7) {
				instruction = '<p>Drag the icon to the left of the URL in your location bar onto the "Home" icon or the "house" icon in your toolbar.</p>';
			} else if(BrowserDetect.browser == 'Explorer') {
				instruction = '<ol><li>Click on the "down" arrow just to the right of the "house" icon in your Internet Explorer toolbar</li> <li>choose "Add or Change Home Page."</li><li>Then click on "Use this webpage as your only home page" or "Add this webpage to your home page tabs," whichever you prefer.</li></ol>';
			} else if(BrowserDetect.browser == 'Opera') {
				instruction = '<ol><li>Select "Preferences" in either the "Tools" menu, (Windows), or the "Opera" menu, (Mac).</li><li>If it is not already selected, click the "General" tab, (the one on the left)</li><li>On the Home Page line in the first section enter "http://bonzobox.com" (without quotation marks), in the box</li></ol>';
			} else {
				instruction = '<p>Drag the icon to the left of the URL in your location bar onto the "Home" icon or the "house" icon in your toolbar.</p>';
			}

			
			mp = GGL.util.mousePos(e);
			GGL.pd(e);
			h = $$("home");
			if($$("homenotice")) {
				f = $$("homenotice");
				f.innerHTML = '';
			} else {
				f = h.create('div',{"id":"homenotice"},false);
				f.style.top = (mp.y-80)+'px';
				f.style.left = (mp.x-150)+'px';
			}

			f.style.width = '300px';

			f.create('h4',{},true,'Set your Homepage');
			f.addContent(instruction);
			f.create('a',{"href":"/"},true,'Close').addEvent('click',GGL.homepage.cxl)

			h.addContent(f);
			GGL.util.trackAction('makeHome');
		},
		
		cxl:function(e) {
			GGL.pd(e);
			$$("homenotice").hide({duration:300,remove:true});
		}

	},
	
	fact: {
		init:function() {
			if($$('gigglefact-more')) {
				$$('gigglefact-more').addEvent('click',GGL.fact.another);
			}
		},
		
		another:function(e) {
			GGL.pd(e);
			var url = '/api/singlefact.php';
			if(this.fid) {
				url += '?l='+this.fid;
			}
			$(this).post(url,GGL.fact.show);
			var fl = GGL.util.getPar({"className":"factlinks"},this);
			$(fl).elmsByClass('loading').first().removeClass('hidden');
			GGL.util.trackAction('loadnewfact');
		},
		
		show:function(rt) {
			var r = eval('('+rt+')');
			if(r.fact) {
				var p = GGL.util.getPar({"className":"gigglefact"},this);
				p.r = r;
				$(p).hide({duration:300,callback:GGL.fact.doShow});
			}
		},
		
		doShow:function() {
			var p,t,s,fl,r;
			p = this;
			r = p.r;
			$(p).hide({duration:100});
			
			t = p.elmsByClass('ftext').first();
			s = p.elmsByClass('gigglefact-source').first();
			fl = p.elmsByClass('factlinks').first();
			t.innerHTML = decodeURIComponent(r.fact.text);
			s.href = decodeURIComponent(r.fact.source);
			this.fid = decodeURIComponent(r.fact.id);
			fl.elmsByClass('loading').addClass('hidden');
			$(p).show({duration:300});
		
		
		}
	},
	
	
	pd:function(e) {
		e = e||window.event;
		if(typeof e !== 'undefined' && e !== null) {
			DOMAssistant.preventDefault(e);
		}
	},
	
	util: {
		setCookie:function(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},
		
		readCookie:function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},

		eraseCookie:function(name) {
			GGL.util.setCookie(name,"",-1);
		},
		
		getPar:function(params,obj) {
		
			function matches(obj) {
				
				if(params.className && params.tag) {
					if(obj.hasClass(params.className) && obj.tagName.strToUpper() == params.tag.strToUpper()) {
						return true;
					}
				} else if(params.className) {
					if(obj.hasClass(params.className)) {
						return true;
					}
				} else if(params.tag) {
					if(obj.tagName.strToUpper() == params.tag.strToUpper()) {
						return true;
					}
				}
				return false;
			}
			
			var p = obj;
			while(p = p.parentNode) {
				p = $(p);
				if(matches(p)) {
					return p;
				}
			}
		},
		
		insertBegin:function(par,obj) {
			if(par.hasChildNodes()) {
				var r = par.firstChild;
				par.insertBefore(obj,r);
			} else {
				$(par.addContent(obj));
			}
		},
		
		mousePos:function(e) {
			var posx = 0;
			var posy = 0;
			if (!e) var e = window.event;
			if (e.pageX || e.pageY) 	{
				posx = e.pageX;
				posy = e.pageY;
			}
			else if (e.clientX || e.clientY) 	{
				posx = e.clientX + document.body.scrollLeft
					+ document.documentElement.scrollLeft;
				posy = e.clientY + document.body.scrollTop
					+ document.documentElement.scrollTop;
			}
			return {"x":posx,"y":posy};
		},
		
		showErr:function(msg,obj) {
			var er,p;
			p = obj.parentNode;
			if(!$(obj.previousSibling).hasClass('error')) {
				er = $(obj).create('span',{className:"error"},false,msg);
				p.insertBefore(er,obj);
			}
		},
		
		
		trackAction:function(action) {
			if(pageTracker && typeof pageTracker._trackPageview != 'undefined') {
				pageTracker._trackPageview("/actions/"+action); 
			}
		}
	},
	
	sounds: {
	
		sequence:0,
		init:function() {
			if(soundManager.readyToLaugh === true) {	
				for(var i=0;i<giggleSource.length;i++) {
					var params = {
					  id: giggleSource[i].id,
					  url: '/uploaded/giggles/' + giggleSource[i].filename,
					  autoLoad: true
					};
					
					giggles.push(soundManager.createSound(params));
				}
				
				$('#soundcontrol a').first().addEvent('click',GGL.sounds.mute);
				$$("make_me_giggle").addEvent('click',GGL.giggle);
				$$('cse-search-box').addEvent('submit',GGL.giggle);
				
				if('undefined' !== typeof BrowserDetect) {
					if(BrowserDetect.browser == 'Explorer') {
						document.title = GGL.orgtitle;
					}
				}
				
				
			} else {
				soundManager.onload = function() { soundManager.readyToLaugh = true; GGL.sounds.init(); }
			}
			
		},
		
		getMore:function() {
			if(GGL.sounds.sequence >= (giggles.length - 3)) {
				var avoid='';
				for(var i=0;i<giggles.length;i++) {
					avoid += giggles[i].sID+',';
				}
				
				$('#soundcontrol a').first().ajax({
					"url":"/api/getsounds.php",
					"params":"avoid="+encodeURIComponent(avoid),
					"method":"POST",
					"callback":GGL.sounds.merge
				});
			}
		},
		
		merge:function(resp) {
			var newSounds = eval(resp);
			if(newSounds.length > 0) {
				for(var i=0;i<newSounds.length;i++) {
					giggles.push(soundManager.createSound({
					  id: newSounds[i].id,
					  url: '/uploaded/giggles/'+newSounds[i].filename,
					  autoLoad: true
					}));
				}
			} else {
				GGL.sounds.sequence = 0;			
			}
		},
		
		isMuted:function() {
			if(GGL.util.readCookie('gigglemute') == 'true') {
				return true;
			} else {
				return false;
			}
		},
		
		mute:function() {
			if(GGL.sounds.isMuted()) {
				GGL.util.eraseCookie('gigglemute');
				$('#soundcontrol a').first().removeClass('muted');
			} else {
				GGL.util.setCookie('gigglemute','true',7);
				$('#soundcontrol a').first().addClass('muted');
			}
		}
	},
	
	giggle:function() {
		if(!GGL.sounds.isMuted()) {
			GGL.sounds.getMore();
			if(giggles.length > GGL.sounds.sequence) {
				giggles[GGL.sounds.sequence].play();
				GGL.sounds.sequence++;
			}
			GGL.util.trackAction('giggle');
		}
		return true;
	},
	
	
	init:function() {
		GGL.orgtitle = document.title;
		GGL.homepage.init();
		GGL.friend.init();
		GGL.fact.init();
		GGL.sounds.init()
	}
}

if(DOMAssistant) {
	DOMAssistant.DOMReady(GGL.init);
}
