/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/

// Optionally pass in an array of params to not include, 
// and an array of '=' delimited QS values to replace if they currently exist or add if they don't (e.g. "dist=newDistValue")
function Querystring(paramsToRemove, paramsToInsert) 
{ 
	this.values = new Object();
	this.get = Querystring_get;
	this.toString = Querystring_toString;
	
	var qs = location.search.substring(1, location.search.length);

	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	this.params = new Array();
	var paramIndex = 0;
	
	for (var i = 0; i < args.length; i++) 
	{
		var value;
		var pair = args[i].split('=');
		var name = unescape(pair[0]);

		if (pair.length == 2)
		{
			value = unescape(pair[1]);
		}
		else
		{
			value = name;
		}
		
		// Check to see if the current name should be removed.
		var paramFound = false;
		
		if(paramsToRemove != null && paramsToRemove.length > 0)
		{
			for(var r = 0; r < paramsToRemove.length; r++)
			{
				if(name == paramsToRemove[r])
				{
					paramFound = true;
					break;
				}
			}
		}
		
		if(!paramFound)
		{
			this.values[name] = value;
			this.params[paramIndex] = name;
			paramIndex++;
		}
	}
	
	// OK, now spin through all the inserts. If the name exists, replace the value.
	// Otherwise, append to values and params.
	if(paramsToInsert != null && paramsToInsert.length > 0)
	{
		for(var p = 0; p < paramsToInsert.length; p++)
		{
			var insertPair = paramsToInsert[p].split('=');
			
			if(insertPair.length == 2)
			{
				var insertName = insertPair[0];
				var insertValue = insertPair[1];
				
				if(this.get(insertName, null) == null)
				{
					this.params[paramIndex] = insertName;
					paramIndex++;				
				}

				this.values[insertName] = insertValue;
			}
		}
	}

}

function Querystring_toString()
{
	var currentQS = "";
	
	if(this.params != null && this.params.length > 0)
	{
		for(var i = 0; i < this.params.length; i++)
		{
			currentQS += this.params[i] + "=" + this.values[this.params[i]];
			
			if(i < (this.params.length - 1))
			{
				currentQS += "&";
			}
		}	
	}
	
	return currentQS;
}

function Querystring_get(key, defaultValue) 
{
	// This silly looking line changes UNDEFINED to NULL
	if (defaultValue == null) 
	{
		defaultValue = null;
	}
	
	var value = this.values[key];
	
	if (value == null) 
	{
		value = defaultValue;
	}
	
	return value
}