

//////////////////////////////////////////////
// Querystring parser v1.0					//
//											//
// note: Querystring is a static object and	//
// need only to be parsed once.				//
// It is therefore created as an anonymous	//
// function with lazy instantiation (ref.	//
// singleton design pattern)				//
//////////////////////////////////////////////


var QueryString = new function()
{
	// Get the number of items in the querystring.
	this.Count = 0;


	// Determine if a given key is in the querystring.
	this.Exists = function(key)
	{
		return (typeof(query[key]) != 'undefined');
	};


	// Write entire querystring
	this.Flush = function()
	{
		var s = new String();
		if (this.Count)
		{
			for (var item in query)
			{
				s += item + '=' + query[item] + '\n';
			}
		}
		else
		{
			s = '{empty}';
		}

		return s;
	};


	// Get the item for a given key.
	this.Item = function(key)
	{
		return new String((this.Exists(key)) ? query[key] : '');
	};


	// Get array of keys.
	this.Keys = function()
	{
		var indices = new Array();

		if (this.Count)
		{
			for (var item in query)
			{
				indices[indices.length] = item;
			}
		}

		return indices;
	};


	// Return querystring in unaltered form
	this.Raw = function()
	{
		return new String(document.location.search);
	};


	// Return constant with version number.
	this.Version = 1.1;


	//////////////////////
	// initialize begin	//
	//////////////////////


	var query = new Array();				// local variable that holds querystring as associative array
	var search = document.location.search;	// local variable of the querystring part of the location including the questionmark.


	// remember to discount questionmark (ie. x > 1) when testing for actual content in querystring
	if (search.length > 1)
	{
		var qs = search.substring(1);

		// normalize space
		qs = qs.replace(/\+/g, ' ');

		// arrayalize
		qs = qs.split('&');
		if (!qs) { return; }

		var kp; // key pair(s)
		for (var i=0; i<qs.length; ++i)
		{
			kp = qs[i].split('=');

			// replace value if content is missing
			if (typeof(kp[1]) == 'undefined') { kp[1] = ''; }

			// test whether item already exists
			if (typeof(query[kp[0]]) != 'undefined')
			{
				query[kp[0]] += ',' + unescape(kp[1]);
			}
			else
			{
				query[kp[0]] = unescape(kp[1]);

				this.Count++;
			}
		}
	}


	//////////////////////
	// initialize end	//
	//////////////////////
};


//////////////////
// end of file	//
//////////////////

