/*
 * ContextMenu - jQuery plugin for right-click context menus
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 * Dual licensed under the MIT and GPL licenses:
 * Date: 16 July 2007 Version: r2
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 */
(function($){var menu,shadow,trigger,content,hash,currentTarget;var defaults={menuStyle:{listStyle:'none',padding:'1px',backgroundColor:'#fff',opacity:'0.8',width:'80px'},itemStyle:{margin:'0px',color:'#6F6F6F',display:'block',cursor:'default',padding:'3px',border:'1px solid #fff',cursor:'pointer',fontSize:'0.9em',fontWeight:'bold',backgroundColor:'transparent'},itemHoverStyle:{border:'1px solid #FFC53A',color:'#000',backgroundColor:'#FFE877'},eventPosX:'pageX',eventPosY:'pageY',shadow:true,onContextMenu:null,onShowMenu:null};$.fn.contextMenu=function(id,options){if(!menu){menu=$('<div id="jqContextMenu"></div>').hide().css({position:'absolute',zIndex:'500'}).appendTo('body').bind('click',function(e){e.stopPropagation();});}
if(!shadow){shadow=$('<div></div>').css({backgroundColor:'#000',position:'absolute',opacity:0.1,zIndex:499}).appendTo('body').hide();}
hash=hash||[];hash.push({id:id,menuStyle:$.extend({},defaults.menuStyle,options.menuStyle||{}),itemStyle:$.extend({},defaults.itemStyle,options.itemStyle||{}),itemHoverStyle:$.extend({},defaults.itemHoverStyle,options.itemHoverStyle||{}),bindings:options.bindings||{},shadow:options.shadow||options.shadow===false?options.shadow:defaults.shadow,onContextMenu:options.onContextMenu||defaults.onContextMenu,onShowMenu:options.onShowMenu||defaults.onShowMenu,eventPosX:options.eventPosX||defaults.eventPosX,eventPosY:options.eventPosY||defaults.eventPosY});var index=hash.length-1;$(this).hoverIntent(function(e){var bShowContext=(!!hash[index].onContextMenu)?hash[index].onContextMenu(e):true;if(bShowContext)display(index,this,e,options);return false;},function(){return false;});return this;};function display(index,trigger,e,options){var cur=hash[index];content=$('#'+cur.id).find('ul:first').clone(true);content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(function(){$(this).css(cur.itemHoverStyle);},function(){$(this).css(cur.itemStyle);}).find('img').css({verticalAlign:'middle',paddingRight:'2px'});menu.html(content);if(!!cur.onShowMenu)menu=cur.onShowMenu(e,menu);$.each(cur.bindings,function(id,func){$('#'+id,menu).bind('click',function(e){hide();func(trigger,currentTarget);});});menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();if(cur.shadow)shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();$(document).one('click',hide);}
function hide(){menu.hide();shadow.hide();}
$.contextMenu={defaults:function(userDefaults){$.each(userDefaults,function(i,val){if(typeof val=='object'&&defaults[i]){$.extend(defaults[i],val);}
else defaults[i]=val;});}};})(jQuery);$(function(){$('div.contextMenu').hide();});

/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqmodal/)
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 * $Version: 07/06/2008 +r13
 */
(function($){$.fn.jqm=function(o){var p={overlay:50,overlayClass:'jqmOverlay',closeClass:'jqmClose',trigger:'.jqModal',ajax:F,ajaxText:'<div align=\"center\"><br /><br /><img src=\"files/loader.gif\" title=\"\"  alt=\"Loading...\"/></div><br />',target:F,modal:F,toTop:F,onShow:F,onHide:F,onLoad:F};return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};if(p.trigger)$(this).jqmAddTrigger(p.trigger);});};$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});};$.jqm={hash:{},open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);if(c.modal){if(!A[0])L('bind');A.push(s);}
else if(c.overlay>0)h.w.jqmAddClose(o);else o=F;h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in{Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
if(c.ajax){var r=c.target||h.w,u=c.ajax,r=(typeof r=='string')?$(r,h.w):$(r),u=(u.substr(0,1)=='@')?$(t).attr(u.substring(1)):u;r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
else if(cc)h.w.jqmAddClose($(cc,h.w));if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);(c.onShow)?c.onShow(h):h.w.show();e(h);return F;},close:function(s){var h=H[s];if(!h.a)return F;h.a=F;if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();}return F;},params:{}};var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version=="6.0"),F=false,i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i);f(h);},f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return!r;},hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function(){if(!this[c]){this[c]=[];$(this).click(function(){for(var i in{jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};})(jQuery);

/* Livequery. Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)*/
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);

/* ScollTo & SerialScroll. Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com  */
;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
;(function($){var a='serialScroll',b='.'+a,c='bind',C=$[a]=function(b){$.scrollTo.window()[a](b)};C.defaults={duration:1e3,axis:'x',event:'click',start:0,step:1,lock:1,cycle:1,constant:1};$.fn[a]=function(y){y=$.extend({},C.defaults,y);var z=y.event,A=y.step,B=y.lazy;return this.each(function(){var j=y.target?this:document,k=$(y.target||this,j),l=k[0],m=y.items,o=y.start,p=y.interval,q=y.navigation,r;if(!B)m=w();if(y.force)t({},o);$(y.prev||[],j)[c](z,-A,s);$(y.next||[],j)[c](z,A,s);if(!l.ssbound)k[c]('prev'+b,-A,s)[c]('next'+b,A,s)[c]('goto'+b,t);if(p)k[c]('start'+b,function(e){if(!p){v();p=1;u()}})[c]('stop'+b,function(){v();p=0});k[c]('notify'+b,function(e,a){var i=x(a);if(i>-1)o=i});l.ssbound=1;if(y.jump)(B?k:w())[c](z,function(e){t(e,x(e.target))});if(q)q=$(q,j)[c](z,function(e){e.data=Math.round(w().length/q.length)*q.index(this);t(e,this)});function s(e){e.data+=o;t(e,this)};function t(e,a){if(!isNaN(a)){e.data=a;a=l}var c=e.data,n,d=e.type,f=y.exclude?w().slice(0,-y.exclude):w(),g=f.length,h=f[c],i=y.duration;if(d)e.preventDefault();if(p){v();r=setTimeout(u,y.interval)}if(!h){n=c<0?0:n=g-1;if(o!=n)c=n;else if(!y.cycle)return;else c=g-n-1;h=f[c]}if(!h||d&&o==c||y.lock&&k.is(':animated')||d&&y.onBefore&&y.onBefore.call(a,e,h,k,w(),c)===!1)return;if(y.stop)k.queue('fx',[]).stop();if(y.constant)i=Math.abs(i/A*(o-c));k.scrollTo(h,i,y).trigger('notify'+b,[c])};function u(){k.trigger('next'+b)};function v(){clearTimeout(r)};function w(){return $(m,l)};function x(a){if(!isNaN(a))return a;var b=w(),i;while((i=b.index(a))==-1&&a!=l)a=a.parentNode;return i}})}})(jQuery);
//;(function($){var g=location.href.replace(/#.*/,''),h=$.localScroll=function(a){$('body').localScroll(a)};h.defaults={duration:1e3,axis:'y',event:'click',stop:1};h.hash=function(a){a=$.extend({},h.defaults,a);a.hash=0;if(location.hash)setTimeout(function(){i(0,location,a)},0)};$.fn.localScroll=function(b){b=$.extend({},h.defaults,b);return(b.persistent||b.lazy)?this.bind(b.event,function(e){var a=$([e.target,e.target.parentNode]).filter(c)[0];a&&i(e,a,b)}):this.find('a,area').filter(c).bind(b.event,function(e){i(e,this,b)}).end().end();function c(){var a=this;return!!a.href&&!!a.hash&&a.href.replace(a.hash,'')==g&&(!b.filter||$(a).is(b.filter))}};function i(e,a,b){var c=a.hash.slice(1),d=document.getElementById(c)||document.getElementsByName(c)[0],f;if(d){e&&e.preventDefault();f=$(b.target||$.scrollTo.window());if(b.lock&&f.is(':animated')||b.onBefore&&b.onBefore.call(a,e,d,f)===!1)return;if(b.stop)f.queue('fx',[]).stop();f.scrollTo(d,b).trigger('notify.serialScroll',[d]);if(b.hash)f.queue(function(){location=a.hash;$(this).dequeue()})}}})(jQuery);

/* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+  <http://cherne.net/brian/resources/jquery.hoverIntent.html>*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:5,interval:400,timeout:200};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {return -c * ((t=t/d-1)*t*t*t - 1) + b;};

/* Cookie Plugin Copyright (c) 2006 Klaus Hartl (stilbuero.de) */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};

	// Define global variable for the jqmodal to show file info
	var idShow;

	//Initialise stuff here for document ready
	$(document).ready(function(){
		$('#q').toggleVal();
		$('#title').toggleVal();
		// Initialise modal box for file info
		$('#jInfo').jqm({
			ajaxText: '<img src="files/loader.gif" align="center" alt="Loading..." />',
		    onShow: function(hash) {
		        hash.w.load('controllers/loadinfo.php?id='+idShow);
		        hash.w.show();
		    }, ajax: false
		});
		$('#alert').jqm({modal: false, trigger: false});		
		// For a first time visitor, set a cookie for their playlist
		initCookie();	
	});

	//For hiding default text in input boxes when they are selected
	jQuery.fn.toggleVal=function(focusClass){this.each(function(){$(this).focus(function(){if($(this).val()==this.defaultValue){$(this).val("")}if(focusClass){$(this).addClass(focusClass)}}).blur(function(){if($(this).val()==""){$(this).val(this.defaultValue)}if(focusClass){$(this).removeClass(focusClass)}})})}

	// Fix clear type on MSIE
	jQuery.fn.fixClearType = function(){return this.each(function(){if(typeof this.style.filter  && this.style.removeAttribute)this.style.removeAttribute("filter");})}

	// Override javascript alert with a modal box
	function alert(msg) {
		$('#alert').jqmShow().find('div.content').html(msg);
	}

	// For scrolling the main panels of the page
	jQuery(function( $ ){
		$('div#frame').serialScroll({
			target:'div#sections',
			items:'li',
			axis:'xy',
			navigation:'#navigation li a',
			duration:300,
			force:true, 
			
			onBefore:function( e, elem, $pane, $items, pos ){
				e.preventDefault();
				if( this.blur )
					this.blur();
			},
			onAfter:function( elem ){
			}
		});
	});

	// Adds right-click menu to random searchlist - clicking I Want More link
    $('ol.searchlist li').livequery(function(){ 
		$(this).contextMenu('searchlist_menu', {
		    bindings: {
		        'Add': function(t) {
				  // Add this laugh to the playlist
				  var laugh = $(t).attr('id');
				  var reload = saveLaugh(laugh);
				  if (reload == true) {
					loadLaugh();
				  }
				},
		        'Save': function(t) {
				  // Download the laugh as an mp3
		          window.location = $(t).find('a').attr('href');
				  return false;
		        },
		        'Info': function(t) {
				  // Set global variable to show info for this id
				  idShow = $(t).attr('id');
				  // Call the modal box
				  $('#jInfo').jqmShow().fixClearType() ; 
		        }
		    }
		});
	});
	
	// Adds right-click menu to playlist
	$('ol.playlist li').livequery(function(){ 
		$(this).contextMenu('playlist_menu', {
	      bindings: {
	        'Delete': function(t) {
				var laugh = $(t).attr('id');
				delLaugh(laugh);
				//$(t).fadeTo(200, 0,function(){$(this).remove();});
	        },
	        'Save': function(t) {
	          window.location = $(t).find('a').attr('href');
			  return false;
	        },
		    'Info': function(t) {
				// Set global variable to show info for this id
				 idShow = $(t).attr('id').substring(1,5);
				 // Call the modal box
				 $('#jInfo').jqmShow().fixClearType() ; 
	        }
	      }
	    });
	});
	
	// Populates the list with 5 more random laughs
	$('.more').click(function() {
		// Blacklist to ensure that any laughs already in the playlist don't appear in the random list
		var blacklist = $.cookie('laughplaylist');
		var _url = 'controllers/loadmore.php';
		var loader = '<div align=\"center\"><br /><br /><img src=\"files/loader.gif\" title=\"\"  alt=\"Loading...\"/></div>';
		$('#searchresults').empty().append(loader);
		// Ajax call 
		$.ajax({ type: 'GET', url: _url, data: 'load=5&blacklist='+blacklist, async: false,
			success: function(data){$('#searchresults').html(data);}
			//error: $("#searchresults").html('Something went wrong, try again.')
		});  
		return false;
	});
	
	// Open Help in a popup window - consider a modal box?
	$('.help').click(function() {
		window.open('help.html','this','width=510,height=600,scrollbars=yes');
		return false;
	});
	
	// Open Terms in a popup window
	$('.terms').click(function() {
		window.open('terms.html','this','width=510,height=600,scrollbars=yes');
		return false;
	});
	
	// Views the current cookie values
	$('.cookieview').click(function() {
		alert('Playlist Ids: '+$.cookie('laughplaylist'));
        return false;
    });
	
	// Deletes the playlist cookie
	$('.delplaylist').click(function() {
		$.cookie('laughplaylist', null);
		initCookie();
		alert ('Your playlist has been deleted');
		return false;
    });
	
	// Initialise a playlist cookie
	function initCookie(){
		if ($.cookie('laughplaylist') == null || $.cookie('laughplaylist') == '') {
			// Set a cookie if none exists - 3 months
			$.cookie('laughplaylist', '0', { expires: 90 });
			loadLaugh();
		} else if ($.cookie('laughplaylist') == '') {
			$.cookie('laughplaylist', null);
		} else {
			// Load the previous playlist
			loadLaugh();	
		}
	}	

	// Store new ids in the playlist cookie
	function saveLaugh(laughfile){
		var data = $.cookie('laughplaylist').split(",");
		// max_playlist default is 12
		var max_playlist = 12;
		if (data.length < max_playlist) {
			// Will only store one of each id - multiple audio files tend to confuse soundManager2
			isAlreadySaved = false;
			for(var i=0; i<data.length; i++){
			    if(data[i] == laughfile){
					isAlreadySaved = true;
					alert("You've got this one already.");
					return false;
			    }
			}
			if(!isAlreadySaved) {
				data.push(laughfile);
			    $.cookie('laughplaylist',data.toString());
			}
			return true;
		} else {
			alert ("Oops, your playlist is full! You might have to delete a precious laugh to fit more in.");
			return false;
		}
	}
	
	// Loads the laugh playlist on each refresh
	function loadLaugh(){
	
		var laughdata = $.cookie('laughplaylist').split(",");
		if (laughdata != '' && laughdata != '0') {
			var _url = 'controllers/loadplaylist.php';
			var loading = '<div align=\"center\"><img src=\"files/loader.gif\" title=\"\" alt=\"Loading...\"/></div>';
			$('ol.playlist').empty().append(loading);
			$.ajax({ type: 'GET', url: _url, data: 'id='+$.cookie('laughplaylist'), async: false,
				success: function(data) {
					$('ol.playlist').html(data);
				} //error: $("#playlist").html('Empty')
				
			});
			//InlinePlayer.init();			
		} else {	
			//alert('got here');
			$("ol.playlist").html('Your Playlist is empty. <a href="#" onClick="saveLaugh(14);loadLaugh();" title="Add the first laugh">Add a laugh?</a>');
			return false;
		}
	}
	
	// Deletes the laughfile id in the cookie and reloads the playlist
	function delLaugh(laughfile){
		if (laughfile) {
			var data = $.cookie('laughplaylist').split(",");
			// Delete the value with an index of laughfile
			data.splice(data.indexOf(laughfile), 1);
			// Resave the altered cookie
			$.cookie('laughplaylist',data.toString());
			// Reload the playlist
			loadLaugh();
			return true;
		} else {
			alert ("Could not be deleted.");
			return false;
		}
	}
