/**
  * Utiltity Library - combined javascript utilities
  * Includes: $Util, Easing v1.3, jQuery.timers
**/

//so doesn't conflict with mootools
if (typeof jQuery != 'undefined') {
	var $j=jQuery.noConflict();
}

(function (window,$,$j,undefined) { 
    var my = {}, thisElem, hideId, showPopup=false, pageReturn='', loginLnk, statusCookie = 'OP_status';

	function delayHide() {
		thisElem.setStyle("display","none");	
	}
	
	function init_facebook() {
		
		/* facebook initialize function. Called after FB .js file loaded. Needed for facebook connect and like button */
		window.fbAsyncInit = function() {
        FB.init({appId: '215965005084313', status: true, cookie: true,
                 xfbml: true, oauth: true});
			/*
			if(document.getElementById('fb_link'))
			{
				FB.getLoginStatus(updateButton);
	  			FB.Event.subscribe('auth.statusChange', updateButton);
			}*/
		
  
      };	
	} 
	
	/**
	* Remove deprecated properties from jquery to avoid warnings in chrome when hovering
	* over rotator tabs
	*/
	function removeJQDeprecated() {
		var _props = $j.event.props, len = _props.length, res = [];
		for (var x=0;len--;x++) {
		  var el = _props[x];
		  if (el != 'layerX' && el != 'layerY') res.push(el);
		}
    	$j.event.props = res;
	}
	
	/******* Public Methods and Properties *********/

	my.page_return = "";
	
	my.page_init = function() {
		init_facebook();
		my.page_ready_load();
		//my.check_login();
		if(showPopup) {$j(document).ready(function(){my.showPopAd();});}
		my.preload_images();
		//remove hash tag that facebook adds on login redirect
		if (window.location.hash == '#_=_') window.location.hash = '';
		//remove deprecated properties from jquery.
		removeJQDeprecated();
	};
				
	/* Global page ready method. Starts when html is loaded. */
	my.page_ready_load = function() {
		$j(document).ready(function(){
			//special 25th aniv promo. fade in and out mag foldout
			//anniv_mag_fade()
			//$j(document).oneTime(16000,"magfadeout",function(){anniv_mag_fade();});
			my.smooth_scroll();
		});

	};
	

	/**
	* Set popup cookie to display popup
	*
	* If entered from home page then display on third page view.
	* If on any gallery landing page reset counter and display on secone page view.
	* All other pages display on second page view.
	* @param string isHome Home page flag
	* @param string limStart Gallery landing page flag
	* @param string view Page layout
	*/
	
	my.setPopupCookie = function(isHome,limStart,view) {
		var cooName = 'subpop';
		var cVal = {};
		var ret = false;
		//24hr flag. true = display once a day
		//false = fallow display logic. If first come to home page then display on 3rd view. If come to gallery landing reset counter 
		var onceADay = true;
		
		if(cooVal=my.getCookie(cooName)) {
			
			if(!onceADay) {
			
				cValObj = my.explode_to_object(cooVal,'&');
				cValObj.count = parseInt(cValObj.count);
								
				//only if popup not displayed
				if(cValObj.popup==='0') {
					
					cValObj.count++;
					
					//If gallery landing first page reset counter
					if(limStart==='0' && view==='images') {
						cValObj.home = '0';
						cValObj.count = 1;
					} else {
						
						if(cValObj.home=='1') {
							
							if(cValObj.count>2) {
								
								ret = true;
								cValObj.popup = '1'; 
							}
								
						} else {
							
							ret = true;
							cValObj.popup = '1'; 
						}
						
					}
						
					var newCVal = my.implode_to_string(cValObj,'&');
					//console.log('new: ' + newCVal);
					my.setCookie(cooName,newCVal,1); //set visited cookie. Will expire in 24 hours.
				}
			
			}
		
		} else { 
			my.setCookie(cooName,'home=' + isHome + '&count=1&popup=0',1); //set visited cookie. Will expire in 24 hours.
			if(onceADay) ret = true;
		}
		
		showPopup = ret;
	};
	
	//Set sign-in/out link
	my.setLogin = function() {
		
		loginLnk = $j('#login');
		
		if(my.getCookie(statusCookie)) {//Check for cookie. Set to Sign-Out and make sure still logged in.
			my.setSignOutLink();		
			my.checkLoginStatus();	
		} else {//User not logged in set to Sign-In
			my.setSignInLink();
	
		}
		
	};
	
	my.checkLoginStatus = function() {
	
		//If user is logged out then change to Sign-In
		$j.ajax({url: '/index.php?option=com_ajaxcomments&protocol=json&task=login.check&tmpl=component&format=raw',
				type: "POST",
				dataType: "json",
				success: my.checkLoginResp/*,
				error: my.http_error_response*/
				});
	};
	
	my.checkLoginResp = function(resp) {
		//If user not logged in change link to Sign-In and remove cookie
		if(!resp.login) {
			my.setSignInLink();
			my.expCookie(statusCookie);
		}
	};
	
	my.setSignInLink = function() {
		loginLnk.attr('href','/login.html?return=' + pageReturn);
		loginLnk.html('Sign-In');	
	}
	
	my.setSignOutLink = function() {
		loginLnk.attr('href','/logout.html?task=logout&return=' + pageReturn);
		loginLnk.html('Sign-Out');
	}
	
	/* set page return variable */
	my.setReturn = function(ret) { 
		pageReturn = ret;
	};
	
	my.getReturn = function() { 
		return pageReturn;
	};
	
    my.hide = function (elem) { 
		elem.setStyle("display","none");        

    }; 
		
	my.hideDelay = function (elem,msec) {
		thisElem = elem;
		hideID = delayHide.delay(msec);
		return hideID;
	
	};
		
	my.display = function (elem) { 
		
		//alert(typeof elem);
		if(typeof elem == "object")
			elem.setStyle("display","block");
		else
		{
			var obj = $(elem);
			obj.setStyle("display","block");
		}

    }; 
		
	/*** Sets cookie to expire number of days ***/
	my.setCookie = function (name,value,expDays) {
		if(name) {
			var expDate = new Date();
			var expSecs = expDate.getTime();  //Get the milliseconds since Jan 1, 1970
			expSecs += 3600*1000*24*expDays;  //add days in milliseconds
			expDate.setTime(expSecs); //Set expire date
			document.cookie = name + "=" + escape(value) + ';path=/' + ((expDays==null) ? "" : ";expires="+expDate.toUTCString());
		}
	};
	
	/* Remove cookie */
	my.expCookie = function(name) {
		document.cookie = name + '=;path=/;expires=1';					
	}
	
	/*** Checks if cookie exists ***/
	my.getCookie = function (c_name) 	{
	
	//are there any cookies
	if (document.cookie.length>0)
	  {
	  //find specific cookie value
	  c_start=document.cookie.indexOf(c_name + "=");
	  
	  //extract cookie value
	  if (c_start!=-1)
		{
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return false;
	};
	
	/*** Check if cookie exists ***/
	my.isCookie = function (c_name) 	{
	
	//are there any cookies
	if (document.cookie.length>0)
	  {
	  //get cookie value
	  c_start=document.cookie.indexOf(c_name + "=");
	  
	  //if value then cookie valid
	  if (c_start!=-1) {return true;}
	  
	  }
	return false;
	};
	
	//Selects matching option in selector by text
	my.selMatchByText = function (sel,val) {
		
		var cat = $j(sel);
			//Loop through each category item to find matching
			cat.children().each(function(i,opt) {
				var st = $j.trim($j(opt).text());
				
				if(st==val) 
				{
					$j(opt).attr('selected','selected');
					return;
				}
	
			});
		
	};
	
	my.showPopAd = function() {
			
		var _popForm = $('popad');
		
		if(_popForm) {
			//add click event for popup form. will cancel closing if popup clicked
			_popForm.addEvent('click',function() {clearTimeout(hideId);});
			
			//horizontally center popup in column1 div parent container
			//my.dispElemInCont(null,_pop,false,false,24,185);
			my.display(_popForm);
			
			//delay closing of popup
			hideId = my.hideDelay(_popForm,15000);
		}
		
	};

	my.closePopAd = function () 
	{
		my.hide($('popad'));
	};
	
	my.paging_img_switch = function(img,dir,flag)
	{
		
		if(flag=="over")
		{
			img.src = "/templates/op/images/" + dir + "-active.png";
		}
		else
		{
			img.src = "/templates/op/images/" + dir + "-inactive.png";
		}
		
	};
	
	my.preload_popup_images = function()
	{
		var img = new Image(328,375);
		var img2 = new Image(350,400);	
		img.src = "/templates/op/images/sub_bkg-gift.jpg";
		img2.src = "/templates/op/images/sub_pop_bkg.png";
	};
	
	my.preload_images = function()
	{
		img1 = new Image(9,13);
		img2 = new Image(9,13);
		img3 = new Image(9,13);
		img4 = new Image(9,13);		
		img1.src = "/templates/op/images/next-active.png";
		img2.src = "/templates/op/images/prev-active.png";
		img3.src = "/templates/op/images/next-inactive.png";
		img4.src = "/templates/op/images/prev-inactive.png";
	};
	
	my.smooth_scroll = function() {

		   $j('.scrollTop').click(function() {
			
		   //var newHash='#page_bg';
		   var target=$j('body').offset().top,
		   duration=800,
		   easing='easeOutQuint';
		   // animate to target
		   $j('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing);
		   //Cancel click event
		   return false;
	
		});
	};
	
	/**
	* Check if user is logged in and set sign-in link
	*/
	my.check_login = function() {
	$j.ajax({url: 'index.php?option=com_ajaxcomments&protocol=json&task=login.check&tmpl=component&format=raw',
				type: "GET",
				dataType: "json",
				success: my.check_login_response,
				error: my.http_error_response
				});
	};
	
	/**
	* Response handler for check_login()
	*/
	my.check_login_response = function(resp) {
		$j(document).ready(function() {
						
			if(resp.login) 
				$j('#signin_link').attr('href','/logout.html').html('Sign-Out');
			else
				$j('#signin_link').attr('href','/index.php?option=com_user&view=login&return=' + $Util.page_return).html('Sign-In');
			
			/*//Replace poll form token. Does not work.
			var poll_form = $j('#poll_wrap').find('form');
				
			if(poll_form.length) {
				my.replaceTokens(resp.token);
			}
			*/
			});
			
				
	};
		
	my.http_error_response = function(xhr,status) {
		//alert('Error Encountered: HTTP ' + xhr.status + ' ' + xhr.statusText);	
	};
	
	my.submitContact = function(frm) {
		
		var valid = document.formvalidator.isValid(frm);
		
		if(valid===true) {
			$j('#load-spin').removeClass('invisible');
			$('emailForm').send({onComplete: function(data) {
				$j('#load-spin').addClass('invisible');
				alert('Your message has been submitted.');
				window.parent.document.getElementById('sbox-window').close();				
			}});
		}
		      		
	};
	
	/**
	* Will convert key=val string delimited by delim into an object
	*
	* @param string str Url query string
	* @param string delim Value delimiter
	* @return object
	*/
	
	my.explode_to_object = function(str,delim) {
		var cArr = str.split(delim);
		var cObj = new Object;
		var cLen = cArr.length;
		for(var cnt=0;cLen--;cnt++) {
			var cStr = new String(cArr[cnt]);
			var cElem = cStr.split('=');
			cObj[cElem[0]] = cElem[1];
		}
		
		return cObj;
	};
	
	/**
	* Convert Object into key=val string delimited by delim
	*
	* @param string str Url query string
	* @param string delim Delimeter
	* @return object
	*/
	
	my.implode_to_string = function(obj,delim) {
		var len = obj.length;
		var str = '';
		var elem;
		
		for(elem in obj) {
			str += delim + elem + '=' + obj[elem];	
		}
		str = str.substr(1);
		return str;
	};
	
	/**
	* Replace all tokens in document
	*/
	my.replaceToken = function (n)
	{//mootools script
		$(document).getElements('input').each(function(e){
			if (e.getProperty('name') && e.getProperty('name').length == 32 && e.getProperty('value') == '1' && e.getProperty('type') == 'hidden') {
				e.setProperty('name', n);
			}
		});
	};
	
	/**
	* Get url querystring value
	*/
	my.getQuery = function(key, _def) {
	  if (_def==null) _def=""; 
	  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	  var qs = regex.exec(window.location.href);
	  if(qs == null)
		return _def;
	  else
		return qs[1];
	};
	
	//base 64 decode	
	var b64array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	my.decode64 = function(input) {
		var output = "", hex = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "",i = 0,len=input.length;
		do {
			enc1 = b64array.indexOf(input.charAt(i++));
			enc2 = b64array.indexOf(input.charAt(i++));
			enc3 = b64array.indexOf(input.charAt(i++));
			enc4 = b64array.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {output = output + String.fromCharCode(chr2);}
			if (enc4 != 64) {output = output + String.fromCharCode(chr3);}
			chr1 = chr2 = chr3 = enc1 = enc2 = enc3 = enc4 = "";
		} while (i < len);
		return output;
	};
		
    if(window.$Util === undefined) {
		window.$Util = my;
	} else {throw new Error('$Util is already defined. Cannot create library');}
  
}(this,$,jQuery));


/********** Global Functions and variables ****************/

var axel = Math.random() + "";
var ord = axel * 1000000000000000000;

function anniv_mag_fade()
{
	var mag_promo = $j('#full-mag');
	mag_promo.css('opacity','0');
	
	$j(document).oneTime(1000,"magfadein",function(){
		
		mag_promo.css('display','block').animate({'opacity':1.0},1000,'easeInCubic');
		
		$j(document).oneTime(10000,"magfadeout",function(){
			mag_promo.animate({'opacity':0},1000,'easeOutCubic',function(){
				mag_promo.css('display','none');});
			
		});
	});	
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function grabvar( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}

function officialRules(url) {
	a = window.open(url,'rules','width=650,height=525,resizable=no,scrollbars=yes,toolbar=no,directories=no,status=no');
	var width = 650; 
	var height = 525;
	var aw = screen.availWidth; 
	var ah = screen.availHeight; 
	var xPos = (aw - width)/2; 
	var yPos = (ah - height)/2; 
	a.moveTo(xPos,yPos);
}

var playedOnce = false;

function onYouTubePlayerReady(playerid) {
	player = document.getElementById('ytvideo');
	player.addEventListener('onStateChange', 'youtubeEvent');
}

function youtubeEvent(state) {
	if (state == 1) {
		if (!playedOnce) {
			playedOnce = true;
			pageTracker._trackEvent('video', 'unique_play_per_page');
		}
	pageTracker._trackEvent('video', 'play');
	return;
	}
	
	if (state == 0) {
		pageTracker._trackEvent('video', 'ended');
		return;
	}
}

/********** JQuery Extenstions ***********/
if (typeof jQuery != 'undefined')
{

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 */

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});


/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

} //End of JQuery Extensions
