
/* Video player id for js interaction - see jQuery.hero
 **************************************************************/
var videoPlayer = null;
function playerReady(thePlayer) {
	
	videoPlayer = window.document[thePlayer];
	jQuery.fn.hero.checkForFile();
	
	console.log("READY: " + videoPlayer);
	
	addListeners();
}
function addListeners() {
	if (videoPlayer) {
		videoPlayer.addModelListener("STATE", "stateListener");		
	} else { 
		setTimeout("addListeners()",100); 
	}
}

function stateListener(currentState) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	
	console.log("JS: " + currentState)

	if(currentState == "IDLE"){
		jQuery.fn.hero.stopMonitor();
		jQuery.fn.hero.stopTracking();
	}
	
	if(currentState == "BUFFERING"){
		jQuery.fn.hero.stopTracking();
		jQuery.fn.hero.startTracking();
	}
	
	if(currentState == "PLAYING"){
		jQuery.fn.hero.stopTracking();
		jQuery.fn.hero.startTracking();
	}	
	
	if(currentState == "PAUSED"){
		jQuery.fn.hero.stopTracking();
	}

	if(currentState == "COMPLETED"){
		jQuery.fn.hero.stopMonitor();
		jQuery.fn.hero.stopTracking();
	}
}


/*
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate; 	
	
	if(currentState == "PLAYING" && previousState == "BUFFERING"){
		jQuery.fn.hero.stopTracking();
		jQuery.fn.hero.startTracking();
	}	
	
	if(currentState == "PAUSED" && previousState == "PLAYING"){
		jQuery.fn.hero.stopTracking();
	}
	
	if(currentState == "PLAYING" && previousState == "PAUSED"){
		jQuery.fn.hero.stopTracking();
		jQuery.fn.hero.startTracking();
	}	
	
	if(currentState == "IDLE" && previousState == "PLAYING"){
		jQuery.fn.hero.stopMonitor();
		jQuery.fn.hero.stopTracking();
	}
	
	if(currentState == "COMPLETED"){
		jQuery.fn.hero.stopMonitor();
		jQuery.fn.hero.stopTracking();
	}

}
*/



jQuery.noConflict();
(function($){

	
	
/********************************************************************
 * On Load events
********************************************************************/
$(document).ready(function(){	

	/* New window for rel='external' links */
	$('a[rel=external]').attr('target','_blank');  

	/********************************************************************
	 * GUIDE
	********************************************************************/
	$('.channelguide tr').click(function(){		
		$(this).toggleClass('active');
		$(this).toggleClass('expanded');
		return false;
	});

	$('#guide-state').change(function(){
		var state = $('#guide-state option:selected').val();
		window.location = window.location.pathname + '?state=' + state;
		return false;
	});
	
	
	/********************************************************************
	 * SHARE THIS
	********************************************************************/
	//Create your sharelet with desired properties and set button element to false
	var object = SHARETHIS.addEntry({
		title:'share',
		summary: 'Sharing is good for the soul.'
	},{button:false,offsetLeft: -14, offsetTop: 5});


	//Output your customized button
	//document.write('<span id="share"><a href="javascript:void(0);"><img src="/my_share_icon.gif" />Share!</a></span>');

	//Tie customized button to ShareThis button functionality.
	var element = document.getElementById("sharethis");
	if(element != null){
		object.attachButton(element);
	}
	
	
	
	/********************************************************************
	 * TEXT RESIZE
	********************************************************************/	
	$('a.font').textResize({
		target: $(".resize"),
		sizes:  [ "12px", "14px", "16px", "18px", "20px" ]
	});
	
		
	/********************************************************************
	 * FORMS
	********************************************************************/
	//default input values	
	$(this).textReplacement()
	
	
	//Submit Button Rollovers
	$(this).submitRollOver();	
	
	
	/********************************************************************
	 * PRINT
	********************************************************************/
	$('a.print').click(function() {
		window.print();
		return false;
	});
	
		
	
	
	/********************************************************************
	 * PNG FIX
	********************************************************************/
	if ($.browser.msie) {
		try {document.execCommand("BackgroundImageCache", false, true);} catch(err){};
		if (typeof(DD_belatedPNG) != 'undefined')
		{
			DD_belatedPNG.fix('img');
		}
	}

});



/**
 * Clear input values on click
 * @param {Object} options
 */
jQuery.fn.textReplacement = function(settings){
	settings = jQuery.extend({
	}, settings);

	var blankedFieldValues = [];

	if($('input[type="text"].autoblank').length > 0){		
		$('input[type="text"].autoblank').each(function(){
			var input = $(this);
			blankedFieldValues[input.attr('id')] = input.val();
			input.focus( function(){
				if(!input.hasClass('blanked')) {
					input.val('');
					input.addClass('blanked');
				}
			});
			input.blur( function() {
				if(input.val() == '') {
					input.val(blankedFieldValues[input.attr('id')]);
					input.removeClass('blanked');
				}
			});
		});
	}
	
	/* search box autoblank validation hack */
	$('#search').submit(function() {
		var input = $('#search #q.autoblank');
		if(!input.hasClass('blanked') || input.val() == '') {
			alert('Please enter a search criteria.');
			input.focus();
			return false;
		}
	});
};


/**
 * Creates a rollover for all !!Image!! submit buttons
 * @param {Object} options
 */
jQuery.fn.submitRollOver = function(settings){
	settings = jQuery.extend({
		overAppend:  "_over"
	}, settings);

	
	if($('input[type="image"]').length > 0){		
		
		$('input[type="image"]').each(function(){
						
			var out = $(this).attr("src");
			var extension = out.substring(out.lastIndexOf("."));
			var over = out.replace(extension, settings.overAppend + extension);

			
			$(this).hover(
		        function(){ // Change the input image's source when we "roll on"
		            $(this).attr({ src : over});
		        },
		        function(){ // Change the input image's source back to the default on "roll off"
		            $(this).attr({ src : out});
		        }
		    );
	
		
		});
		
	}
	
	
	if($('input[type="submit"]').length > 0){		
		
		$('input[type="submit"]').each(function(){
						
			$(this).hover(
		        function(){ // Change the input image's source when we "roll on"
		            $(this).addClass("over");
		        },
		        function(){ // Change the input image's source back to the default on "roll off"
		            $(this).removeClass("over");
		        }
		    );
	
		
		});
		
	}
	
};








/**
 * JQuery plugin resize text on click - acts as a loop.
 * @param {Object} options
 */
jQuery.fn.textResize = function(settings){
	settings = jQuery.extend({
		sizes:  [ "12px", "14px", "16px", "18px", "20px" ]
	}, settings);
	
	var item = $(this);
	var total = settings.sizes.length;
	var COOKIE_NAME = "StvdioTextSize";
	
	// check for cookie and set the size if found
	if($.cookie(COOKIE_NAME)){		
		$(settings.target).css('font-size', $.cookie(COOKIE_NAME));
	}

	$(item).click(function(){
		var currentSize = $(settings.target).css('font-size');
		var pos = $.inArray(currentSize, settings.sizes);
		var size =  settings.sizes[(pos == (total - 1)) ? 0 : (pos + 1)]
		$(settings.target).css('font-size', size);		
		$.cookie(COOKIE_NAME, size, { expires: 7 });		
	});

};






/********************************************************************
 * PLUGINS
********************************************************************/

/**
 * jQuery.hero
 * SBS Hero Carousel on Home page
 * Date: 2010/02/24
 * @version 0.1
 *
 **/
jQuery.fn.hero = function(settings){
	settings = jQuery.extend({
		start: (new Date()).getDay(),		// which item to start on
		time: 5,					// time between each tick
		initScroll: true,			// allow for automatic scrolling,
		standAlone: true			// This player has no associated playlist
	}, settings);
	
	
	var current = settings.start;
	var totalAmount = ($("#featuredNav li a").length);
	var canTick = true;
	var speed = 500;
	var xOffSet = 350;
	var xInfoStart;
	var api;
	var videoOn = false;
	var nextSlide = (settings.start + 1) % totalAmount;
	var TICKER_LABEL = "ticker"
	var TRACKER_LABEL = "tracker"
	var fileToPlay;
	var videoTitle;
	
	
	if(settings.title){
		videoTitle = settings.title
	}
	
	if(settings.file){
		fileToPlay = settings.file
	}
	
	
	// TRACKER VARS
	rsCI="sbs-stvdio-dav";
	rsCG="Stvdio-Inline"; //must not contain an underscore character
	//rsHPage="http://www.sbs.com.au/rockwiz/game/gethighscores"; // (or "http://www.sbs.com.au/rockwiz/game/getquestion", etc.etc.)
	rsHPage=window.location;
	rsDN="//secure-au.imrworldwide.com/";
	si="Stvdio-Inline-Marquee";
	
	// make the first one active
	//$("#featuredNav li:eq(0)").find("a").addClass("active");
	
	//and show its text in the texbox
	if($(".featureInfo")){
		xInfoStart = parseFloat($(".featureInfo").css("right"))
		$(".featureInfo li:eq(" + settings.start + ")").addClass("active");			
	};
	
			
	
	if($("div.scrollable").length > 0 && settings.initScroll){
		// activate the scroller	
		var api = $("div.scrollable").scrollable({
			size:	1, 
			easing:	"swing", 
			clickable: false,
			speed:	speed	
		}).circular().navigator({ 
	        navi: "#featuredNav", 
	        naviItem: 'a', 
	        activeClass: 'active',        
	        api : false
	        
	    })
	   
		// ** Ticker Functions **/
		var startSlide = function(){		
			$("#featuredNav").everyTime(settings.time * 1000, TICKER_LABEL, function() {    	
		    	current = (current == (totalAmount - 1))? 0 : (current + 1);
		    	showSlide()
		    });
		}	    
		var showSlide = function(){
			
			$("#featuredNav li:eq(" + current + ") a").click();			
			if(!videoOn){
				setTextBox()
			}		
		}	
		
		
		
		/*
		 * USER INTERACTION
		 * Rollovers, video player
		 */
		
		// track when user clicks on the marquee.
		var trackItems = $('#featuredNav li a').mousedown(function(){
			trackClick(trackItems.index(this));
		});
		
		/* handle general onclicks */
		var items = $('#featuredNav li');
		
		
		$(items).click(function(index){
			current = items.index(this)
			
			// move the text
			setTextBox()		
			
			if(videoOn){			
				jQuery.fn.hero.stopMonitor();
				pauseTicker();
			}
	
		}).mouseover(function(index){
			$(this).find("a").addClass("active");
		}).mouseout(function(){		
			if(items.index(this) != current){
				$(this).find("a").removeClass("active");			
			}		
		});
		
		
		var pauseTicker = function(){
			if(!videoOn){
				$("#featuredNav").stopTime(TICKER_LABEL);
			}
		}	
		
		var playTicker = function(){
			if(!videoOn){			
				startSlide();
			}
		}	
		
		var menuOver = function(){
			pauseTicker();
		}
		
		var menuOut = function(){
			playTicker();
		}	
		
		var config = {    
		     sensitivity: 20, // number = sensitivity threshold (must be 1 or higher)    
		     interval: 200, // number = milliseconds for onMouseOver polling interval    
		     over: pauseTicker, // function = onMouseOver callback (REQUIRED)    
		     timeout: 500, // number = milliseconds delay before onMouseOut    
		     out: playTicker // function = onMouseOut callback (REQUIRED)    
		};
		
		$(".featureInfo").hoverIntent( config );
		$("#featuredNav").hoverIntent( config );
		
		
		/**
		 * INIT
		 */
		
		startSlide();
	
		
	}
	
	
	// buttons
	$(".play").click(function(){
		if(settings.initScroll){
			$("#featuredNav").stopTime(TICKER_LABEL);
		}
						  
		if(videoOn == false){
			fileToPlay = $(this).attr("rel");
			videoTitle = $(this).attr("title");			
			trackLoadVideoPlayer();
			$(this).addClass("inactive");
								  
			
			// move the text off
			if($(".featureInfo")){
				$(".featureInfo").animate({
					right: -105
				  }, 500, function() {
					// Animation complete.
				  });
			};
			
			$(".items").fadeOut("slow", function(){	
				loadPlayer(fileToPlay);
			});
		}
		
		return false;
	
	})
	
	
	var loadPlayer = function(fileToPlay){
		videoOn = true;	
		$(".playerContainer ").addClass("on");
		videoPlayer.sendEvent('LOAD', fileToPlay);
		videoPlayer.sendEvent('PLAY');
	}
	
	var unLoadPlayer = function(){
		videoOn = false;
		$(".playerContainer").removeClass("on");
		videoPlayer.sendEvent('LOAD', "/web/images/misc/trans.gif");
	
	}
	
	
	
	
	var getAlphaIndex = function(s){
		switch (s)
		{
		case 1:
		  return "a"
		  break;
		case 2:
		  return "b"
		  break;
		case 3:
		  return "c"
		  break;
		case 4:
		  return "d"
		  break;
		case 5:
		  return "e"
		  break;
		case 6:
		  return "f"
		  break;
		case 7:
		  return "g"
		  break;
		default:
		  return "a"
		}
	}
	
	
	// move the text box
	var setTextBox = function(){		
		if($(".featureInfo")){
			$(".featureInfo li.active").animate({
				left: xOffSet * -1					
			}, (speed / 2), function() {
				// Animation complete.
				$(this).removeClass("active");				
				$(".featureInfo li:eq(" + current + ")").addClass("active").css({"left": xOffSet * -1}).animate({
					left: 0						
				}, (speed / 2), function() {
					
				});					
			});
		};		
	}
	
	
	
	// ************************************** FLASH INTERACTION ************************************** //
	jQuery.fn.hero.playMonitor = function(){

	}
	
	
	jQuery.fn.hero.stopMonitor = function(){	
		if(videoOn == true){
			$("#featuredNav").stopTime(TICKER_LABEL);
			$(".items").fadeIn("slow");	
			$(".play").removeClass("inactive");
			
			videoPlayer.sendEvent('STOP');
			
			// move the text back on
			if($(".featureInfo")){			
				$(".featureInfo").animate({
					right: 0
				}, 500, function() {				
				});			
			};	
			
			unLoadPlayer();
			startSlide();
			
		}
		
		
	}
	
	
	
	/* TRACKING
	* 
	*/
		 
	jQuery.fn.hero.startTracking = function(){
		// start the tracker
		$(".playerContainer ").everyTime(5000, TRACKER_LABEL, function() {    	
			trackVideoPlayer();
		});
		
	}
	
	jQuery.fn.hero.stopTracking = function(){
		// stop the tracker
		$(".playerContainer ").stopTime(TRACKER_LABEL);
		
	}
	
	
	jQuery.fn.hero.checkForFile = function(){
		// set the load track
		if(settings.file){
			trackLoadVideoPlayer();
		}
	}
	
	
	var trackClick = function(index){
		
		// send to Nielsen
		si = si +".internalclick-" + getAlphaIndex((index + 1)) +"1";
		var url = rsDN + "cgi-bin/m?ci=" + rsCI + "&cg=" + rsCG + "&si=" + si + "&rnd=" + Math.ceil(Math.random()*100000000)
		sendTracker(url);
		
	}
	
	
	var trackVideoPlayer = function(){

		var mySi = "PlayVideo/" + fileToPlay;
		var ci = "sbs-stvdio-dav";
		var t1 = "dav1-" + videoTitle;			

		var url = rsDN + "cgi-bin/m?ci=" + ci + "&tl=" + t1 + "&cg=" + rsCG + "&du=0&cc=1&si=" + mySi + "&rp=" + rsHPage + "&rnd=" + Math.ceil(Math.random()*100000000);
		sendTracker(url);
		
	}
	
	var trackLoadVideoPlayer = function(){
		
		var mySi = "LoadVideo/" + fileToPlay;
		var ci = "sbs-stvdio-dav";
		var t1 = "dav0-" + videoTitle;	
		
		var url = rsDN + "cgi-bin/m?ci=" + ci + "&tl=" + t1 + "&cg=" + rsCG + "&du=0&cc=1&si=" + mySi + "&rp=" + rsHPage + "&rnd=" + Math.ceil(Math.random()*100000000);
		sendTracker(url);
			
	}
		
	// send to Nielsen
	var sendTracker = function(url){		
		var i = new Image();
		i.src = url;
	}
		
	$("#featuredNav li:eq(" + current + ") a").click();	
};



})(jQuery);








/********************************************************************
 * PLUGINS
********************************************************************/





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





/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};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);



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