﻿
(function($)
{
	$.User =
	{
		sContextData:function(sName, sValue)
		{/* Sets or gets a cookie with the current page as the context.
			@Returns The value or jQuery.User if a set.
			@Parameters
			*sName (String): The name of the context data.
			*sValue (String): The value of the data.
			@Function sContextData ( oContext, sValue )
			Sets or gets a cookie with a specified context.
			@Parameters
			*oContext (Object): A set of key/value pairs that define the context and name of the data.
			@oContext
			*sContext (String): The name of the context to use.
			*sName (String): The name of the context data.
			*/
			var sContext;
			if(typeof arguments[0] != "string")
			{
				sContext = arguments[0]["sContext"];
				sName = arguments[0]["sName"];
			}			
			
			var oCookie = JSON.FromString(_Cookie(sContext, "Js.User")) || {};
			if(arguments.length == 1) { return oCookie[sName]; }
			oCookie[sName] = sValue;
			_Cookie(sContext, "Js.User", JSON.ToString(oCookie));
			return this;				
		},
		
		nContextData:function(sName, sValue)
		{/*	Passes arguments to the jQuery.User.sContextData() function.
			In the case of a Get, this will cast the value of the cookie to a Number.
			*/
			var oReturn = this.sContextData.apply(this, arguments);
			if(arguments.length == 1) { return Number(oReturn); }
			return oReturn;
		}
	};
	
	var _Cookie = function(sContext, sName, sValue)
	{
		var sPath = "/";
		if(sContext != null) { sName+="."+sContext; }
		else
		{	// keep /path/to/file/ (without the file name or querystring values)
			var oLoc = String(document.location).split("/").slice(3);
			sPath = oLoc.join("/");
			var oPath = sPath.split(".");
			sPath = oPath[0];
			oPath = sPath.split("/");
			oPath.pop();
			sPath = "/"+oPath.join("/")+"/";	
			if(sPath == "//") { sPath = "/"; }	
		}
		
		if(arguments.length==2)
		{
			if(document.cookie.length==0) { return null; }
			var nOffset = document.cookie.indexOf(sName+"=")
			if(nOffset == -1) { return null; }
			nOffset += sName.length+1;
			var nEnd = document.cookie.indexOf(";", nOffset)
			if(nEnd == -1) { nEnd = document.cookie.length }
			return unescape(document.cookie.substring(nOffset, nEnd))
		}
		else
		{
			document.cookie = [sName,"=",escape(sValue),"; expires=",new Date(2323,0,1).toGMTString(),"; path=",sPath,";"].join("");
		}
	};
})(jQuery);
