/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
            
           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);

// get cookie function
function readCookie(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 false;
}

// Sets the visitor's station from the links on the firstvisit box
function setStationFirstVisit(station)
{
	// Set a cookie so the firstvisit box won't be shown again.
	jQuery.cookie('kiss_userset', '1', { expires: 30, path: '/', domain: cookiedomain});

	// If there is no cookie, then the page will have been built as 100.
	// If they have clicked 100 in the firstvisit box, set the 100 cookie and hide the firstvisit box
	if (!readCookie('kiss') && station =='100'){
		jQuery.cookie('kiss', '100', { expires: 30, path: '/', domain: cookiedomain});
		jQuery("#firstvisit").slideUp("200");
		return false;
	}
	// If the kiss cookie is already set as the same as the station, just hide the firstvisit box.
	else if (readCookie('kiss') == station){
		jQuery("#firstvisit").slideUp("200");
		return false;
	}
	// Otherwise set the station cookie and reload.
	else{
		// Set the station cookie
		jQuery.cookie('kiss', station, { expires: 30, path: '/', domain: cookiedomain});
		jQuery("#firstvisit-links").empty().append('One moment. Reloading page to set your station.');
		location.reload();
	}

				
	return false;
}

// Sets the visitor's station
function setStation(station){
	// Set the station cookie
	jQuery.cookie('kiss', station, { expires: 30, path: '/', domain: cookiedomain});
	jQuery("#flavour").empty().append('<p><strong>One moment. Reloading page to set your flavour of Kiss.</strong>');
	var url = new String(window.location);
	window.location = url.replace(/\?.*$/, "");
}

function setStationKiss(station){
	// Set the station cookie
	jQuery.cookie('kiss', station, { expires: 30, path: '/', domain: cookiedomain});
	jQuery.cookie('kiss_userset', '1', { expires: 30, path: '/', domain: cookiedomain});
	jQuery("#pagereload").show();
	jQuery("#customise").hide();
	var url = new String(window.location);
	window.location = url.replace(/\?.*$/, "");
	//location.reload();
}



/* function to add a form hint to input fields with a title value */
/* $('input:text').hint(); */
jQuery.fn.hint = function (blurClass) {
	if (!blurClass) { 
		blurClass = 'blur';
	}
	
	return this.each(function () {
		// get jQuery version of 'this'
		var $input = jQuery(this),
	
		// capture the rest of the variable to allow for reuse
		title = $input.attr('title'),
		$form = jQuery(this.form),
		$win = jQuery(window);
	
		function remove() {
			if ($input.val() === title && $input.hasClass(blurClass)) {
				$input.val('').removeClass(blurClass);
			}
		}
		// only apply logic if the element has the attribute
		if (title) { 
			// on blur, set value to title attr if text is blank
			$input.blur(function () {
				if (this.value === '') {
					$input.val(title).addClass(blurClass);
				}
			}).focus(remove).blur(); // now change all inputs to title
	
		// clear the pre-defined text when form is submitted
		//form.submit(remove);
		//win.unload(remove); // handles Firefox's autocomplete
		}
	});
};

var sethome = false;
var setupgrade = false;
var debugging = false;

jQuery(document).ready(function($) {

	// Facebook
	FB.init("6ad3d92f198608f8299d96db027a38ae", "/xd_receiver.htm");

	if (debugging) alert('execution paused - wait for firebug lite window to load before continuing..');

	if (debugging) console.time('functions');

	// Film - remove unwanted elements from DOM
	jQuery('.film_rated li span.high2').remove();


	var temp_path = readCookie('template_path_kiss');
	var template_path = urldecode(temp_path);

	if (readCookie('kiss')){
		var station = readCookie('kiss');
	} else {
		var station = '100';
	}

	if (debugging) console.time('functions-navigation');
	// NAVIGATION FUNCTIONS
	//
	// set up the menu rollovers
	jQuery('#menu li a')
	.mouseover(function(){
		jQuery(this).stop().css( {backgroundPosition: "0 0"} ).animate({backgroundPosition:"(-150px 0)"}, {duration:300})
	})
	.mouseout(function(){
		jQuery(this).stop().animate({backgroundPosition:"(-300px 0)"}, {duration:300, complete:function(){
			jQuery(this).css({backgroundPosition: "0 0"})
		}})
	})
	// set up the nav home button
	jQuery("#menu #homenav a").unbind('mouseover').unbind('mouseout');
	jQuery('#menu #homenav a')
	.mouseover(function(){
		jQuery(this).stop().css( {backgroundPosition: "-38px 0"} ).animate({backgroundPosition:"(-299px 0)"}, {duration:400});
		jQuery('#homeicon').attr('src', template_path+'images/nav-home-icon.gif');
	})
	.mouseout(function(){
		jQuery(this).stop().animate({backgroundPosition:"(-444px 0)"}, {duration:400, complete:function(){
			jQuery(this).css({backgroundPosition: "-38px 0"})
		}})
		if (setupgrade){
			jQuery('#homeicon').attr('src', ''+template_path+'images/nav-home-icon-upgrade.gif');
		} else {
			jQuery('#homeicon').attr('src', ''+template_path+'images/nav-home-icon2.gif');
		}
	})
	// remove actions from current page
	jQuery(".current_page_item a").unbind('mouseover').unbind('mouseout');
	// add icon to home nav
	jQuery('#homenav a').prepend('<img id="homeicon" src="'+template_path+'images/nav-home-icon2.gif" width="14px" height="13px" alt="home" />');
	//
	if (sethome){
		jQuery('#menu #homenav a').css('background-position','-299px 0');
		jQuery('#homeicon').attr('src', template_path+'images/nav-home-icon.gif');
	}
	
	if (setupgrade){
		jQuery('#homeicon').attr('src', ''+template_path+'images/nav-home-icon-upgrade.gif');
	}
	
	//
	// NOW AND NEXT FUNCTIONS
	//

	//
	jQuery("#listenlive").click(function(event){
		window.open('http://kube.totalkiss.com?jumpto=kiss'+station);
		return false;
	});
	

	// Random number to tack on the end of the load() requests so we don't get served stale IE cache
	var random = Math.floor(Math.random()*100000000);

	jQuery("#radioshow").click(function(event){
		jQuery.getJSON(template_path+'schedule/kube_nownext_json.php?random='+random+'&callback=?', function(data){ jQuery('#kissradio').html(data.html); });
		return false;
	});
	jQuery("#tvshow").click(function(event){
		jQuery("#kissradio").empty();
		return false;
	});
	
	jQuery.getJSON(template_path+'schedule/kube_nownext_json.php?random='+random+'&callback=?', function(data){ jQuery('#kissradio').html(data.html); });

	if (debugging) console.timeEnd('functions-navigation');

	if (debugging) console.time('functions-customise');
	//
	// CUSTOMISE AREA
	//
	jQuery('#customise').hide();
	jQuery('#customiseloading').hide();
	jQuery(".kisstomize").click(function(event){
		// set the areas
		// media
		/*var all_media_sel = '';
		jQuery(".mediasel").each( function () {
			all_media_sel = all_media_sel + jQuery(this).val() + ",";
		});
		all_media_sel = all_media_sel.substring(0, all_media_sel.length-1);
		if (urldecode(readCookie('mediacarousel')) == all_media_sel || !readCookie('mediacarousel')){ // all selected so sort out the display
			// check the main box - .attr('checked', true)
			jQuery('input[name=media_all]').attr('checked', true);
			// hid the sub-selections
			jQuery('.mediasel').attr('disabled',true);
			jQuery("#media_opt").hide();
		}
		*/
		// dj
		var all_dj_sel = '';
		jQuery(".djsel").each( function () {
			all_dj_sel = all_dj_sel + jQuery(this).val() + ",";
		});
		all_dj_sel = all_dj_sel.substring(0, all_dj_sel.length-1);
		if (urldecode(readCookie('djcarousel')) == all_dj_sel){ // all selected so sort out the display
			// check the main box - .attr('checked', true)
			jQuery('input[name=dj_all]').attr('checked', true);
			// hid the sub-selections
			jQuery('.djsel').attr('disabled',true);
			jQuery("#dj_opt").hide();
		}
		
		/*
		// music
		var all_music_sel = '';
		jQuery(".musicsel").each( function () {
			all_music_sel = all_music_sel + jQuery(this).val() + ",";
		});
		all_music_sel = all_music_sel.substring(0, all_music_sel.length-1);
		if (urldecode(readCookie('musiccarousel')) == all_music_sel || !readCookie('musiccarousel')){ // all selected so sort out the display
			// check the main box - .attr('checked', true)
			jQuery('input[name=music_all]').attr('checked', true);
			// hid the sub-selections
			jQuery('.musicsel').attr('disabled',true);
			jQuery("#music_opt").hide();
		}

		*/
		
		// open close customise area
		if (jQuery('#customise').is(":hidden"))
		{
		   // jQuery('#customiseloading').stop().slideDown('fast');
		    //jQuery("#customise").load("customise.html", function(){
				jQuery('#customise').slideDown();
				//jQuery('#customiseloading').stop().hide();
			//});
		} else {
		    jQuery('#customise').stop().slideUp("fast");
		}
		return false;
	});
	
	// media
	jQuery("#media_all").click(function(event){
		var state = jQuery('.mediasel').attr('disabled') ? false : true;
		jQuery('.mediasel').attr('disabled',state);
		var vis = state ? jQuery("#media_opt").hide() : jQuery("#media_opt").show();
	});
	// djs
	jQuery("#dj_all").click(function(event){
		var state = jQuery('.djsel').attr('disabled') ? false : true;
		jQuery('.djsel').attr('disabled',state);
		var vis = state ? jQuery("#dj_opt").hide() : jQuery("#dj_opt").show();
	});
	// Music
	jQuery("#music_all").click(function(event){
		var state = jQuery('.musicsel').attr('disabled') ? false : true;
		jQuery('.musicsel').attr('disabled',state);
		var vis = state ? jQuery("#music_opt").hide() : jQuery("#music_opt").show();
	});
	
	
	// Saving prefs
	jQuery(".customsave").click(function(event){
		// Kiss station
		jQuery.cookie('kiss', jQuery('input[name=kiss]:checked').val() , { expires: 30, path: '/', domain: cookiedomain});
		/*
		// Media
		var media_result = "";
		// check if 'all' checkbox is ticked
		if (jQuery('input[name=media_all]').is(':checked')){ // select all values
			jQuery(".mediasel").each( function () {
				media_result = media_result + jQuery(this).val() + ",";
			});
		} else { // select only the checked ones
			jQuery(".mediasel").each( function () {
				if (jQuery(this).is(':checked')){
					media_result = media_result + jQuery(this).val() + ",";
				}
			});
		}
		media_result = media_result.substring(0, media_result.length-1);
		jQuery.cookie('mediacarousel', media_result , { expires: 30, path: '/', domain: cookiedomain});
		*/
		// DJ
		var dj_result = "";
		// check if 'all' checkbox is ticked
		if (jQuery('input[name=dj_all]').is(':checked')){ // select all values
			jQuery(".djsel").each( function () {
				dj_result = dj_result + jQuery(this).val() + ",";
			});
		} else { // select only the checked ones
			jQuery(".djsel").each( function () {
				if (jQuery(this).is(':checked')){
					dj_result = dj_result + jQuery(this).val() + ",";
				}
			});
		}
		dj_result = dj_result.substring(0, dj_result.length-1);
		jQuery.cookie('djcarousel', dj_result , { expires: 30, path: '/', domain: cookiedomain});
		
		/*
		// Music
		var music_result = "";
		// check if 'all' checkbox is ticked
		if (jQuery('input[name=music_all]').is(':checked')){ // select all values
			jQuery(".musicsel").each( function () {
				music_result = music_result + jQuery(this).val() + ",";
			});
		} else { // select only the checked ones
			jQuery(".musicsel").each( function () {
				if (jQuery(this).is(':checked')){
					music_result = music_result + jQuery(this).val() + ",";
				}
			});
		}
		music_result = music_result.substring(0, music_result.length-1);
		jQuery.cookie('musiccarousel', music_result , { expires: 30, path: '/', domain: cookiedomain});
		*/
		
		//alert ('music_result:'+music_result);
		jQuery('#customise').hide();
		jQuery('#customiseloading').show();
		jQuery('#pagereload').show();
		location.reload();
		//return false;
		
	});
	if (debugging) console.timeEnd('functions-customise');
	
	
	if (debugging) console.time('functions-explore/widget');
	//
	// EXPLORE TOTALKISS.COM
	//
	// add the menu to body
	jQuery('<div id="ieholder"><div id="kissnav_nav" style="display:none"><iframe id="iFrameExplore" name="iFrameExplore" width="100%" scrolling="no" height="100px" frameborder="0" src="http://www.totalkiss.com/kissnav/" /></div><div id="kissnav_nav_b"></div></div>').prependTo("body");
	jQuery('<img src="http://www.totalkiss.com/kissnav/explore-button-white.gif" width="160" height="20" alt="Explore totalkiss.com" title="Explore totalkiss.com"/>').appendTo("#kissnav_button");

	// button action
	jQuery('#kissnav_button').click(function() {
		jQuery("#kissnav_nav").toggle();
		var innerFrame = jQuery('#iFrameExplore');
		var innerDoc = (innerFrame.get(0).contentDocument) ? innerFrame.get(0).contentDocument : innerFrame.get(0).contentWindow.document;
		var theheight = innerDoc.body.offsetHeight;
		innerFrame.height(theheight);
	});
	// when mouse leaves the explore nav
	jQuery("#kissnav_nav").bind("mouseleave",function(){
		if (jQuery.browser.msie) {
			jQuery("#kissnav_nav").toggle();
		} else {
			jQuery("#kissnav_nav").slideToggle('fast');
		}
	});
	
	// KUBE WIDGET
	jQuery.getJSON(template_path+'schedule/kube_widget_json.php?random='+random+'&callback=?', function(data){
		jQuery('.kisskube').html(data.html);
		//if (!jQuery.browser.msie){ Cufon.replace('h5'); }
		Cufon.replace('h5');
	});
	if (debugging) console.timeEnd('functions-explore/widget');


	// FOCUS REMOVE FROM LINKS
	jQuery('a').click(function() {
		this.blur();
	});
	
	
	if (debugging) console.time('functions-todayonkiss');
	// TODAY ON KISS
	jQuery('.slider-content').hide();
	jQuery('.slider-content:first').show();
	jQuery('.slider-content:first').toggleClass('off');
	jQuery('.slider-title').click(function(){
		jQuery('.slider-content').slideUp('fast');
		jQuery('.slider-title').addClass('off');
		jQuery(this).siblings('.slider-content').slideDown('fast');
		jQuery(this).removeClass('off');
	});
	if (debugging) console.timeEnd('functions-todayonkiss');
	
	if (debugging) console.time('functions-latest');
	// MOST VIEWED / TOP RATED / LATEST COMMENTS
	jQuery('.most-viewed-box').hide();
	jQuery('.top-rated-box').hide();
	jQuery('.most-viewed-box li:odd').addClass('odd-comment'); // Zebra striping
	jQuery('.top-rated-box li:odd').addClass('odd-comment'); // Zebra striping
	jQuery('.latest-comments-box li:odd').addClass('odd-comment'); // Zebra striping
	jQuery('.most-viewed-tab').click(function(){
		jQuery('.latest-comments-box').hide();
		jQuery('.top-rated-box').hide();
		jQuery('.most-viewed-box').show();
		jQuery('.panel div').removeClass('current-tab');
		jQuery(this).addClass('current-tab');
	});
	
	jQuery('.latest-comments-tab').click(function(){
		jQuery('.most-viewed-box').hide();
		jQuery('.top-rated-box').hide();
		jQuery('.latest-comments-box').show();
		jQuery('.panel div').removeClass('current-tab');
		jQuery(this).addClass('current-tab');
	});
	
	jQuery('.top-rated-tab').click(function(){
		jQuery('.most-viewed-box').hide();
		jQuery('.latest-comments-box').hide();
		jQuery('.top-rated-box').show();
		jQuery('.panel div').removeClass('current-tab');
		jQuery(this).addClass('current-tab');
	});
	
	// IE7 target="_blank" work around
	/*jQuery('a[@target=_blank]').click(function(){
		window.open(this.href);
		return false;
	});*/
	if (debugging) console.timeEnd('functions-latest');
	
	
	if (debugging) console.time('functions-explore/anicar');
	var activeImg = 1;
	
	var aniCar = setInterval(function()
	{
		curr = activeImg +1;
		if (curr > jQuery('#carouselImages').children().size()){
			curr = 1;
		}
		jQuery('#img-'+activeImg).removeClass('active-image');
		jQuery('#img-'+curr).css('opacity', 0.2);
		jQuery('#img-'+curr).addClass('active-image');
		jQuery('#img-'+curr).fadeTo('500', 1);
		
		jQuery('#control-'+activeImg).removeClass('activeControl');
		activeImg = curr;
		jQuery('#control-'+activeImg).addClass('activeControl');

	}, 5000);
	if (debugging) console.timeEnd('functions-explore/anicar');
	
	
	if (debugging) console.time('functions-explore/herodiv');
	/* CODE FOR HERO DIV ROLLOVER EFFECTS */
	
	//jQuery('#control-'+activeImg).addClass('activeControl');
	jQuery('.controller').mouseover(function () {
		clearInterval(aniCar);
		// get ID of clicked hero
		var curr = jQuery(this).attr('id');
		curr = curr.substring(8);	
		// add/remove active class from slideshow images and fade in new one
		if (curr != activeImg) {
			jQuery('#img-'+activeImg).removeClass('active-image');
			jQuery('#img-'+curr).css('opacity', 0.2);
			jQuery('#img-'+curr).addClass('active-image');
			jQuery('#img-'+curr).fadeTo('500', 1);
			
			jQuery('#control-'+activeImg).removeClass('activeControl');
			activeImg = curr;
			jQuery('#control-'+activeImg).addClass('activeControl');
		}
	});
	if (debugging) console.timeEnd('functions-explore/herodiv');
	
	
	if (debugging) console.time('functions-explore/local-cookies');
	// SET LOCAL COOKIE
	if (station =='100'){
		jQuery("#cookie101").append(' | ').show();
		jQuery("#cookie105").show();
	} else if (station =='101'){
		jQuery("#cookie100").append(' | ').show();
		jQuery("#cookie105").show();
	} else if (station =='105'){
		jQuery("#cookie100").append(' | ').show();
		jQuery("#cookie101").show();
	}
	
	jQuery("#cookieclose").click(function(event){
		jQuery("#flavour").hide();
		jQuery("#nownext").show();
		return false;
	});
	jQuery("#cookieopen").click(function(event){
		jQuery("#flavour").show();
		jQuery("#nownext").hide();
		return false;
	});

	jQuery("#cookie100").click(function(){setStation('100');});
	jQuery("#cookie101").click(function(){setStation('101');});
	jQuery("#cookie105").click(function(){setStation('105');});
	jQuery("#cookie100firstvisit").click(function(){setStationFirstVisit('100');});
	jQuery("#cookie101firstvisit").click(function(){setStationFirstVisit('101');});
	jQuery("#cookie105firstvisit").click(function(){setStationFirstVisit('105');});
	
	jQuery("#set100").click(function(){setStationKiss('100');});
	jQuery("#set101").click(function(){setStationKiss('101');});
	jQuery("#set105").click(function(){setStationKiss('105');});

	// schedule page - change header graphic on top menu active state	
	jQuery('.sched-switcher').click(function(){
		if (jQuery(this).hasClass('active'))
		{
			return false;
		} else {
			jQuery('.sched-switcher').removeClass('active');
			jQuery(this).addClass('active');
			return false;
		}
	});
	if (debugging) console.timeEnd('functions-explore/local-cookies');
	
	
	if (debugging) console.time('functions-explore/cufon');
	// CUFON
	//if (!jQuery.browser.msie) {
		// Calls to action Cufon
		Cufon.replace('h1');
		Cufon.replace('h2');
		Cufon.replace('h3');
		Cufon.replace('h4');
		// Cufon.replace('h5'); Kube widget
		Cufon.replace('h6');
	//}
	if (debugging) console.timeEnd('functions-explore/cufon');

	if (debugging) console.timeEnd('functions');

	// If buildCarousels() is defined (home page) then fire it now.
	if (typeof buildCarousels == 'function') { buildCarousels(); }

});

// FUNCTIONS

function urldecode( str ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Philip Peterson
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +      input by: AJ
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Brett Zamir
	// %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
	// *     example 1: urldecode('Kevin+van+Zonneveld%21');
	// *     returns 1: 'Kevin van Zonneveld!'
	// *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
	// *     returns 2: 'http://kevin.vanzonneveld.net/'
	// *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
	// *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
	
	var histogram = {};
	var ret = str.toString();
	
	var replacer = function(search, replace, str) {
	    var tmp_arr = [];
	    tmp_arr = str.split(search);
	    return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urlencode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
	
	for (replace in histogram) {
	    search = histogram[replace]; // Switch order when decoding
	    ret = replacer(search, replace, ret) // Custom replace. No regexing   
	}
	
	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
	
	return ret;
}

/**
 * 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) {
            value = '';
            options = jQuery.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            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
        }
        // NOTE 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;
    }
};