/* querystringHelper.js >> configurable values for all other namespaces and classes
 */
(function(){
	/*
		Forward and decode querystring.
	*/
	window.location.forwardQueryString = function(){
		var collection = {};
		// Gets the query string, starts with '?'
		var querystring = window.location.search;

		// Empty if no query string
		if (!querystring) {
			return { toString: function() { return ""; } };
		}

		// Decode query string and remove '?'
		querystring = decodeURI(querystring.substring(1));
		return '?' + querystring;	
	};

	/* 
		Parsing query parameters and return in a collection 
	*/
	window.location.querystring = function(){
		var collection = {};
		// Gets the query string, starts with '?'
		var querystring = window.location.search;
		// Empty if no query string
		if (!querystring) {
			return { toString: function() { return ""; } };
		}

		// Decode query string and remove '?'
		querystring = decodeURI(querystring.substring(1));

		// Load the key/values of the return collection
		var pairs = querystring.split("&");
		for (var i = 0; i < pairs.length; i++) {
			// Empty pair (e.g. ?key=val&&key2=val2)
			if (!pairs[i]) {
				continue;
			}

			// Don't use split("=") in case value has "=" in it
			var seperatorPosition = pairs[i].indexOf("=");
			if (seperatorPosition == -1) {
				collection[pairs[i]] = "";
			}
			else {
				collection[pairs[i].substring(0, seperatorPosition)] 
					= pairs[i].substr(seperatorPosition + 1);
			}
		}

		// toString() returns the key/value pairs concatenated
		collection.toString = function() {
			return "?" + querystring;
		};
	};
	
	CleanURL = function(url){
		var str = url.split("?");
		var returnVal = "";
		
		if(str){
			if(str[0]){
				returnVal = str[0] 	
			
				if(str[1]){
					returnVal = returnVal + '?' + str[1]
					for (var i = 2; i < str.length; i++) {
						// Empty pair (e.g. ?key=val??key2=val2)
						if (!str[i]) {
							continue;
						}
						returnVal += '&' + str[i];
					}
				}
			}
		}
		
		return returnVal;
	
	}

	forwardURL = function(str) {
			
		str = str + window.location.forwardQueryString();
		str = CleanURL(str);		
		window.location.href = str ;
	};
		
	forwardURLNoHistory = function(str) {
	
		str = str + window.location.forwardQueryString();
		str = CleanURL(str);		
		window.location.replace(str);
	};
	
})();
