﻿/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	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 pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

//get the value
Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

//add the value (will cause refresh)
Querystring.prototype.add = function(key, value) {
	var append = "?";
	
	if(location.search.indexOf("?") != -1 && location.search.length > 1){
		append = "&";
	}
	if(location.search == "?"){
		location.search = append + key + "=" + value;
	}
	else {
		location.search += append + key + "=" + value;
	}	
}

//checks to see if the value exists
Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

//sets the value in the querystring
Querystring.prototype.setValue = function(key, value) {
	if(this.contains(key)){
		this.params[key] = value;
		var newQstring = "";
		var append = "?";
		for (var i in this.params){
			if(this.params[i] != ""){
				newQstring += append + i + "=" + this.params[i];
				append = "&";
			}
		}
		location.search = newQstring;
	}
	else {
		location.search += append + key + "=" + value;
	}
}

//removes the key/value in the querystring
Querystring.prototype.remove = function(key) {
	if(this.contains(key)){
		var newQstring = "?";
		var append = "";
		for (var i in this.params){
			if(i != key){
				newQstring += append + i + "=" + this.params[i];
				append = "&";
			}
		}
		location.search = newQstring;
	}
}