// global var
var	captcha='';		// used in other js files as well, must be defined outside of document ready
/*
This is modeled after how CSS border-width is implied (where one value sets all, two values sets the top/bottom and right/left, etc):

'10px' sets all corner radii to 10px.
'10px 5px' sets the top-left and bottom-right corner radii to 10px, and the other corners to 5px.
'10px 5px 3px' sets the top-left to 10px, the top-right to 5px, the bottom-right to 3px, and the bottom-left to 5px.
'10px 5px 3px 0' sets the top-left to 10px, the top-right to 5px, the bottom-right to 3px, and the bottom-left to 0px.

*/
// global css definitions set via roundies  rounded corner settings
	DD_roundies.addRule('.rounded7', '7Px', true);
	DD_roundies.addRule('.rounded7t', '7Px, 7px, 0px, 0px', true);
	DD_roundies.addRule('.rounded7b', '0px, 0px, 7Px, 7px', true);
	DD_roundies.addRule('.rounded10', '10px', true);
	DD_roundies.addRule('.rounded10t', '10Px, 10px, 0px, 0px', true);
	DD_roundies.addRule('.rounded15', '15px', true);
	DD_roundies.addRule('.rounded20', '20px', true);
	DD_roundies.addRule('.rounded20t', '20Px, 20px, 0px, 0px', true);
	DD_roundies.addRule('.rounded20b', '0px, 0px, 20Px, 20px', true);
	DD_roundies.addRule('.r320', '3px 20px', true);	
	DD_roundies.addRule('.r_20', '0px 20px', true);	
	DD_roundies.addRule('.rB10', '0px 0px 10px 10px', true);	
	DD_roundies.addRule('.rR10', '0px 10px 10px 0px', true);	

// global functions
function refreshCap() {
//alert('Gauranga');
	var maxWidth_ = $('input[name="maxWidth"]').val();
	var numImgs_ = $('input[name="numImgs"]').val();
	var dirLevel_ = $('input[name="dirLevel"]').val();
//alert('maxWidth = '+maxWidth_ + '   numImgs = ' + numImgs_ + '   ' + dirLevel_+ 'php/processCapchaAjax.php');
	$.post(dirLevel_ + "_ajax/processCapchaAjax.php", {maxWidth:maxWidth_, numImgs:numImgs_, dirLevel:dirLevel_}, function(data){
		$("#capcha").html(data);
	});
}

// fde rowBtn's to .6  (executed on page loading)
// $(".rowBtn").fadeTo(0, 0.6);
   $(".rowBtn").stop(true, true).animate( { color:"#333" },0);

// ---- used for rowBtns - navigation bar (on home pg and adinfo
var btnClick=0;
function hilt1( btn ) {
   $(btn).stop(true, true).animate( { color:"#fff" },500);
   $(".selected").stop(true, true).animate( { color:"#ff0" },500);
}
function norm1( btn ) {
   $(btn).stop(true, true).animate( { color:"#333" },500);
   $(".selected").stop(true, true).animate( { color:"#cc0" },500);
//		$(btn).css('color','white');
}
function hilt2( btn ) {
	$(".rowBtn").removeClass("selected").animate( { color:"#333" },500);;
	$(btn).animate( { color:"#ff0" },500).addClass("selected");
}

	$(".rowBtn").hover(function() {
		hilt1( this );
	}, function() {
		norm1( this );
	});	

// ---  input restriction functions
function l(o){ o.value=o.value.toLowerCase().replace(/([^0-9a-z\s-])/g,""); }		// to Lowercase alphanum : 0-9 a-z + ' ' + '-'    ( \s = ' '   space )
function u(o){ o.value=o.value.toUpperCase().replace(/([^0-9A-Z\s-])/g,""); }		// to Uppercase alphanum:  0-9 A-Z + ' ' + '-' 
function p(o){ o.value=o.value.replace(/([^0-9A-z\s!@#$%^&amp;*()_-])/g,""); }		// for password, alpha upper and lower case + 0-9 + ' ' + '!@#$%^&*()_-'
function n(o){ o.value=o.value.replace(/([^0-9])/g,""); }							// numerical only, nothing else    no spaces either
function ph(o){ o.value=o.value.replace(/([^0-9-])/g,""); }							// phone   numbers only + '-'
function d(o){ o.value=o.value.replace(/([^0-9.])/g,""); }							// decimal numbers only   0-9 + '.'    (numbers plus the period)
function a(o){ o.value=o.value.replace(/([^A-z\s])/g,""); }							// alphabet only,   A-z    upper and lowercase + ' '
function a2(o){ o.value=o.value.replace(/([^A-z\s-])/g,""); }						// alphabet  upper and lower  A-z  + ' ' + '-'

// another input restriction method

(function($){
	$.fn.alphanumeric = function(p) { 
		p = $.extend({
			ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
			nchars: "",
			allow: ""
		 }, p);	
		return this.each( function() {
			if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
			s = p.allow.split('');
			for ( i=0;i<s.length;i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
			p.allow = s.join('|');
			var reg = new RegExp(p.allow,'gi');
			var ch = p.ichars + p.nchars;
			ch = ch.replace(reg,'');
			$(this).keypress(function (e) {
				if (!e.charCode) k = String.fromCharCode(e.which);
				else k = String.fromCharCode(e.charCode);
				if (ch.indexOf(k) != -1) e.preventDefault();
				if (e.ctrlKey&&k=='v') e.preventDefault();
			});
			$(this).bind('contextmenu',function () {return false});
		});
	};
	$.fn.numeric = function(p) {
		var az = "abcdefghijklmnopqrstuvwxyz";
		az += az.toUpperCase();
		p = $.extend({
			nchars: az
		}, p);	
		return this.each (function(){
			$(this).alphanumeric(p);
		});
			
	};
	
	$.fn.alpha = function(p) {
		var nm = "1234567890";
		p = $.extend({
			nchars: nm
		}, p);	
		return this.each (function() {
			$(this).alphanumeric(p);
		});
	};	
})(jQuery);
/*
	function	numeric(p) {
		var az = "abcdefghijklmnopqrstuvwxyz";
		az += az.toUpperCase();
		p = $.extend({
			nchars: az
		}, p);	
		return this.each (function(){
			$(this).alphanumeric(p);
		});
	}
*/
function	toggleDiv( div_id )
{
	$("#"+div_id).stop(true, true) .animate( { opacity:'toggle', height:'toggle', width:'toggle' }, 400 ) ;
	maketop( div_id );
	if( div_id == 'sugLamp' )
	{
// alert("here");
		$("#sentmsg").stop(true,true).hide(2000);
		$("#sugPG").stop(true,true).show(2000);
		$(".divFade8").stop(true,true).fadeTo(5000,0.5);
		showSuggestion(1);
	}
}

// --- tool tip and hover boxes
$(document).ready(function(){
// not coded correctly, not used for now	$(".body").css( {'background' : "url('../_images/lamp-2-a-bk.jpg') transparent repeat fixed;}" });
	// process any userError - this is detected in commonPhpHdr  and further processed in displaytopmenu    and completed here.  
	// it is evoked if there is a session[user] or cookie[user]  set, but we either can't find that user in the db, or the status of the user is not active
	// an email is sent to tech, and we then post an error message on screen,     the following logic will detect if such message is present, and if so, hide it after 10 seconds 
/*	var userError = $("#userErrorFlag").val();
	if( userError == 'Y' ) {
		$("#userErrorDiv").delay(10000).hide(2000);
	}
*/
});  // end of document ready
	// - if there was a userError, see desc above, we no longer fade out box in 10 sec, but when user hits close
	$("#userErrorClose").click( function() {
		$("#userErrorDiv").hide(2000);
	});
	
// displaytopmenu  home page astriks
	$("#sitereq").hover(function() {
		$('#sitereqtxt').fadeIn(400);
	}, function() {
		$('#sitereqtxt').fadeOut(400);
	});

// for captcha
// refresh Captcha 
	$("#refreshCap").live('click', function(){
//alert('Gopala');
		captcha='';		// reset selected captcha
		refreshCap();
//		r2();
	 });
							   
/*
// for debug of capcha ajax   enable  ajax.debug.js to use it
function r2() {
	var datastr = "maxWidth="+$('input[name="maxWidth"]').val()+ "&numImgs="+$('input[name="numImgs"]').val()+"&dirLevel="+$('input[name="dirLevel"]').val();
	$.ajax({
		type: "POST",
		data: datastr,
		url: "_php/processCapchaAjax.php",
		success: function(msg){
alert( msg );
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$(XMLHttpRequest).AjaxDebug({
				nativeConsole : true
			});
		}
	});
}
*/

// --- captcha img button
	$(".capBtn").live('click', function(){
		$(".capBtn").css({'background-position':'bottom left'});	// restore all btns to up pos
		$(this).css({'background-position':'top left'});		// set this btn to down pos
		captcha = $(this).find(".capId").attr('id');		// save the id of the hidden span (this is id of btn)
// alert( "id = " + captcha );
	});
				
// - Fade Btns
	$("div.btn133, div.btn104").hover(function() {
		$(this).find(".BtnDn").stop(true, true).fadeIn( 800 );
		$(this).find(".BtnUp").stop(true, true).fadeOut( 800 );
	}, function() {
		$(this).find(".BtnUp").stop(true, true).fadeIn( 800 );
		$(this).find(".BtnDn").stop(true, true).fadeOut( 800 );	
	});	

// 
/*	$("#do").hover(function() {
		$("#loginHover").stop(true, true).fadeIn( 1000 );
		$("#loginOff").stop(true, true).fadeOut( 1000 );
	}, function() {
		$("#loginOff").stop(true, true).fadeIn( 1000 );
		$("#loginHover").stop(true, true).fadeOut( 400 );	
	});	
*/

// - pre-process for Login box
	$('#pwd, #closeLoginBtn').keypress(function(e) {
		code = e.keyCode ? e.keyCode : e.which;
		if(code.toString() == 13) {
			go_Login();		// process form if hit key, or enter
		}
	});

	$("#doLogin").click(function(){
		go_Login();
	});

function go_Login() {
//	alert("GotIt");
			// get data from form
			$("#loginErrDiv").hide(100);	// turn off in case user opens div again
			var	user_email = ($("input[name='email']").val());
			var	dirLevel = ($("input[name='menuPgDirLevel']").val());
//alert( "Level = "+dirLevel );
			var pwd = ($("input[name='pwd']").val());
			var expires_ = 1;  // 1 day
			if( $('#remember').attr('checked') )
				expires_ = 60;	// 60 days
			var datastr = "ueml="+user_email+"&pwd="+pwd;
//	alert( datastr );
			//start the ajax  - have php ck & process login
			$.ajax({
				type: "GET",
				url: dirLevel + "_ajax/process_login.php",
				data: datastr,

				success: function(msg){  
// alert(msg);
					var msg2 = msg.substr(0,2); 
					if( msg2 == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
					{
						// parse the data
				        var data = msg.split(",");
//	alert("user data : " + data[1] );
						// set the cookies
						var user_ = data[1].split(";");	// user data is all in one line, sep by ';', get into array
//	alert("user name : " + user_[1] );
						
						$.cookie('user', data[1], { expires: expires_ , path: '/' }); // data[1] = user data in one line 
						$("#userName").html(user_[1]);  // userName	
						var mygenie = "<a href='"+dirLevel+user_[3]+"/mygenie.php'>my genie</a>";
						$("#mygenie_pg").html(mygenie); 	

						$("#loggedin").removeClass().addClass('div-block');	
						$("#notloggedin").removeClass().addClass('div-none');	
						
						$("#formdata").fadeOut(800);
						$("#done").fadeIn(800).html(user_[1] + ' is Logged In');	
						$("#loginBox").delay(1000).fadeOut(400);
					}
					else
					{
//	alert("("+msg+") it was not ok");
						$("#loginErrDiv").html(msg).show(200);
						return false;
					}
				}  
			});
}
	$("#logout").click(function(){
		var	dirLevel_ = ($("input[name='menuPgDirLevel']").val());
		$.cookie('user', '', { expires: '-1' , path: '/' }); // set expire to yesterday
		// use Ajax to have php wipe out session data
		$.post( dirLevel_ + '_ajax/process_logout.php', {dirLevel: dirLevel_} );
		var url = dirLevel_ + "index.php";
//	alert( "url: " + url );
		location.href = url;
	});

// prccess Home Btn from displayTopMenu.php
	$("#homeTop").click(function() {
		var	dirLevel = ($("input[name='menuPgDirLevel']").val());
		var url = dirLevel + "index.php";
		location.href = url;
	});

// for help menu in displaytopmenu.php

	$(".hmenu").hover( function() {
		if( !$(this).hasClass('selected') )
			$(this).stop().animate( { paddingLeft:"4", color:"#cc0", backgroundColor:"#06c" },400);
	}, function() {
		if( !$(this).hasClass('selected') )
			$(this).stop().animate( { paddingLeft:'30', color:'#09f', backgroundColor:'#006' },800);
	});
	
	$(".txtBtn").hover(function() {
		$(this).stop(true, true).animate( { color:'#cc0', backgroundColor:'#05f' },400);
	}, function() {
		$(this).stop(true, true).animate( { color:'#09f', backgroundColor:'#007' },900);
	});
	$(".txtBtn2").hover(function() {
		$(this).stop(true, true).animate( { color:'#ff7', backgroundColor:'#f00' },400);
	}, function() {
		$(this).stop(true, true).animate( { color:'#f90', backgroundColor:'#700' },900);
	});
	$(".txtBtn3").hover(function() {
		$(this).stop(true, true).animate( { color:'#ff0', backgroundColor:'#0b0' },400);
	}, function() {
		$(this).stop(true, true).animate( { color:'#aa0', backgroundColor:'#040' },900);
	});
	
/*	$(".close16Btn").hover(function() {
		$(".close16BtnDn").fadeIn(600);
		$(this).fadeOut(600);
	}, function() {
		$(".close16BtnDn").fadeOut(600);
		$(this).fadeIn(600);
	});
*/
	$(".close16Btn").click(function() {
		$(this).parent().fadeOut(800);
	});

	$(".draghandle").mousedown(function() {
		$(".draghandle").parent().css( 'z-index', '20' );
		$(this).parent().css( 'z-index', '40' );
	});
	
var helpMenuOff = true;
	$("#helpBtn").click(function() {
		if( helpMenuOff ) {
//alert('menuoff is true - set to False');
			$("#helpTip").stop(true, true).show(600);
//			setMenuTimer();
//			$("#servicesBox").stop(true,true).hide(400);
			helpMenuOff = false;
		} else {
			closeHM();
//alert('menuoff set to = true');			
		}
	});
	$("#clsHM").click(function() {
		closeHM();
	});

	$("#menucontainer").mouseleave(function() {
		$(this).oneTime(800, "clsHelp", function() {
			closeHM();			// mouse has left the help menu, if it does not return after TimeOut, then close the help meny
		});
	});
	$("#menucontainer").mouseenter(function() {
		$("#menucontainer").stopTime("clsHelp");	// mouse has re-entered the menu, do not close it
	});

//close the help menu
function closeHM() {
	$("#helpTip").stop(true, true).hide(800);
	$(".menubox2").stop(true, true).hide(800);
	helpMenuOff = true;
	$(".hmenu").removeClass('selected');	// resets all hmenu buttons, if additional levels, make hmenu1 2 3 
}

/*function setMenuTimer() {
	$("#helpTip").stop(true, true).delay(20000).hide(400);
}*/
function hmenuBtnOn( ele ) {
		$(".hmenu").stop().animate( { paddingLeft:'30', color:'#08d', backgroundColor:'#006' },400).removeClass('selected');	// resets all hmenu buttons, if additional levels, make hmenu1 2 3 
		$(".menubox2").stop(true, true).hide(400);  // close all other level 2 divs
		$(ele).stop(true, true).animate( { paddingLeft:"4", color:"#fff", backgroundColor:"#06c" },400);
		$(ele).addClass('selected');
}
function hmenuBtnOff( ele ) {
		$(ele).stop(true, true).animate( { paddingLeft:'30', color:'#06c', backgroundColor:'#006' },400);
		$(ele).removeClass('selected');
}
	$("#postEventBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#postEventInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#postEventInfo").stop(true, true).hide(400);
		}
	});
	$("#postFreeBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#postFreeInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#postFreeInfo").stop().hide(400);
		}
	});
	$("#postAdBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#postAdInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#postAdInfo").stop(true, true).hide(400);
		}
	});
	$("#createEmailBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#createEmailInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#createEmailInfo").stop(true, true).hide(400);
		}
	});
	$("#adinfoBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#adInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#adInfo").stop(true, true).hide(400);
		}
	});
	$("#freeListBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#freeListInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#freeListInfo").stop(true, true).hide(400);
		}
	});
	$("#majicBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#majicInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#majicInfo").stop(true, true).hide(400);
		}
	});
	$("#searchInfoBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#searchInfoInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#searchInfoInfo").stop(true, true).hide(400);
		}
	});
	$("#adAlertInfoBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#adAlertInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#adAlertInfo").stop(true, true).hide(400);
		}
	});
	$("#eventAlertInfoBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#eventAlertInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#eventAlertInfo").stop(true, true).hide(400);
		}
	});
	$("#priceQuoteBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#priceQuoteInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#priceQuoteInfo").stop(true, true).hide(400);
		}
	});
	$("#auctionPostBtn").click(function() {
		if( !$(this).hasClass('selected') ) {
			hmenuBtnOn(this);
			$("#auctionInfo").stop(true, true).show(400);
		}else{
			hmenuBtnOff(this);
			$("#auctionInfo").stop(true, true).hide(400);
		}
	});
	$(".freeHMBtn").click(function() {
//		$(".menubox2").stop(true, true).hide(400);
//		$(this).stop(true, true).animate( { paddingLeft:"4", color:"#cc0", backgroundColor:"#06c" },400);
//		helpMenuOn = false;
		var url = "http://majicgenie.com/_login/user_register.php";
		location.href = url;
	});
	$(".clientHMBtn").click(function() {
//		$(".menubox2").stop(true, true).hide(400);
//		$(this).stop(true, true).animate( { paddingLeft:"4", color:"#cc0", backgroundColor:"#06c" },400);
//		helpMenuOn = false;
		var url = "http://majicgenie.com/_login/client_register.php";
		location.href = url;
	});
	$(".overHMBtn").click(function() {
//		$(".menubox2").stop(true, true).hide(400);
//		$(this).stop(true, true).animate( { paddingLeft:"4", color:"#cc0", backgroundColor:"#06c" },400);
//		helpMenuOn = false;
		var url = "http://majicgenie.com/adinfo.php?open=accfeatures";
		location.href = url;
	});

/**
 * Cookie plugin
  * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
  */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * 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);
	});
});
