/*

Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)

This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

var windowFocus = true;
var originalTitle;
var blinkOrder = 0;

var chatboxFocus = new Object();
var newMessages = new Object();
var newMessagesWin = new Object();
var chatBoxes = new Object();
var numOnlineUsers = 0;
$(document).ready(function(){

	// click on the menu						   
	$('#changeStatus').click(function() {
		$('#statusToggle').show('normal');
		$('#closeStatus').show();
		$(this).hide();
		
	
		return false;
		
		
		
	});
	
	$('#closeStatus').click(function() {
		closeStatusBox()	
	
		return false;
		
		
		
	});
	
	$('#onlineStatus').click(function() {
		
		//put code here 
		connection.send($pres().tree());
		setChatString(numOnlineUsers);
		
		$('#currentStatus').html("Online");
		closeStatusBox();
		return false;
	});
	
		$('#offlineStatus').click(function() {
		
		//put code here 
		//connection.disconnect();
		connection.send($pres({'type':'unavailable'}).tree());
		numOnlineUsers = 0;
		$('#onlineList').html("");
		setChatString(-3);
			
		$('#currentStatus').html("Offline");
		closeStatusBox();
		return false;
	});
		
			$('#invisibleStatus').click(function() {
		
		//put code here 
		connection.send($pres({'type':'unavailable'}).tree());
		setChatString(numOnlineUsers);
		
		$('#currentStatus').html("Invisible");
		closeStatusBox();
		return false;
	});
	
	function closeStatusBox()
	{
		$('#statusToggle').hide('normal');
		$('#closeStatus').hide();
		$('#changeStatus').show();
		
		
	}
    // click on the menu						   
	$('#onlineUsers li').live('click',function() {
		var userid  =  $(this).attr("id");
		
		chatWith(userid);
		return false;
	});
	
	
	$('#chatBtn').click(function() {
		$('#chatHolder').toggle();
		return false;
	});
	
	originalTitle = document.title;

	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
	startChatSession();
});
function setChatString (usersOnline)
{
	if(usersOnline == -3)
	{
		msg = "Disconnected";
	}
	else if (usersOnline == -2)
	 {
	   msg = "Loading Chat..";
	 }
	else if (usersOnline == -1)
	 {
		msg  = "Connecting...";
	 }
	 else if (usersOnline > 0  ) 
	 {
	     msg = (usersOnline == 1) ? usersOnline + " user online": usersOnline + " users online" ; 
	 }
	 else 
	 {
	   msg  = "No user online";
	 }
	  
	 $('#onlineMsg').text(msg)  ; 
	 //alert ('shola');
}
function addUser (userid, fullname)
{
	//first clean user_id
	userid = cleanUserId(userid) ;
	
	//now see if it already exists  (i.e user is online)
	id = $('#'+ userid).val();
	if($(('#'+ userid)).size() != 0)return;
	
	numOnlineUsers++;
	setChatString(numOnlineUsers);
	listHtml = '<li id="' + userid + '" > ' + fullname + ' </li>';
	$('#onlineList').append(listHtml);
}
function removeUser (userid)
{
	//first clean user_id
	userid = cleanUserId(userid) ;
	
	numOnlineUsers--;

	if(numOnlineUsers < 0)
		numOnlineUsers = 0;
	
	setChatString(numOnlineUsers);
	
	userid = "#" + userid ;
	$(userid).remove();
}
function restructureChatBoxes() {
	align = 0;
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				$("#chatbox_"+chatboxtitle).css('right', '220px');
			} else {
				width = (align)*(225+7)+220;
				$("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			align++;
		}
	}
	align = 0;
}

function chatWith(chatuser) {
	chatuser = chatuser.toLowerCase();
	createChatBox(chatuser);
	$("#chatbox_"+chatuser+" .chatboxtextarea").focus();
}

function createChatBox(chatboxtitle,minimizeChatBox) {
	if ($("#chatbox_"+chatboxtitle).length > 0) {
		if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
			$("#chatbox_"+chatboxtitle).css('display','block');
			restructureChatBoxes();
		}
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
	$(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	.addClass("chatbox")
	.html('<div class="chatboxhead"><div class="chatboxtitle">'+chatboxtitle+'</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')">X</a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>')
	.appendTo($( "body" ));		   
	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	$("#chatbox_"+chatboxtitle).css('position', 'fixed');
	
	chatBoxeslength = 0;
	
	var c = 0;
	for (x in chatBoxes) {
		c++;
		if ($("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}
	
	if (chatBoxeslength == 0) {
		$("#chatbox_"+chatboxtitle).css('right', '220px');
	} else {
		width = (chatBoxeslength)*(225+7)+220;
		$("#chatbox_"+chatboxtitle).css('right', width+'px');
	}
	
	chatBoxes[c] = chatboxtitle;
//	chatBoxes.push(chatboxtitle);

	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		if ($.cookie('chatbox_minimized')) {
			minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxtitle) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}

	chatboxFocus[chatboxtitle] = false;

	$("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
		chatboxFocus[chatboxtitle] = false;
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[chatboxtitle] = true;
		newMessages[chatboxtitle] = false;
		$('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	$("#chatbox_"+chatboxtitle).click(function() {
		if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
			$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		}
	});

	$("#chatbox_"+chatboxtitle).show();
}

function closeChatBox(chatboxtitle) {
	$('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();

	disconnect(chatboxtitle);

}

function toggleChatBoxGrowth(chatboxtitle) {
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if ($.cookie('chatbox_minimized')) {
			minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1);


		$.cookie('chatbox_minimized', newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if ($.cookie('chatbox_minimized')) {
			newCookie += '|'+$.cookie('chatbox_minimized');
		}


		$.cookie('chatbox_minimized',newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
}

function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	 
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");

		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','44px');
		if (message != '') 
		{
			msgStanza = $msg(
					{
						"to": unCleanUserId(chatboxtitle) + '@' + domain + '',
						"type":"chat"
					}
				).c("body").t(message);
			connection.send(msgStanza);
			
			message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
			$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
			$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			//post to backend session
			$.post(baseUrl + "/chat/index/send", {to: chatboxtitle, message: message} , function(data){});
		}
		return false;
	}

	var adjustedHeight = chatboxtextarea.clientHeight;
	var maxHeight = 94;

	if (maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > chatboxtextarea.clientHeight)
			$(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		$(chatboxtextarea).css('overflow','auto');
	}
	 
}

function decrypt(str)
{
	arr = str.split('');
	k = arr.pop();
	k = k.charCodeAt(0)-65;
	for(i=0;i<arr.length;i++)
	{
		s = arr[i];
		arr[i] = s.charCodeAt(0);
		arr[i] = arr[i]-k;
		arr[i] = String.fromCharCode(arr[i]);
	}
	str = arr.join('');
	return str;
}
var currentMsg;
var jid;


var rawData = new Array();
var j = 0;
function startChatSession()
{  
	username = decrypt(username);
	password = decrypt(password);
	setChatString(-1);
	jid = username + '@' + domain +'/precurio';
	connection = new Strophe.Connection(service);
	connection.addHandler(on_iq,null,'iq',null);
	connection.addHandler(on_presence,null,'presence');
	connection.addHandler(on_message,null,'message');
	connection.rawOutput = function (data) {
		rawData[j++] = 'out:' + data;
		};
	connection.rawInput = function (data) {
		rawData[j++] = 'in:' + data;
			};
	connection.connect(jid,password,on_connect);
}
var conError;
var iqData;

function cleanUserId(userid)
{
	var domain;
	var arr;
	domain="";
	//the userid may be a full email address. if it is, get the userid from the email
	arr = userid.split('@',2);
	if(arr.length > 1)
	{
		userid = arr[0]; //the userid is the first part.
		domain = '@'+arr[1];
	}
	//now clean user_id
	userid = userid.replace(/\./g,"-");
	userid = userid + domain;
	
	return userid;
}
function unCleanUserId(userid)
{
	var domain;
	var arr;
	domain="";
	//the userid may be a full email address. if it is, get the userid from the email
	arr = userid.split('@',2);
	if(arr.length > 1)
	{
		userid = arr[0]; //the userid is the first part.
		domain = '@'+arr[1];
	}
	//now clean user_id
	userid = userid.replace(/-/g,".");
	userid = userid + domain;
	
	return userid;
}

function on_message(msg)
{
	currentMsg = $(msg).find("body").parent();
	
	msgBody = $(msg).find("body").eq(0).text();

	//msgId = $(currentMsg).attr('id');//attr[0].nodeValue;
	msgTo = $(currentMsg).attr('to');//attr[0].nodeValue;
	msgType = $(currentMsg).attr('type');//attr[1].nodeValue;
	msgFrom = $(currentMsg).attr('from');//attr[2].nodeValue;
	
	//first clean the msgFrom attribute. i.e remove "." signs from it.
	msgFrom = cleanUserId(msgFrom);
	
	switch(msgType)
	{
		case 'headline':
			on_headline(msgFrom,msgTo,msgBody);
			return true;
		case 'normal':	
			on_normal(msgFrom,msgTo,msgBody);
			return true;
		case 'groupchat':
			on_groupchat(msgFrom,msgTo,msgBody);
			return true;
		case 'error':
			on_message_error(msg);
			return true;
		case 'chat':
		default:
			break;
	}
	
	if(msgBody == "" || msgBody == undefined) return true;
	
	if(msgTo == undefined)//the message was not sent to you specifically,which means it is most likely an admin broadcast 
	{
		msgFrom  =  msgFrom == domain ? 'Administrator' : msgFrom;
	}
	else
	{
		msgFrom = msgFrom.substr(0,msgFrom.indexOf('@'));
		msgFrom = msgFrom.toLowerCase();
		
		//post to backend session
		$.post(baseUrl + "/chat/index/receive", {from: msgFrom, message: msgBody} , function(data){});
	}
	
	
	chatboxtitle = msgFrom;

	if ($("#chatbox_"+chatboxtitle).length <= 0) {
		createChatBox(chatboxtitle);
	}
	if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
		$("#chatbox_"+chatboxtitle).css('display','block');
		restructureChatBoxes();
	}
	
	$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+msgFrom+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+ msgBody + '</span></div>');

	$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);

	newMessages[chatboxtitle] = true;
	newMessagesWin[chatboxtitle] = true;
	
	if (windowFocus == false) {
		 
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					document.title = x+' says...';
					titleChanged = 1;
					break;	
				}
			}
		}
		
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}

	} else {
		for (x in newMessagesWin) {
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		if (newMessages[x] == true) {
			if (chatboxFocus[x] == false) {
				//FIXME: add toggle all or none policy, otherwise it looks funny
				$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
			}
		}
	}
	return true;
	
}
function on_message_error(data)
{
	conError = data;
//	alert('message error');
	return true;
}
function on_presence(data)
{
	presence = $(data).eq(0);
	type =  ($(presence).attr('type'));
	switch(type)
	{
		case 'subscribe':
			on_subscribe(data);
			return true;
		case 'subscribed':	
			on_subscribed(data);
			return true;
		case 'unsubscribe':
			on_unsubscribe(data);
			return true;
		case 'unsubscribed':	
			on_unsubscribed(data);
			return true;
		case 'probe':
			on_probe(data);
			return true;
		case 'unavailable':
			on_unavailable(data);
			return true;
		case 'error':
			on_presence_error(data);
			return true;
		case undefined:
			break;
	}
	
	from =  ($(presence).attr('from'));
	name = from.substr(0,from.indexOf('@'));
	name = name.toLowerCase();
	if(name == "all")return true;
	addUser(name,name);
	return true;
}

function on_groupchat(from,to,msg)
{
//	alert('groupchat');
	return true;
}
function on_headline(from,to,msg)
{
//	alert('headline');
	return true;
}
function on_normal(from,to,msg)
{
	if(msg == 'psm')//sender has requested subscription initiation
	{
		from = unCleanUserId(from);
		setChatString(numOnlineUsers);
		//first check if sender is not on roster already
		if(isMyFriend(from))return true;
		//then check if it is not to myself
		if(from == jid)return true;
		//now send subscription request to sender
		connection.send($pres({'type':'subscribe', 'to':from}).tree());
	}
	return true;
}

function on_unavailable(data)
{
	presence = $(data).eq(0);
	from =  ($(presence).attr('from'));
	name = from.substr(0,from.indexOf('@')).toLowerCase();
	removeUser(name);
	return true;
}
function on_subscribe(data)
{
	presence = $(data).eq(0);
	from =  ($(presence).attr('from'));
	//first add the guy to your rooster
	name = from.substr(0,from.indexOf('@'));
	name = name.toLowerCase();
	connection.send($iq({type: 'set',id:'additem','from':jid, xmlns: Strophe.NS.CLIENT}).c(
		    'query', {xmlns: Strophe.NS.ROSTER}).c('item',{'jid':from,'name':name}).tree());
	//then approve subscription
	connection.send($pres({'type':'subscribed', 'to':from}).tree());//accept all subscriptions
}
function on_subscribed(data)
{
//	alert('subscribed');
	presence = $(data).eq(0);
	from =  ($(presence).attr('from'));
	//confirm subscription
	connection.send($pres({'type':'subscribed', 'to':from}).tree());//confirm all subscriptions
	return true;
}
function on_unsubscribe(data)
{
//	alert('unsubscribe');
	return true;
}
function on_unsubscribed(data)
{
//	alert('unsubscribed');
	return true;
}
function on_probe(data)
{
//	alert('probe');
	return true;
}
function on_presence_error(data)
{
	conError = data;
//	alert('presence error');
	return true;
}
function on_iq(data)
{
	iqData = data;
	
	iq = $(data).eq(0);
	type =  ($(iq).attr('type'));
	id =  ($(iq).attr('id'));
	if(type == 'result')
	{
		setChatString(numOnlineUsers);
		if(id == 'rooster_1')
		{
			$(data).find("item").each(function(){
				updateRooster(id,this);
			});
		}
		else
		{	
			//reply (comply with specs)
			connection.send($iq({type: 'result','id':id,'to':domain, xmlns: Strophe.NS.CLIENT}).tree());
		}
	}
	if(type == 'set')
	{	
		item = $(data).find("item").eq(0);
		updateRooster(id,item);
	}
	if(type == 'error')
	{	
		conError = data;
		if(id == 'addItem')//error with add contact to roster
		{
			//TODO determine what to do here.
		}
	}
	return true;
}
var userList = new Array();
function updateRooster(id,item)
{
	user =  ($(item).attr('jid'));
	
	if(user.indexOf('/') != -1)//removes the resource part of the identifier
		user = user.substr(0,user.indexOf('/'));
	
	if(isMyFriend(user))
	{
		var pos;
		//update the user in userlist
		jQuery.each(userList,function(i,item){
			if($(item).attr('jid') == user && $(item).attr('subscription') == 'both')
			{	
				pos = i;
				return false;
			}
		});
		userList[pos] = item;//update
	}
	else
	{
		//add user to list.
		userList.push(item);
	}
	//TODO then update rooster UI
}
function isMyFriend(user)
{
	if(user.indexOf('/') != -1)//removes the resource part of the identifier
		user = user.substr(0,user.indexOf('/'));
	var found = false;
	jQuery.each(userList,function(i,item){
		if($(item).attr('jid') == user && $(item).attr('subscription') == 'both')
		{	
			found = true;
			return false;
		}
	});
	
	return found;
}
function on_connect(status)
{
	if(status == Strophe.Status.CONNECTED)
	{
		setChatString(-2);
		setTimeout("initConnect()", 2000);
	}
	else if(status == Strophe.Status.CONNFAIL || status == Strophe.Status.DISCONNECTED || status == Strophe.Status.AUTHFAIL)
	{
		setChatString(-3);
	}
		
	
}
function initConnect()
{
	connection.send($iq({type: 'get',id:'rooster_1', xmlns: Strophe.NS.CLIENT}).c(
		    'query', {xmlns: Strophe.NS.ROSTER}).tree());
	connection.send($pres().tree());
	
	loadChatSession();

	setTimeout("iniSub()", 3000);
}
function iniSub()
{
	connection.send($msg({type:'normal',to:'all@broadcast.' + domain}).c("body").t('psm').tree());//psm=please subscribe me
}
function disconnect(from)
{
	//@TODO disconnect person whoose name == from;
	$.post(baseUrl + "/chat/index/close", { chatbox: from} , function(data){	
	});
}
function loadChatSession(){  
	var username;
	$.ajax({
	  url: baseUrl + "/chat/index/start/",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;
		
		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				if(item.f == domain)item.f = 'Administrator';
				chatboxtitle = item.f;

				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,1);
				}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
				}
			}
		});
		
		for (i=0;i<chatBoxes.length;i++) {
			chatboxtitle = chatBoxes[i];
			$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
		}
	
		
	}});
}

/**
 * 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
 *
 */

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;
    }
};
