/*
 * Copyright 2010 Thomson Reuters Global Resources. All Rights Reserved.
 * Proprietary and confidential information of TRGR.
 * Disclosure, use, or reproduction without the written authorization of TRGR is prohibited.
 */

/**
 * Method to add the parameters included in the URL in each link in the document not to lose
 * the values.
 */
function addParameters2Links() {
	var ie = document.all;
	var originQS = "";
	if (ie) {
		originQS = location.search;
	} else {
		originQS = document.location.href;
	}
	if(originQS.indexOf("externalDisplayDocument") != -1){
		originQS = originQS.substring(originQS.indexOf("?") + 1);
		// Process links in the document.
		var links = document.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++) {
			var href = links[i].href;
			if (href.indexOf("/wles/app") != -1) {
				var action = href.substring(0, href.indexOf("?"));
				var destinationQS = href.substring(href.indexOf("?") + 1);
				destinationQS = mergeParameters(destinationQS, originQS);
				links[i].href = action + "?" + destinationQS;
			}
		}
		// Process iframes in the document.
		var iframes = document.getElementsByTagName("iframe");
		for (var i = 0; i < iframes.length; i++) {
			var src = iframes[i].src;
			if (src.indexOf("/wles/app") != -1) {
				var action = src.substring(0, src.indexOf("?"));
				var destinationQS = src.substring(src.indexOf("?") + 1);
				destinationQS = mergeParameters(destinationQS, originQS);
				iframes[i].src = action + "?" + destinationQS;
			}
		}
	}
}

/**
 * Method to merge two sets of pairs name-value.
 * 
 * @param destinationQS Query string in which all the parameters will end.
 * @param originQS Query string that contains all parameters.
 * 
 * @return The complete query string. 
 */
 function mergeParameters(destinationQS, originQS) {
	if (destinationQS == "") {
		return originQS;
	}
	if (originQS == "") {
		return destinationQS;
	}
	var qs1 = processQS(destinationQS);
	var qs2 = processQS(originQS);
	var ret = destinationQS;
	for (var i = 0; i < qs2.length; i++) {
		var parameterAlreadyPresent = false;
		for (var j = 0; ((j < qs1.length) && (!parameterAlreadyPresent)); j++) {
			// If parameter name is not in the original query string, add it.
			if ((qs2[i][0] == qs1[j][0]) && (qs2[i][0] != undefined)) {
				parameterAlreadyPresent = true;
			}
		}
		if (!parameterAlreadyPresent) {
			ret = ret + "&" + qs2[i][0] + "=" + qs2[i][1];
		}
	}
	return ret;
}

/**
 * Method to split a query string into an array of arrays of name/value.
 * @param Query string to process.
 * 
 * @return An array containing in each position "new Array(name, value)".
 */
function processQS(qs) {
	var arr1 = qs.split("&");
	var ret = new Array(arr1.length);
	for (var i = 0; i < arr1.length; i++) { 
		ret[i] = arr1[i].split("=");
	}
	return ret;
}

