﻿
/********************************************************/
/*                    ISURI CHAT                        */
/*                    April 2010                        */
/*                  www.isuri.com.ar                    */
/********************************************************/


var _userID;
var online = false;

(function ($) {

	$.fn.isuriChat = function (userID) {

		_userID = userID;

		if (userID != null) {
			setInterval('PopMessage(' + userID + ')', 3000);   //get messages
			setInterval('refreshContactList(' + userID + ')', 30000); //refresh contacts
		};

		/***************************************************/
		/************  CREATE THE HTML *********************/
		/***************************************************/
		var html = "";


		html = html + "<div id='divContenedor'>";
		html = html + "<div id='divContenedor2'>";

		html = html + "<div id='chatBar' userID='" + userID + "'>";
		html = html + "<div class='btnChat' onClick='ToggleDiv(\".contactList\");refreshContactList(" + userID + ");'><span> Chat </span></div>";

		html = html + "</div>";

		/* creation div of Contacts Online */
		html = html + "<div class='contactList'>";

		$.ajax({
			type: "POST",
			url: baseUrl + "isuriChat.asmx/IsOnline",
			data: '{"userID":"' + userID + '"}',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msj) {
				if (msj.d != "error") {
					if (msj.d == "Offline") {
						online = false;
						html = html + "<div class='titleContactList'>(Offline)&nbsp;&nbsp;<a onclick='fnGoOnline(" + userID + ");' class='goOnlineLinkHeader'>(Go online)</a></div>";
					}
					else {
						online = true;
						html = html + "<div class='titleContactList'>Chat&nbsp;&nbsp;<a onclick='fnGoOffline(" + userID + ");' class='goOfflineLinkHeader'>(Go offline)</a></div>";
					}
				}
			},
			error: function () {
				accion = 1;
			},
			async: false
		});

		html = html + "<div class='contentContactList'></div>";
		html = html + "";
		html = html + "";
		html = html + "</div>";

		this.append(html);

		if (online) {
			loadcookieData();
		}
	}

})(jQuery);


/***********************************************/
/***************   FUNCIONS      **************/
/***********************************************/


function ToggleDiv(div) {
	$(div).toggle();
}

function toogleChatBox(idChatBox) {
	if ($("#chatBox" + idChatBox).is(":visible")) {
		$("#chatBox" + idChatBox).hide();
		$("#pestañaBar" + idChatBox).css("background-color", "gainsboro");
		$("#pestañaBar" + idChatBox).css("color", "#1377A2");
		$.cookie("maximizedChatBox", null, { path: '/' });
	}
	else {
		//minimize
		$.each($(".chatBox"), function () {
			$(this).hide();
		});
		//css
		$.each($(".pestañaBar"), function () {
			$(this).css("background-color", "gainsboro");
		});

		$("#chatBox" + idChatBox).show();
		$("#chatBox" + idChatBox + " textarea").focus();

		$("#chatBox" + idChatBox + " .contentDiv").scrollTop($("#chatBox" + idChatBox + " .contentDiv").attr("scrollHeight"));

		$("#pestañaBar" + idChatBox).css("background-color", "white");

		//fill cookie
		$.cookie("maximizedChatBox", idChatBox, { path: '/' });
	}
}

function loadcookieData() {
	if ($.cookie("activeChats") != null) {
		var activeChats = $.cookie('activeChats').split("*");
		var maximizedChat = $.cookie("maximizedChatBox");
		var blinkChats = null;
		if ($.cookie('blinkChat') != null)
			blinkChats = $.cookie('blinkChat').split("*");
		var i = 0;

		for (i = 0; i < activeChats.length; i++) {
			if (activeChats[i] != "") {
				$.ajax({
					type: "POST",
					url: baseUrl + "isuriChat.asmx/getUserName",
					data: '{"userID":"' + activeChats[i] + '"}',
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function (msj) {
						if (msj.d != "error") {
							createChatWindow(activeChats[i], msj.d);
							$("#chatBox" + activeChats[i] + " .contentDiv").append($.cookie("chat" + activeChats[i]));
							$("#chatBox" + activeChats[i] + " .contentDiv").scrollTop($("#chatBox" + activeChats[i] + " .contentDiv").attr("scrollHeight") - $("#chatBox" + activeChats[i] + " .contentDiv").height());
							if ($("#chatBox" + activeChats[i] + " .contentDiv").html() == "") {
								closeChatBox(activeChats[i]);
							}
						}
					},
					error: function () {
						accion = 1;
					},
					async: false
				});

			}
		}

		//Maximize the chatBox
		$.each($(".chatBox"), function () {
			$(this).hide();
		});
		$(".pestañaBar").css("background-color", "gainsboro");
		if (maximizedChat != null) {
			$("#chatBox" + maximizedChat).show();
			$("#pestañaBar" + maximizedChat).css("background-color", "white");
			$("#pestañaBar" + maximizedChat).css("color", "#1377A2");
			$.cookie("maximizedChatBox", maximizedChat, { path: '/' })
		}
		else
			$.cookie("maximizedChatBox", null, { path: '/' });

		//Blink post bar for chat
		if (blinkChats != null) {
			i = 0;
			for (i = 0; i < blinkChats.length; i++) {
				blinkPestañaBar(blinkChats[i]);
			}
		}


	}
}

function quitarTextoParpad(idPestaña) {
	$("#pestañaBar" + idPestaña).css("color", "#1377A2");


	if ($.cookie("blinkChat") != null) {
		idsConvers = $.cookie('blinkChat').split("*");
		var i = 0;
		var idConversNew = "";
		for (i = 0; i < idsConvers.length; i++) {
			if (idsConvers[i] != idPestaña) {
				if (idConversNew == "")
					idConversNew = idsConvers[i];
				else
					idConversNew = idConversNew + "*" + idsConvers[i];
			}
		}
		$.cookie("blinkChat", idConversNew, { path: '/' });
	}
}

function blinkPestañaBar(idPestaña) {
	$("#pestañaBar" + idPestaña).css("color", "#252870")

	if ($.cookie("blinkChat") != null) {
		idsConvers = $.cookie('blinkChat').split("*");
		var i = 0;
		var existe = false;
		for (i = 0; i < idsConvers.length; i++) {
			if (idsConvers[i] == idPestaña) {
				existe = true
			}
		}
		if (!existe)
			if ($.cookie("blinkChat") != "")
				$.cookie("blinkChat", $.cookie("blinkChat") + "*" + idPestaña, { path: '/' })
			else
				$.cookie("blinkChat", idPestaña, { path: '/' })
	}
	else
		$.cookie("blinkChat", idPestaña, { path: '/' });
}

function closeChatBox(idChatBox) {
	$("#chatBox" + idChatBox).remove();
	$("#pestañaBar" + idChatBox).remove();
	refreshChatBoxPosition();

	if ($.cookie("activeChats") != null) {
		idsConvers = $.cookie('activeChats').split("*");
		var i = 0;
		var idConversNew = "";
		for (i = 0; i < idsConvers.length; i++) {
			if (idsConvers[i] != idChatBox) {
				if (idConversNew == "")
					idConversNew = idsConvers[i];
				else
					idConversNew = idConversNew + "*" + idsConvers[i];
			}
		}
		$.cookie("activeChats", idConversNew, { path: '/' });
	}

	$.cookie("chat" + idChatBox, null, { path: '/' });

	$.ajax({
		type: "POST",
		url: baseUrl + "isuriChat.asmx/CloseChatBox",
		data: '{"userID":"' + _userID + '", "fromUserID":"' + idChatBox + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msj) {
			if (msj.d != "error") {
			}
		},
		error: function () {
			accion = 1;
		},
		async: true
	});
}



function refreshChatBoxPosition() {
	$.each($(".pestañaBar"), function () {
		id = $(this).attr('id');
		res = id.substring(10, id.length);
		var offset = $("#pestañaBar" + res).offset().left - 85;
		if (offset != $("#chatBox" + res).offset().left)
			$("#chatBox" + res).offset({ left: offset });
	});
}

function refreshContactList(userID) {
	//Options:
	//0 - create the html
	//1 - error
	var accion = 0;
	var html = "";
	var json;

	$.ajax({
		type: "POST",
		url: baseUrl + "isuriChat.asmx/getContactList",
		data: '{"userID":"' + userID + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msj) {
			if (msj.d != "error") {
				accion = 0;
				eval('var z=' + msj.d);
				json = z;
				//start
				if (accion == 0) {
					//create html
					if (json.onlineUsers.count == 0) {
						html = html + "<table><tr><td>No users online</td></tr></table>";

						$.each($(".chatBox span"), function () {
							$(this).html(" (Disconnected)");
						});

						$.each($(".chatBox textarea"), function () {
							$(this).attr("disabled", "disabled");
						});
					} else {
						var i = 0;

						$.each($(".chatBox span"), function () {
							$(this).html(" (Disconnected)");
						});

						$.each($(".chatBox textarea"), function () {
							$(this).attr("disabled", "disabled");
						});

						html = html + "<table id='tblContactLst'>";
						while (i < json.onlineUsers.count) {

							var imgUrl = baseUrl + json.onlineUsers.items[i].userImage;

							if (json.onlineUsers.items[i].userName.length > 15) {
								var userName = json.onlineUsers.items[i].userName.substring(0, 14) + "...";

								html = html + "<tr class='chatContact' onclick='createChatWindow(" + json.onlineUsers.items[i].id + ", \"" + userName + "\")'><td class='chatuserImg'><img class='chatuserImg' src='" + imgUrl + "'/></td><td>&nbsp;&nbsp;</td><td>" + userName + "</td><td>&nbsp;&nbsp;</td><td class='stateImg'></td></tr>";
							}
							else {
								html = html + "<tr class='chatContact' onclick='createChatWindow(" + json.onlineUsers.items[i].id + ", \"" + json.onlineUsers.items[i].userName + "\")'><td class='chatuserImg'><img class='chatuserImg' src='" + imgUrl + "'/></td><td>&nbsp;&nbsp;</td><td>" + json.onlineUsers.items[i].userName + "</td><td>&nbsp;&nbsp;</td><td class='stateImg'></td></tr>";
							}
							$("#chatBox" + json.onlineUsers.items[i].id + " span").html("");

							$("#chatBox" + json.onlineUsers.items[i].id + " textarea").removeAttr("disabled");
							i++;
						}
						html = html + "</table>";
					}

					if (!online) {
						$(".btnChat span").html("(Offline)&nbsp;&nbsp;<a onclick='fnGoOnline(" + userID + ");' class='goOnlineLinkBar'>Go Online</a>");
					} else {
						$(".btnChat span").html("Chat (" + json.onlineUsers.count + ")");
					}
				}
				else
					html = html + "<table><tr><td>Error. Be sure that you are connected to internet.</td></tr></table>";
				//end
			}
			else {
				accion = 1;
			}
			$(".contentContactList").html(html);
		},
		error: function () {
			accion = 1;
			$(".contentContactList").html(html);
		},
		async: true
	});


}

function createChatWindow(withUserID, withUserName) {
	var chatbox = "#chatBox" + withUserID;
	var createWindow = false;
	if ($(chatbox).length)
		createWindow = false;
	else
		createWindow = true;

	if (createWindow) {
		var html = "";
		if (withUserName.length > 12) {
			var userName = withUserName.substring(0, 11) + "...";
			html = html + "<div class='pestañaBar' id='pestañaBar" + withUserID + "' onClick='toogleChatBox(" + withUserID + ")'><table><tr><td class='pestañaImage'></td><td>" + userName + "</td></tr></table></div>";
		} else {
			html = html + "<div class='pestañaBar' id='pestañaBar" + withUserID + "' onClick='toogleChatBox(" + withUserID + ")'><table><tr><td class='pestañaImage'></td><td>" + withUserName + "</td></tr></table></div>";
		}
		$("#chatBar").append(html);

		/*  Create  ChatBox*/
		html = "";
		html = html + "<div class = 'chatBox' id='chatBox" + withUserID + "' style='display:none'>";
		html = html + "<div class = 'titleDiv'> <a class='closeChat' title='Close Conversation.' onClick='closeChatBox(" + withUserID + ")'/> <a class='minimizeChat' title='Minimize Conversation' onClick='toogleChatBox(" + withUserID + ")'/> ";

		if (withUserName.length > 12) {
			var userName = withUserName.substring(0, 11) + "...";
			html = html + userName;
		}
		else html = html + withUserName;

		html = html + "<span></span>";
		html = html + "</div>";
		html = html + "<div class = 'contentDiv'>";
		html = html + "</div>";
		html = html + "<div class = 'inputDiv'>";
		html = html + "<textarea class='inputDivTxt' cols='30' onkeydown='javascript:PushMessage(event," + withUserID + ");'/>";
		html = html + "</div>";
		html = html + "</div>";
		$("#divContenedor2").append(html);

		if ($.cookie("activeChats") != null) {
			idsConvers = $.cookie('activeChats').split("*");
			var i = 0;
			var existe = false;
			for (i = 0; i < idsConvers.length; i++) {
				if (idsConvers[i] == withUserID) {
					existe = true
				}
			}
			if (!existe)
				if ($.cookie("activeChats") != "")
					$.cookie("activeChats", $.cookie("activeChats") + "*" + withUserID, { path: '/' })
				else
					$.cookie("activeChats", withUserID, { path: '/' })
		}
		else
			$.cookie("activeChats", withUserID, { path: '/' });

		toogleChatBox(withUserID);
		refreshChatBoxPosition();
		$("#chatBox" + withUserID).click(function () { quitarTextoParpad(withUserID) });
		$("#pestañaBar" + withUserID).click(function () { quitarTextoParpad(withUserID) });
	} else {
		if (!$("#chatBox" + withUserID).is(":visible")) {
			toogleChatBox(withUserID);
		}
	}

}

function PushMessage(event, toUserID) {

	if (event.keyCode != 13) {
		var chatbox = "#chatBox" + toUserID;
		$(chatbox + " textarea").focus();
		return;
	}

	if (!online) {
		var uchatbox = "#chatBox" + toUserID;
		$(uchatbox + " .contentDiv").append("Error in sending message. Make sure that you are online.<br />");
		$(uchatbox + " textarea").focus();
		return;
	}

	if (event.keyCode == 13) {
		var chatbox = "#chatBox" + toUserID;
		var message = $(chatbox + " textarea").val();
		var fromUserID = $('#chatBar').attr('userID');
		if ((message == "") | (message == "\n")) { $(chatbox + " textarea").val(""); $(chatbox + " textarea").focus(); return; }
		var tempmessage = message;
		tempmessage = strip(tempmessage);
		tempmessage = fnURLFormating(tempmessage);
		message = message.replace(/\\/g, "\\\\");
		$.ajax({
			type: "POST",
			url: baseUrl + "isuriChat.asmx/PushMessage",
			data: '{"from":"' + fromUserID + '", "to":"' + toUserID + '", "message":"' + message + '"}',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msj) {
				if (msj.d != "error") {
					$(chatbox + " textarea").val("");
					$(chatbox + " textarea").focus();
				}
			},
			error: function () {
				$(chatbox + " .contentDiv").append("Error in sending message <br />");
				event.returnValue = false; //this is for chrome,, :(
			},
			async: true
		});
	}
}

function PopMessage(UserID) {
	if (!online) {
		return;
	}
	$.ajax({
		type: "POST",
		url: baseUrl + "isuriChat.asmx/PopMessage",
		data: '{"userID":"' + UserID + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msj) {
			if (msj.d != "error") {
				PopMessageError(false);
				eval('var z=' + msj.d);
				var i = 0;
				while (i < z.messages.count) {
					if(z.messages.items[i].fromID == _userID)
					{
						var chatbox = "#chatBox" + z.messages.items[i].toID;
						
						var createWindow = true;
						if ($(chatbox).length)
						{
							createWindow = false;
						}
						if(createWindow)
						{
							createChatWindow(z.messages.items[i].toID, z.messages.items[i].toUserName);
						}

						if ($(chatbox + " .contentDiv").html().indexOf(z.messages.items[i].msgID) == -1)
						{
							var message = z.messages.items[i].message;
							message = fnURLFormating(message);
							$(chatbox + " .contentDiv").append("<div style='display:none;'>" + z.messages.items[i].msgID + "</div><b>" + z.messages.items[i].fromUserName + "</b>: " + message.replace(/\\/g, "\\") + "<br /><br/><div class='clear'></div><div class='separator'></div>");
							$(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
						}
					}
					else 
					{
						var chatbox = "#chatBox" + z.messages.items[i].fromID;

						var createWindow = true;
						if ($(chatbox).length)
						{
							createWindow = false;
						}
						if(createWindow)
						{
							createChatWindow(z.messages.items[i].fromID, z.messages.items[i].fromUserName);
						}

						if ($(chatbox + " .contentDiv").html().indexOf(z.messages.items[i].msgID) == -1) {
							var message = z.messages.items[i].message;
							message = fnURLFormating(message);
							$(chatbox + " .contentDiv").append("<div style='display:none;'>" + z.messages.items[i].msgID + "</div><b>" + z.messages.items[i].fromUserName + "</b>: " + message.replace(/\\/g, "\\") + "<br /><br/><div class='clear'></div><div class='separator'></div>");
							$(chatbox + " .contentDiv").scrollTop($(chatbox + " .contentDiv").attr("scrollHeight") - $(chatbox + " .contentDiv").height());
							blinkPestañaBar(z.messages.items[i].fromID);
						}
					}
					$.cookie("chat" + z.messages.items[i].fromID, $(chatbox + " .contentDiv").html(), { path: '/' });
					i++;
				}
			}
			else
				accion = 1;
		},
		error: function () {
			PopMessageError(true);
		},
		async: true
	});
}


function PopMessageError(value) {
	if (value) {
		$(".contentDiv").addClass("contentDivError");
		$(".inputDivTxt").val("Se perdió la conexión con el servidor. Verifique su conexión a internet.");
		$(".inputDivTxt").attr("disabled", true);
	}
	else {
		if ($(".contentDiv").hasClass("contentDivError")) {
			$(".contentDiv").removeClass("contentDivError");
			$(".inputDivTxt").val("");
			$(".inputDivTxt").removeAttr("disabled");
		}
	}
}


function fnURLFormating(msg) {
	var urlMatches = msg.match(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g);
	if (urlMatches != null) {
		urlMatches = uniqueArr(urlMatches);
		var i=0;
		for (i = 0; i < urlMatches.length; i++) {
			msg = replaceAll(msg, urlMatches[i], "<a target='_blank' href='" + urlMatches[i] + "'>" + urlMatches[i] + "</a>");
		}
	}
	return msg;
}

function replaceAll(OldString, FindString, ReplaceString) {
	var SearchIndex = 0;
	var NewString = "";
	while (OldString.indexOf(FindString, SearchIndex) != -1) {
		NewString += OldString.substring(SearchIndex, OldString.indexOf(FindString, SearchIndex));
		NewString += ReplaceString;
		SearchIndex = (OldString.indexOf(FindString, SearchIndex) + FindString.length);
	}
	NewString += OldString.substring(SearchIndex, OldString.length);
	return NewString;
}

//return new uniqueArr values to temp array
function uniqueArr(a) {
	temp = new Array();
	var k = 0;
	for (k = 0; k < a.length; k++) {
		if (!contains(temp, a[k])) {
			temp.length += 1;
			temp[temp.length - 1] = a[k];
		}
	}
	return temp;
}

//Will check for the Uniqueness
function contains(a, e) {
	var j = 0;
	for (j = 0; j < a.length; j++) if (a[j] == e) return true;
	return false;
}


function fnGoOffline(userID) {

	online = false;

	$.ajax({
		type: "POST",
		url: baseUrl + "isuriChat.asmx/GoOffline",
		data: '{"userID":"' + userID + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msj) {
			if (msj.d != "error") {
			}
		},
		error: function () {
			accion = 1;
		},
		async: false
	});

	$(".titleContactList").html("(Offline)&nbsp;&nbsp;<a onclick='fnGoOnline(" + userID + ");' class='goOnlineLinkHeader'>Go Online</a>");
	$(".btnChat span").html("(Offline)&nbsp;&nbsp;<a onclick='fnGoOnline(" + userID + ");' class='goOnlineLinkBar'>Go Online</a>");
	ToggleDiv(".contactList");
	$.each($(".chatBox"), function () {
		$(this).remove();
	});
	$.each($(".pestañaBar"), function () {
		$(this).remove();
	});
}

function fnGoOnline(userID) {

	online = true;

	$.ajax({
		type: "POST",
		url: baseUrl + "isuriChat.asmx/GoOnline",
		data: '{"userID":"' + userID + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (msj) {
			if (msj.d != "error") {
			}
		},
		error: function () {
			accion = 1;
		},
		async: false
	});

	$(".titleContactList").html("Chat&nbsp;&nbsp;<a onclick='fnGoOffline(" + userID + ");' class='goOfflineLinkHeader'>(Go Offline)</a>");
	refreshContactList(userID);
}


function chatLogout() {
	$.cookie("activeChats", null, { path: '/' });
}

function strip(html) {
	var tmp = html.replace(/<.*?>/g, '');
	return tmp;
}

/*********************************************************************************************/
/**************************      PLUGINS    **************************************************/
/*********************************************************************************************/
/*********************************************************************************************/

//2009-03-20  Plugin SETOFFSET
(function ($) {

	$.fn.extend({

		/**
		* Stores the original version of offset(), so that we don't lose it
		*/
		_offset: $.fn.offset,

		/**
		* Set or get the specific left and top position of the matched
		* elements, relative the the browser window by calling setXY
		* @param {Object} newOffset
		*/
		offset: function (newOffset) {
			return !newOffset ? this._offset() : this.each(function () {
				var el = this;

				var hide = false;

				if ($(el).css('display') == 'none') {
					hide = true;
					$(el).show();
				};

				var style_pos = $(el).css('position');

				// default to relative
				if (style_pos == 'static') {
					$(el).css('position', 'relative');
					style_pos = 'relative';
				};

				var offset = $(el).offset();

				if (offset) {
					var delta = {
						left: parseInt($(el).css('left'), 10),
						top: parseInt($(el).css('top'), 10)
					};

					// in case of 'auto'
					if (isNaN(delta.left))
						delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
					if (isNaN(delta.top))
						delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;

					if (newOffset.left || newOffset.left === 0)
						$(el).css('left', newOffset.left - offset.left + delta.left + 'px');

					if (newOffset.top || newOffset.top === 0)
						$(el).css('top', newOffset.top - offset.top + delta.top + 'px');
				};
				if (hide) $(el).hide();
			});
		}

	});

})(jQuery);

/*********************  Cookie Plugin ***************************/


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;
	}
};

