// JavaScript Document
/**
 * 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.fn.bgIframe=function(B){if($.browser.msie&&/6.0/.test(navigator.userAgent)){B=$.extend({top:"auto",left:"auto",width:"auto",height:"auto",opacity:true,src:"javascript:false;"},B||{});var C=function(D){return D&&D.constructor==Number?D+"px":D},A='<iframe class="bgiframe" frameborder="2" tabindex="-1" src="'+B.src+'"style="display:block;position:absolute;z-index:-1;'+(B.opacity!==false?"filter:Alpha(Opacity='0');":"")+"top:"+(B.top=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+'px')":C(B.top))+";left:"+(B.left=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+'px')":C(B.left))+";width:"+(B.width=="auto"?"expression(this.parentNode.offsetWidth+'px')":C(B.width))+";height:"+(B.height=="auto"?"expression(this.parentNode.offsetHeight+'px')":C(B.height))+';"/>';return this.each(function(){if($("> iframe.bgiframe",this).length==0){this.insertBefore(document.createElement(A),this.firstChild)}})}return this}; jQuery.fn.slideshow=function(options){var settings={timeout:'4000',type:'sequence',pauselink:null,playcallback:null,pausecallback:null};if(options)jQuery.extend(settings,options);var pauseState=0;var current=1;var last=0;var timer='';var change=function(){if(pauseState==0){for(var i=0;i<slides.length;i++){jQuery(slides[i]).css('display','none')}jQuery(slides[last]).css('display','block').css('zIndex','0');jQuery(slides[current]).css('zIndex','1').fadeIn('slow');if(settings.type=='sequence'){if((current+1)<slides.length){current=current+1;last=current-1}else{current=0;last=slides.length-1}}else if(settings.type=='random'){last=current;while(current==last){current=Math.floor(Math.random()*(slides.length))}}else{alert('type must either be \'sequence\' or \'random\'')}timer=setTimeout(change,settings.timeout)}};var pause=function(){if(pauseState==0){pauseState=1;clearTimeout(timer);if(settings.playcallback!=null){settings.pausecallback(jQuery('#'+settings.pauselink))}}else{pauseState=0;change();if(settings.playcallback!=null){settings.playcallback(jQuery('#'+settings.pauselink))}}return false};this.css('position','relative');var slides=this.find('img').get();jQuery.each(slides,function(i){jQuery(slides[i]).css('zIndex',slides.length-i).css('position','absolute').css('top','0').css('left','0')});if(settings.type=='sequence'){timer=setTimeout(change,settings.timeout)}else if(settings.type=='random'){do{current=Math.floor(Math.random()*(slides.length))}while(current==0)timer=setTimeout(change,settings.timeout)}else{alert('type must either be \'sequence\' or \'random\'')}if(settings.pauselink!=null){jQuery('#'+settings.pauselink).click(pause)}return this};jQuery.fn.slideshow_n=function(options){var settings={timeout:'4000',type:'sequence',pauselink:null,playcallback:null,pausecallback:null};if(options)jQuery.extend(settings,options);var pauseState=0;var current=1;var last=0;var timer='';var change=function(){if(pauseState==0){for(var i=0;i<slides.length;i++){jQuery(slides[i]).css('display','none')}jQuery(slides[last]).css('display','block').css('zIndex','0');jQuery(slides[current]).css('zIndex','1').fadeIn('slow');if(settings.type=='sequence'){if((current+1)<slides.length){current=current+1;last=current-1}else{current=0;last=slides.length-1}}else if(settings.type=='random'){last=current;while(current==last){current=Math.floor(Math.random()*(slides.length))}}else{alert('type must either be \'sequence\' or \'random\'')}timer=setTimeout(change,settings.timeout)}};var pause=function(){if(pauseState==0){pauseState=1;clearTimeout(timer);if(settings.playcallback!=null){settings.pausecallback(jQuery('#'+settings.pauselink))}}else{pauseState=0;change();if(settings.playcallback!=null){settings.playcallback(jQuery('#'+settings.pauselink))}}return false};var slides=this.find('.slide').get();jQuery.each(slides,function(i){jQuery(slides[i]).css('zIndex',slides.length-i)});if(settings.type=='sequence'){timer=setTimeout(change,settings.timeout)}else if(settings.type=='random'){do{current=Math.floor(Math.random()*(slides.length))}while(current==0)timer=setTimeout(change,settings.timeout)}else{alert('type must either be \'sequence\' or \'random\'')}if(settings.pauselink!=null){jQuery('#'+settings.pauselink).click(pause)}return this}; jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	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: {
		guid: 1,
		global: {},
		regex: /^([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 = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			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 (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, 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 ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});

