/*

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 cloud_url = 'http://c1394202.r2.cf0.rackcdn.com/media/users/tiny';
var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 33000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();
var right_margin = 475;

$(document).ready(function(){
	originalTitle = document.title;
	//startChatSession(); 

	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
});

function restructureChatBoxes() {
	var align = 0;
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				$("#chatbox_"+chatboxtitle).css('right', right_margin +'px');
			} else {
				width = (align)*(2425+7)+right_margin;
				$("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			align++;
		}
	}
}

function chatWith(chatuser, chaticon) {
	createChatBox(chatuser,0,chaticon);
	showChatHistory(chatuser);
	$('#chatBox_'+chatuser).focus();
}

function createChatBox(chatboxtitle,minimizeChatBox,chatphoto) {
	if ($("#idChat_"+chatboxtitle).length > 0) {
		//restructureChatBoxes();
		if ($("#idChat_"+chatboxtitle).hasClass("chatCollapsed")) {
			$("#idChat_"+chatboxtitle).removeClass("chatCollapsed");
			$("#idChat_"+chatboxtitle).addClass("chatExpanded");
		}
		return;
	}
	// Just in case no photo passed, value is 'null' (text) if passed from WhoList - dock bar
	if ( (typeof chatphoto  === "undefined") || (chatphoto == 'null') ) { 
		cloud_url = '/img/no_avatar.jpg'; 
		chatphoto = ''; 
	}
	
	// load New chat window
    $.ajax({ url: '/chat/chatbox/?chattitle='+chatboxtitle+'&chaticon='+cloud_url + chatphoto,
        dataType: 'html',
        async: false,
        success: function(data, status) {
            $(function() {
                $(document.body).append(data); 
            });
        }
    });
    $("#idChat_"+chatboxtitle).show();
   
	chatBoxeslength = 0;

	for (x in chatBoxes) {
		if ($("#idChat_"+chatboxtitle).hasClass("chatExpanded")) {
			chatBoxeslength++;
		}
	}

	if (chatBoxeslength == 0) {
		//$("#idChat_"+chatboxtitle).css('right', right_margin+'px');
	} else {
		width = (chatBoxeslength)*(300)+right_margin;
		$("#idChat_"+chatboxtitle).css('right', width+'px');
	}

	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) {
			if ($("#idChat_"+chatboxtitle).hasClass("chatExpanded")) {
				$("#idChat_"+chatboxtitle).removeClass("chatExpanded");
				$("#idChat_"+chatboxtitle).addClass("chatCollapsed");
			}
		}
	}

	chatboxFocus[chatboxtitle] = false;
/*
	$("#idChat_"+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 chatHeartbeat(){

	var itemsfound = 0;
	
	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
//				$('#idChat_'+x+' .chatboxhead').toggleClass('chatboxblink');
//			}
//		}
//	} 
	
	var last_time_stamp = '';
	$.ajax({
	  url: "/chat/chatheartbeat",
	  cache: false,
	  dataType: "json",
	  success: function(data) {

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				var chatboxtitle = item.f;
				var last_recv = item.lr;
	        	
				if ($("#idChat_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,0,item.a);
				}
				
				if ($("#idChat_"+chatboxtitle).hasClass("chatCollapsed")) {
					$("#idChat_"+chatboxtitle).addClass("chatExpanded");
					$("#idChat_"+chatboxtitle).removeClass("chatCollapsed");
				}
				
				var me = '';
				if( item.f == username ) { 
	        		me = '&me=1'; 
	        	}
				
				
				if (item.s == 1) {
					item.f = username;
				}
					
				if (item.s == 2) {
					
					//load New chat message formated by template
					$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
				
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
				
					        });
					    }
					});
					
					//$("#idChat_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					newMessages[chatboxtitle] = true;
					newMessagesWin[chatboxtitle] = true;
					
					//load New chat message formated by template
					$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
					        	
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
								
					        });
					    }
					});
					
					//$("#isChat_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
				}
				
				
             	//$("#idChat_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
                
				itemsfound += 1;
				
				// Scroll to Bottom for new message
		        $("#boxScroll_"+chatboxtitle).attr('scrollTop', $("#boxScroll_"+chatboxtitle).attr('scrollHeight') );
			}
		});
		
	  
		chatHeartbeatCount++;
		if (itemsfound > 0) {
			
			chatHeartbeatTime = minChatHeartbeat;
			chatHeartbeatCount = 1;
		} else if (chatHeartbeatCount >= 10) {
			chatHeartbeatTime *= 2;
			chatHeartbeatCount = 1;
			if (chatHeartbeatTime > maxChatHeartbeat) {
				chatHeartbeatTime = maxChatHeartbeat;
			}
		}
		
		return itemsfound;
		//setTimeout('chatHeartbeat();',chatHeartbeatTime);
	}});
	
}

function closeChatBox(chatboxtitle) {
	//restructureChatBoxes();

	//$.post("/chat/closechat", { chatbox: chatboxtitle} , function(data){} );
	
	//Close chat box formated by template
	$.ajax({ url: '/chat/closechat/?box='+chatboxtitle,
	    dataType: 'html',
	    async: false,
	    success: function(data, status) {
	        $(function() {
	        	
	        });
	    }
	});
	
	$("#idChat_"+chatboxtitle).remove();
	
	
	
	return;	
}

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 maxChatBox(chatboxtitle) {
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		var maximizedChatBoxes = new Array();
		
		if ($.cookie('chatbox_maximized')) {
			maximizedChatBoxes = $.cookie('chatbox_maximized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<maximizedChatBoxes.length;i++) {
			if (maximizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)
		
		$.cookie('chatbox_maximized', newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	
	
	} else {
		
		if  ( $('#chatbox_'+chatboxtitle).css('width') == '800px' ) {
				$('#chatbox_'+chatboxtitle).css('width','245px');
				$('#chatbox_'+chatboxtitle+' .chatboxhead').css('width','235px');
				$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('width','229px');
				$('#chatbox_'+chatboxtitle+' .chatboxinput').css('width','235px');
				$('#chatbox_'+chatboxtitle+' .chatboxtextarea').css('width','226px');
				
		} else {
				
			var newCookie = chatboxtitle;

			if ($.cookie('chatbox_maximized')) {
				newCookie += '|'+$.cookie('chatbox_maximized');
			}

			$.cookie('chatbox_maximized',newCookie);
			$('#chatbox_'+chatboxtitle).css('width','800px');
			$('#chatbox_'+chatboxtitle).css('left','300px');
			$('#chatbox_'+chatboxtitle+' .chatboxhead').css('width','784px');
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('width','784px');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('width','790px');
			$('#chatbox_'+chatboxtitle+' .chatboxtextarea').css('width','782px');
		}
	}
	
}



function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	 
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");
		
		// Just in case no username
		if (typeof username  === "undefined") { 
			$.ajax({
				  url: "/chat/startchatsession",
				  cache: false,
				  dataType: "json",
				  success: function(data) {
			 		username = data.username;
			 	
				}
			});
		}
		
		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		if (message != '') {
			$.post("/chat/sendchat", {to: chatboxtitle, message: message} , function(data){
				var username = data.username;
				var time_stamp = data.stamp;
				message = data.msg_san;
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				
				//load New chat message formated by template
				$.ajax({ url: '/chat/new_message/?msg='+message+'&stamp='+time_stamp+'&recip='+chatboxtitle+'&me=1',
				    dataType: 'html',
				    async: false,
				    success: function(data, status) {
				        $(function() {
				        	// Append msg to div
				        	$("#boxScroll_"+chatboxtitle).append(data);
				        	
				            // Scroll to Bottom for new message
				            $("#boxScroll_"+chatboxtitle).attr('scrollTop', $("#boxScroll_"+chatboxtitle).attr('scrollHeight') );
				        });
				    }
				});
				
			});
		}
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;

		return false;
	}

	//var adjustedHeight = chatboxtextarea.clientHeight;
	//var maxHeight = 50; //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 checkChatBoxSend(chatboxtextarea,chatboxtitle) {
	 
//	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = $("div#idChat_"+chatboxtitle+" .chMsgInput").val();
		message = message.replace(/^\s+|\s+$/g,"");
		
		// Just in case no username
		if (typeof username  === "undefined") { 
			$.ajax({
				  url: "/chat/startchatsession",
				  cache: false,
				  async: false,
				  dataType: "json",
				  success: function(data) {
			 		username = data.username;
			 	
				}
			});
		}
		
		$("div#idChat_"+chatboxtitle+" .chMsgInput").val('');
		$("div#idChat_"+chatboxtitle+" .chMsgInput").focus();
		if (message != '') {
			$.post("/chat/sendchat", {to: chatboxtitle, message: message} , function(data){
				var username = data.username;
				var time_stamp = data.stamp;
				message = data.msg_san;
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				
				//load New chat message formated by template
				$.ajax({ url: '/chat/new_message/?msg='+message+'&stamp='+time_stamp+'&recip='+chatboxtitle+'&me=1',
				    dataType: 'html',
				    async: false,
				    success: function(data, status) {
				        $(function() {
				        	// Append msg to div
				        	$("#boxScroll_"+chatboxtitle).append(data);
				        	
				            // Scroll to Bottom for new message
				            $("#boxScroll_"+chatboxtitle).attr('scrollTop', $("#boxScroll_"+chatboxtitle).attr('scrollHeight') );
				        });
				    }
				});
				
			});
		}
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;

		return false;
//	}

}


function startChatSession(){  
	$.ajax({
	  url: "/chat/startchatsession",
	  cache: false,
	  async: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				var chatboxtitle = item.f;
				var last_recv = item.lr;
	        	
				if ($("#idChat_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,1, item.a);
				}
				
				var me = '';
				if( item.f == username ) { 
	        		me = '&me=1'; 
	        	}
				
				if (item.s == 1) {
					item.f = username;
				}

				if (item.s == 2) {
					
					//load New chat message formated by template
					$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
				
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
				
					        });
					    }
					});
					
				} else {
					
					//load New chat message formated by template
					$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
				
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
				
					        });
					    }
					});
					
				}
			}
		});
		
		for (i=0;i<chatBoxes.length;i++) {
			chatboxtitle = chatBoxes[i];
		 //   $("#boxScroll_"+chatboxtitle).scrollTop($("#boxScroll_"+chatboxtitle)[0].scrollHeight);
		//	setTimeout('$("#boxScroll_"+chatboxtitle).scrollTop($("#boxScroll_"+chatboxtitle)[0].scrollHeight);', 100); // yet another strange ie bug
		}
	
	//setTimeout('chatHeartbeat();',chatHeartbeatTime);
		
	}});
}


function showChatHistory(chatboxtitle){ 
	
	$.ajax({
	  url: "/chat/getChatHistory/?chattitle="+chatboxtitle,
	  cache: false,
	  async: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;
		
		// Clear Chat Box
		$("#boxScroll_"+chatboxtitle).html('');
		
		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				var chat_from = item.f;
				var last_recv = item.lr;
	        	var me = '';
	        	
	        	if( username == chat_from ) { 
	        		me = '&me=1'; 
	        	}
							
				//load New chat message formated by template
				$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
				
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
				
					        });
					    }
				});
				
			}
		}	
	
		)
		
		 // Scroll to Bottom for new message
        $("#boxScroll_"+chatboxtitle).attr('scrollTop', $("#boxScroll_"+chatboxtitle).attr('scrollHeight') );
   
		
	}
	
	});
}


function clearChatBox(chatboxtitle){ 
	
   	$("#boxScroll_"+chatboxtitle).html('');
	$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: ');

}


function showChatRecent(chatboxtitle){ 
	
	$.ajax({
	  url: "/chat/getChatRecent/?chattitle="+chatboxtitle,
	  cache: false,
	  async: false,
	  dataType: "json",
	  success: function(data) {
 
		username = data.username;
		
		// Clear Chat Box
		$("#boxScroll_"+chatboxtitle).html('');
		
		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				var chat_from = item.f;
				var last_recv = item.lr;
	        	var me = '';
	        	
	        	if( username == chat_from ) { 
	        		me = '&me=1'; 
	        	}
							
				//load New chat message formated by template
				$.ajax({ url: '/chat/new_message/?msg='+item.m+'&stamp='+item.t+'&recip='+chatboxtitle+me,
					    dataType: 'html',
					    async: false,
					    success: function(data, status) {
					        $(function() {
					        	// Append msg to div
					        	$("#boxScroll_"+chatboxtitle).append(data);
				
					        	// Set the last recv
								$("div#idChat_"+chatboxtitle+' .chMsgInfo').html('Last received: '+last_recv);
				
					        });
					    }
				});
				
			}
		}	
	
		)
		
		 // Scroll to Bottom for new message
        $("#boxScroll_"+chatboxtitle).attr('scrollTop', $("#boxScroll_"+chatboxtitle).attr('scrollHeight') );
   
		
	}
	
	});
}

	
/**
 * Cookie plugin
 *
 * Copy right (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;
    }
};
