var ViewState = function(){this.initialize();};

ViewState.prototype = {
	_cookieName: "_nke_vs",
	_cookieValue: {},
	_cookieExpiryDays: 100,
	
	initialize: function()
	{
		this._getCookieValue();
	},
	
	getValue: function(k, d)
	{
		return this._cookieValue[k] || d;
	},
	
	setValue: function(k, v)
	{
		this._cookieValue[k] = v;
		this.updateCookie();
	},
	
	getAllKeys: function()
	{
		var keys = [];
		for(var key in this._cookieValue)
			keys.push(key);
			
		return keys;
	},
	
	reloadValues: function()
	{
		this._getCookieValue();
	},
	
	_getCookieStringValue: function()
	{
		return this._toJson(this._cookieValue);
	},
	
	updateCookie: function()
	{
		var expiryDate = new Date();
		expiryDate.setTime(expiryDate.getTime() + (this._cookieExpiryDays * 24 * 60 * 60 * 1000));
		
		var cookieExpiry = '; expires=' + expiryDate.toGMTString();
		
		document.cookie = this._cookieName + '=' + this._getCookieStringValue() + cookieExpiry + '; path=/';
	},
	
	_getCookieValue: function()
	{
		var cvalue = this._readCookie();
		
		if (cvalue == null)
		{
			this._cookieValue = {};
		}
		else
		{
			this._cookieValue = eval('(' + cvalue + ')');
		}
	},
	
	_readCookie: function()
	{
		var nameEQ = this._cookieName + '=';
		var ca = document.cookie.split(';');
		
		for(var i = 0; i < ca.length; i++)
		{
			var c = ca[i];
			while (c.charAt(0)== ' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}

		return null;
	},
	
	_toJson: function(obj)
	{
	    switch (typeof obj)
	    {
	        case 'object':
	            if (obj)
	            {
	                var list = [];
	                if (obj instanceof Array)
	                {
	                    for (var i = 0; i < obj.length; i++)
	                    {
	                        list.push(this._toJson(obj[i]));
	                    }
	                    
	                    return '[' + list.join(',') + ']';
	                }
	                else
	                {
	                    for (var prop in obj)
	                    {
	                        list.push('"' + prop + '":' + this._toJson(obj[prop]));
	                    }
	                    
	                    return '{' + list.join(',') + '}';
	                }
	            }
	            else
	            {
	                return 'null';
	            }
	            
	        case 'string':
	            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
	            
	        case 'number':
	        case 'boolean':
	            return new String(obj);
	    }
	}
};