/**
 * Builds querystrings from key/value pairs but can also parse a url
 * into its key/value pairs. A global instance is created at QueryString.current
 * that contains the querystring from the current url.
 */
function QueryString(href) {
	/** The map of key/value pairs */
	this.values = {};

	if (href && href.indexOf('?') >= 0) {
		//if there is a query string
		var href = href.substring(href.indexOf('?') + 1);
		this.readValues(href);
	}
}

/** Builds a simple querystring from a single key/value pair. It just
 * returns the string for using without actually creating new instances */
QueryString.buildFrom = function(key, value) {
	return QueryString.encode(key) + '=' + QueryString.encode(value);
};

/** Decodes a querystring parameter */
QueryString.decode = function(s) {
	var tmp = s + '';
	tmp = tmp.replace(/\+/g, ' ');
	tmp = decodeURIComponent(tmp);
	return tmp;
};

/** Encodes a querystring parameter */
QueryString.encode = function(s) {
	var tmp = s;
	//tmp = tmp.replace(/\+/g, ' ');
	tmp = encodeURIComponent(tmp);
	return tmp;
};

/** Gets a value by key */
QueryString.prototype.get = function(key) {
	return this.values[key];
};

/** Gets a value by key encoded for uri building */
QueryString.prototype.getEncoded = function(key) {
	return QueryString.encode(this.values[key]);
};

/** Gets an array of keys */
QueryString.prototype.getKeys = function() {
	var ret = [];
	for (key in this.values)
		ret.push(key);
	return ret;
};

/** Returns true if the querystring contians the key, even if its null */
QueryString.prototype.hasKey = function(key) {
	return (typeof this.values[key] != 'undefined')
};

/**
 * Reads in the values from the query string.
 * @private
 */
QueryString.prototype.readValues = function(str) {
	var pairs = str.split('&');
	for (var i=0; i<pairs.length; i++) {
		var pair = pairs[i].split('=');
		this.set(
			QueryString.decode(pair[0]),
			QueryString.decode(pair[1])
		);
	}
};

/**
 * Sets a key value pair.
 */
QueryString.prototype.set = function(key, value) {
	this.values[key] = value;
};

QueryString.prototype.toString = function() {
	var ret = '';
	for (key in this.values) {
		if (ret != '') ret += '&';
		ret += QueryString.encode(key) + '=' +
				QueryString.encode(this.values[key]);
	}
	return ret;
};


/** Create a global instance that contians the querystring */
QueryString = new QueryString(window.location.href);

