﻿/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
	
	mods to add "set" and "write" "count" and init by dc
*/


function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object();
	this.get=Querystring_get;
	this.set=Querystring_set;
	this.writeQS = writeQS;
	this.notDefined = qsItemIsUndefined;
	this.count = 0;
	
	if (qs == null){
		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
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=');
		var name = unescape(pair[0]);
		if (!(typeof (this.params[name])==='undefined')){//ignore duplicates
		
			//alert("ignoring duplicate parameter " + name);
		}
		else{
			this.count = 1+this.count;//count this one
			if (pair.length == 2)
				{value = unescape(pair[1]);}
			else
				{value = name;}
			
			this.params[name] = value;
		}
	}
	
	
	function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
		if (default_ == null) default_ = null;
	
		var value=this.params[key];
		if (value==null){
				value=default_;}
		return value;
	};
	
	function Querystring_set(key, value_) {
		
		if (typeof (this.params[key])==='undefined'){
			
			this.count = 1 + this.count;
		}
		this.params[key] = unescape(value_);	

	};
	
	function writeQS (){
		 var str = "?";
		 var i = 0;
		 for (var prop in this.params){
		
			str = str + prop + "=" + this.params[prop];
			if ((i++)<(this.count-1)){
				str = str + "&";
				}
		}
		
		location.search = str;
		
	};
	
	function qsItemIsUndefined(anItem){
		return (typeof (this.params[anItem])==='undefined');
	};
}