/*
ICUS_parseQuery.js - Query string handling for ICUS
(C) ICUS Pte Ltd all rights reserved - please read the copyright notice and disclaimer on ICUS_standardCMI.js

* 02 Nov. 2004 - Timothee Groleau
    - Refactored into 2 functions ICUS_getQuery & ICUS_parseQuery
    - Allow valueless variables

* 31 Dec. 2001 - Timothee Groleau
    - Creation
*/

/*
ICUS_getQuery
Description:
	* Extract a query string from either a string, a document object or
	  a location object
Parameters:
	* url: may be either a string, a document object or a location object
	    defaults to document.location.href if no parameter is passed
Outputs: 
	A string representing the query string, without the '?'
Usages:
	* q = ICUS_getQuery("doc.htm?var1=value1&var2=value2&var3=value3");
	* q = ICUS_getQuery(document);
	* q = ICUS_getQuery(parent);
*/
function ICUS_getQuery(url) {
	var pos = -1;

	if (typeof(url) == "undefined") {
		url = document.location.href;
	
	} else if (typeof(url) == "object") {
		if (typeof(url.location) == "object") {
			url = url.location;
		}
		if (typeof(url.href) == "string") {
			url = url.href;
		}
		if (typeof(url) == "object") {
			return "";
		}
	}
	
	if ((pos = url.indexOf("?")) == -1) {
		return "";
	} else {
		return url.substring(pos+1);
	}
}


/*
ICUS_parseQuery
Description:
	* Parses a query string into a usable javascript object representing the pairs
	  var=value.
	* Valueless items in the query string will be created as a new properties with
	  an empty string for a value.
	* Multi-valued variables are not supported. Should such case arise, only the
	  last pair for that variable will be considered.
Parameters:
	* query: a url encoded query string ('var=value' pairs delimited by '&') 
	      query should not contain a starting '?' or it will be considered part
	      of the first variable's name
Outputs: 
	A javascript object whose properties are the query's variables' names, 
	converted to lower case, and the values of these properties are the values
	from the var=value pairs.
Usage:
	props = ICUS_parseQuery("var1=value1&var2=value2&var3=value3");
*/
function ICUS_parseQuery(query) {
	var params = {};
	
	if (typeof(query) == "undefined" || query == "") return params;
	
	var pos = -1;
	var pairs = query.split("&");
	
	for (var i in pairs) {
		if ((pos = pairs[i].indexOf("=")) == -1) {
			params[unescape(pairs[i]).toLowerCase()] = "";
		} else {
			params[unescape(pairs[i].substring(0, pos)).toLowerCase()] = unescape(pairs[i].substring(pos+1));
		}
	}
	
	return params;
}


