/*
 * Copyright 2009 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("target") != -1){
	
		originQS = originQS.substring(originQS.indexOf("?") + 1);
		// Process iframes in the document.
		/*
		comentar a Virginia, hay menos riesgo si el action del frame se pinta como hasta ahora para entrada normal a wles y sólo si llega 
		parámetro target de alertas, se vuelve cambia el action añadiendo los parámetros de las alertas (se llama dos veces al main action, 
		en el caso de las alertas, pero la entrada estandar a wles no cambia)
		*/
		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;
}
