var gCH1Cookie = null;

function CH1Cookie()
{   if( gCH1Cookie != null )
    {   return gCH1Cookie;
	}
	//this.parseCookies();
    /*
	if( gCH1Cookie == null )
	{   var obj = new Object;
		obj.prototype = CH1Cookie.prototype;
		obj.cookieString = document.cookie;
		try
		{   obj.parseCookies();
		}
		catch( e )
		{   alert( 'error: ' + e );
		}
		gCH1Cookie = obj;
	}
	return gCH1Cookie;
    */
	this.created = 1;
}

CH1Cookie.prototype.parseCookies = function()
{   this.cookieStrings = document.cookie.split( /;\s*/ );
	this.numCookies = 0;
	this.cookies = new Array();
	for( var i = 0; i < this.cookieStrings.length; i++ )
	{   var match = this.cookieStrings[i].match( /^([^=]*)=(.*)$/ );
		if( !match )
		{   continue;
		}
		var cookie_name = unescape( match[1] );
		var cookie_val = match[2];
		if( cookie_val.match( /&/ ) )
		{   cookie_val = parseQueryArgs( cookie_val );
		}
		else
		{   cookie_val = unescape( cookie_val );
		}
		this.cookies[cookie_name] = cookie_val;
		this.numCookies++;
	}
	this.dirty = false;
	this.modifiedCookies = new Array();
	return this.numCookies;
};

CH1Cookie.prototype.setCookie = function( aName, aCookie )
{   if( this.cookies[aName] == null )
    {   this.numCookies++;
	}
	this.cookies[aName] = aCookie;
	this.dirty = true;
	this.modifiedCookies[aName] = true;
};

CH1Cookie.prototype.saveCookies = function( aName )
{   if( aName == null && this.dirty )
    {   for( var name in this.modifiedCookies )
        {   if( name != null )
            {   this.saveCookies( name );
			}
		}
		this.dirty = false;
		this.modifiedCookies = new Array();
	}
	else
	{   var cookie_name = escape( aName );
		var cookie_val = '';
		if( typeof this.cookies[aName] == 'string' )
		{   cookie_val = escape( this.cookies[aName] );
		}
		else
		{   for( var attr in this.cookies[aName] )
		    {   if( cookie_val != '' )
		        {   cookie_val += '&';
		        }
				cookie_val += escape( attr ) + '=' + escape( this.cookies[aName][attr] );
			}
		}
		document.cookie = escape( aName ) + '=' + cookie_val;
	}
};

CH1Cookie.prototype.getCookie = function( aName )
{   return this.cookies[aName];
};

CH1Cookie.prototype.getCookieParam = function( aName, aParam )
{   if( typeof this.cookies[aName] == 'string' )
    {   return null;
	}
	else
	{   return this.cookies[aName][aParam];
	}
};

function getQueryArgs()
{   var query = document.location.search.match( /^\?(.*)$/ );
	if( query )
	{   return parseQueryArgs( query[1] );
	}
	else
	{   return new Array();
	}
}

function parseQueryArgs( aQuery )
{   var argpairs = aQuery.split( '&' );
	var args = new Array();
	for( var i = 0; i < argpairs.length; i++ )
	{   var pair = argpairs[i].split( '=' );
		var key = unescape( pair.shift() );
		var val = unescape( pair.join( '=' ) );
		args[key] = val;
	}
	return args;
}

try
{   gCH1Cookie = new CH1Cookie();
	gCH1Cookie.parseCookies();
}
catch( e )
{   alert( 'error: ' + e );
}
