//    Licensed Materials - Property of IBM
//
//    IBM Cognos Products: cogadmin
//
//    (C) Copyright IBM Corp. 2005, 2015
//
//    US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//
// Copyright (C) 2008 Cognos ULC, an IBM Company. All rights reserved.
// Cognos (R) is a trademark of Cognos ULC, (formerly Cognos Incorporated).

//----------------------------------------------------------
/*
 * namespace for cogadmin local javascript library.
 */

if (!window.CognosObjectFactory) {
	window.CognosObjectFactory = function() {
		throw 'RuntimeException: CognosObjectFactory is a static class and may not be instantiated';
	}
	CognosObjectFactory.init = function(objName) {
		var namespace = objName.split(".");
		var obj=window;
		for (var i=0; i < namespace.length;i++) {
			if (!obj[namespace[i]]) {
				obj = obj[namespace[i]] = {};
			} else {
				obj = obj[namespace[i]];
				if (typeof(obj) != "object") 
					throw new Error(objName
							+ " already exists and is not an object");
			}
		}
		return obj;
	}
}


//returns either val or the result of evaluating val
function evalParm(val) {
	var ret = window[val];
	return ret ? ret : val;
}

// table actions: expand/collapse, select row, ...
function toggleGroupVisibility(imgID, rowID) {
	var row = document.getElementById(rowID);
	if (!row) {
		return;
	}
	var sibling = getNextSibling(row);
	var collapsing = true;
	// get all the siblings until we hit the next group TR
	while (sibling.id == '') {
		if (sibling.style.display == '') {
			sibling.style.display = 'none';
			collapsing = false;
		} else {
			sibling.style.display = '';
		}
		
		sibling = getNextSibling(sibling);
		
		if (!sibling) {
			break;
		}
	}
	
	// change the image
	var image = document.getElementById(imgID);
	if (!image) {
		return;
	}

	if (collapsing)	{
		image.src = image.src.substring(0, image.src.indexOf('expand.gif'))
				+ 'collapse.gif';
	} else {
		image.src = image.src.substring(0, image.src.indexOf('collapse.gif'))
				+ 'expand.gif';
	}
}

//getNextSibling
// We need to do this to workaround a firefox issue since firefox treats
// linebreaks as nodes.
function getNextSibling(startNode){
  endNode=startNode.nextSibling;
  while(endNode.nodeType!=1){
    endNode = endNode.nextSibling;
  }
  return endNode;
}

// selectTableRow
// @rowPrefix: the ID prefix used to loop through all the selectable rows in the
// table
// @rowID: the ID for the row that will get selected
// @skipColumns: the number of columns that should get skipped when selecting a
// row
function selectTableRow(rowPrefix, rowID, skipColumns) {

	var row = document.getElementById(rowID);

	if (!row) {
		return;
	}
	
	// get the parent of the TR
	var parent = row.parentNode;
	
	if (!parent) {
		return;
	}

	// need to clear all the other selections and select only the one row
	for (rowIndex=0; rowIndex < parent.childNodes.length; rowIndex++) {
		var row = parent.childNodes[rowIndex];
		
		// we found a selectable row
		if (row.nodeName == 'TR' && row.id.indexOf(rowPrefix) == 0) {
			var skippedCols = 0;
			// loop through the TD's of the TR
			for (colIndex=0; colIndex < row.childNodes.length; colIndex++) {
				var col = row.childNodes[colIndex];
				
				if (col.nodeName == 'TD') {
					// is this the row that should be selected?
					if (row.id == rowID) {
						if (skippedCols >= skipColumns) {
							col.style.background = '#DEE7EF';
						} else {
							skippedCols++;
						}
					} else {
						// TODO; this doesn't work in firefox
						// TODO: fix alternating backgrouns
//						if (rowIndex%2) {
//						 col.style.background = '#f3f3f3';
//						}	
//						else {
							col.style.background = '#ffffff';
//						}					
					}
				}
			}
		}
	}	
}


// @fragID: The ID for the fragment that will get created
// @divID: The ID of the div that will get updated by the fragment
// @xtsTargetURL: parameters that will get added to the URL. Should NOT start
// with &
function createFragment(fragID, divID, xtsTargetURL) {
	var frag = new fragment("/xts"+encodeURI(xtsTargetURL), fragID, divID);
	if (frag.parent && !document.getElementById(divID)) {
		var div = document.createElement('div');
		div.id = divID;
		document.getElementById(frag.parent.div).appendChild(div);
	}
	return frag;
}

// @id; div id for the modal dialog content
function showModalDialog(style, id, title, height, width,fragment) {
	if (id) {
		var div = document.getElementById(id);
		if (div) {
			div.style.display="";
			if (!width) {
				width=xWidth(div);
			}
			if (!height) {
				height=xHeight(div);
			}
			var left = ((document.body.clientWidth - width) / 2);
			if (left < 0) {
				left = document.body.scrollLeft;
			}
			var top = ((document.body.clientHeight - height) / 2);
			if (top < 0) {
				top = document.body.scrollTop;
			}
			var uiDialog = new ui_dialog(id, title, style, left, top, width,
					height);
			if (fragment) {
				uiDialog.fragment = fragment;	
 			}
			
			uiDialog.setContent(div.innerHTML);
			div.parentNode.removeChild(div);
			uiDialog.show();
			return uiDialog;
		}
	}
}

// @id; div id for the modal dialog
// @iframeId: iframe id
function showModalDialogWithIFrame(id, height, width) {
	showModalDialogWithIFrame.triggerElement = document.activeElement;
	var div = $(id);
	if (div) {
		div.style.display = "";
		
		var locker = ui_locker.get();
		locker.show();
		
		if (height) {
			div.style.height = height + 'px';
		}
		if (width) {
			div.style.width = width + 'px';
		}
		
		var left = ((document.body.clientWidth - div.clientWidth) / 2)
				+ document.body.scrollLeft - 170;
		if (left < 0) {
			left = document.body.scrollLeft;
		}
		div.style.left = left + 'px';
		
		var top = ((document.body.clientHeight - div.clientHeight) / 2)
				+ document.body.scrollTop - 45;
		if (top < 0) {
			top = document.body.scrollTop;
		}
		div.style.top = top + 'px';
		div.style.visibility = 'visible';
		ui_setFocus(div);
	}
}

function hideModalDialog(id) {
	div = document.getElementById(id);
	if (div) {
		div.style.display = 'none';	
	}
	
	var locker = ui_locker.get();
	while (locker.count > 0){
		locker.hide();
		locker = ui_locker.get();
	}
	setTimeout(function(){var triggerEle=showModalDialogWithIFrame.triggerElement;if(triggerEle){triggerEle.focus()}},500);
}

// @event - the event that has taken place (mouseclick, mouseover, ...)
function cancelBubble(event) {
	event.cancelBubble = true;
	if (event.stopPropagation) {
		event.stopPropagation();
	}
}

//highlight row
function toggleHighlight(fragmentName, object, alternate){
	cleanWhitespace(fragmentName + "tbodyElement");
	var group = document.getElementById(fragmentName + "tbodyElement");
	
	if (group.hasChildNodes()) {
		var children = group.childNodes;
		
		for (var i = 0; children.length > i; i++)  {
			if (children[i].id != fragmentName + "footer") {
				if (alternate == true) {			
					if (i%2 == 0) {
						children[i].className = "cogstyle-table-row-alternate";
					} else {
						children[i].className = "cogstyle-table-row-default";
					}
				} else {
					children[i].className = "cogstyle-table-row-default";
				}
			}
		}
		
		object.className = "cogstyle-table-row-selected";
	}
}

function cleanWhitespace (element) {
	var element = document.getElementById(element);
	for (var i = 0; i < element.childNodes.length; i++) {
		var node = element.childNodes[i];
		if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) {
			node.parentNode.removeChild(node);
		}
	}
}

function toggleAllGroups(fragmentName) {
	var i=0;
	var toggle = null;
	var hasNext = true;
	while(hasNext) {
		var tg = new toggleGroup(fragmentName,i++,toggle);
		hasNext = tg.hasNext;
		toggle = tg.toggle;
	}
	
}

//expand/collapse group
function toggleGroup(fragmentName, group_number, toggle){
	var element = null;
	var display = false;
	var image=null;
	// get the next available group
	var next_available_group=0;
	for (var i=group_number; i < group_number+20; i++){
		image = document.getElementById(fragmentName + "group_image_" + i);
		if (image) {
			break;
		}
	}
	next_available_group = i;
	
	if (image && group_number==next_available_group) {
		if ((toggle == 'expand')
				|| (!toggle && image.src.indexOf("collapse.gif") >= 0)) {
			image.src = image.src.replace(/collapse/, "expand");
			display = false
			if (!toggle) {
				toggle = 'expand';
			}
		} else {

			image.src = image.src.replace(/expand/, "collapse");
			display = true;
			if (!toggle) {
				toggle = 'collapse';
			}
		}
		image.setAttribute("aria-expanded",toggle != 'expand')
		var summary = document.getElementById(fragmentName + "group_summary_"
				+ group_number);
		if (summary != null) {
			summary.style.display=display ? 'none' : '';
		}
		
		var i = 1;
		while (i == 1 || element) {
			element = document.getElementById(fragmentName + "group_"
					+ group_number + "_" + (i++));
			if (element) {
				element.style.display = display ? '' : 'none';
			} 
		}
	}
	
	this.hasNext =  image != null;
	this.toggle = toggle;
	
}

//selects all the input checkboxes from a form
function toggleCheckboxes(source_checkbox, parent_id) {
	var arrayCheckbox = getChildInputs(parent_id, 'checkbox');
	
	for (var i=0; i<arrayCheckbox.length; i++){
		var checkbox = arrayCheckbox[i];
			
		if (checkbox.id != '') {
			if (source_checkbox.checked == true) {
				checkbox.checked = true;
			} else {
				checkbox.checked = false;
			}
		}
	}
}

function getChildInputs (parent, typeName) {

	var inputs = document.getElementById(parent).getElementsByTagName('input');
	
	var matchingInputs = new Array();
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (typeName && input.type != typeName) {
			continue;
		}
		matchingInputs.push(input);
	}
	
	return matchingInputs;
}

// given a rowID, will hide/show all the rows with the same ID.
function toggleRows(rowID, visible) {
	var row = document.getElementById(rowID);
	if (row) {
		row.style.display = visible ? '' : 'none';
		
		while(row.nextSibling) {
			row = row.nextSibling;
			if (row.id == rowID) {
				row.style.display = visible ? '' : 'none';		
			}
		}
	}
}

// Creates a transient object to be added to an array and passed to the CPS
// function transientUpdateList
// Used when you have multiple transient updates to do and you don't want the
// fragment to refresh multiple times
function createTransient(name, value, scope, channel) {

	return {
	   "name": name,
	   "scope": scope,
	   "channel": channel,
	   "value": value
	}
}

function ParamsObject (params) {
	this.value = params;

	this.valueOf = function() {
		return this.value;
	}
	
	this.indexOf = function(value) {
		return this.value.indexOf(value);
	}
}

//from-to navigate the table
function navGo(frag, pagerName , sortParams, interactionParams) {
	var from = document.getElementById(pagerName + "_from");
	var to = document.getElementById(pagerName + "_to");	
	
	var fromloc = trim(from.value);
	var toloc = trim(to.value);

	if (fromloc != "") {
		checkPositiveIntegerDefault(from,"");
		fromloc = from.value;
		if ( fromloc == "" ) {
			alert(pager_validation_msg_array['IDS_PAGER_FROM_INVALID']);
			// alert( "The number in the first entry box is not valid; it must
			// be a number greater than 0.");
			return;
		} 

		if (toloc !="")  {
			checkPositiveIntegerDefault(to,"");
			toloc = to.value;
			if ( toloc == "" ) {
				alert(pager_validation_msg_array['IDS_PAGER_TO_INVALID']);
				// alert( "The number in the second entry box is not valid; it
				// must be a number greater than 0.");
				return;
			} 
			if ( Number(toloc) < Number(fromloc)) {
				alert(pager_validation_msg_array['IDS_PAGER_ENTRIES_INVALID']);
				// alert( "The number in the first entry box cannot be greater
				// than the number in the second entry box.");
				return;
			}
		}
	} else {
		if (toloc == "") {
			alert(pager_validation_msg_array['IDS_PAGER_ENTRIES_EMPTY']);
			// alert ("Specify the entry numbers to show and then click the Go
			// to button.");
			return;
		} else {
			checkPositiveIntegerDefault(to,"");
			toloc = to.value;
			if ( toloc == "" ) {
				alert(pager_validation_msg_array['IDS_PAGER_TO_INVALID']);
				// alert( "The number in the second entry box is not valid; it
				// must be a number greater than 0.");
				return;
			} 
		}					
	}
					
	var skipnum = Number(fromloc) -1;
	if (Number(skipnum) < 0) {
		skipnum=0;
	}
	
	var addtionParams = sortParams;
	if (interactionParams != '') {
		addtionParams  =	addtionParams + "&" + interactionParams;
	}
	
	var paramsObj = new ParamsObject(pagerName + "_skip=" + skipnum + "&"
			+ pagerName + "_from=" + fromloc + "&" + pagerName + "_to=" + toloc
			+ "&" + addtionParams);
	frag.retrieve(paramsObj);
}

function navOthers (frag,defaultOnClickParams,interactionParams){
	var params = defaultOnClickParams + "&" + interactionParams;
	var paramsObj = new ParamsObject(params);				
	frag.retrieve(paramsObj);
}

// sort the table 
function sortGo(frag, columnTitle, sortColumn, sortOrder, pageParams,
		interactionParams) {
	var isSortedOn = false;
	if (sortColumn != '' && sortColumn == columnTitle) {
		isSortedOn = true;
	}

	var order = "ascending";
	if (isSortedOn == true) {
		if (sortOrder == "descending") {
			order = '';
		} else {
			if (sortOrder == "ascending") {
				order = "descending";
			}
		}
	}
	var addtionParams = pageParams;
	if (interactionParams != '') {
		addtionParams  =	addtionParams + "&" + interactionParams;
	}
	
	var paramsObj = new ParamsObject("sort_column=" + columnTitle
			+ "&sort_order=" + order + "&" + addtionParams);
	frag.retrieve(paramsObj);
}

//return multi-dimensional array where each child element in the array
//is an array containing the checkbox number, id and value
function getCheckboxArray(table_name) {
	var checkboxes = new Array();
	var elements = document.getElementsByTagName("INPUT");
	var checkboxNumber = 0;
	
	for (var i=0; i<elements.length; i++) {
		if (elements[i].id != null){
			if (elements[i].id.indexOf(table_name + "_checkbox_") >= 0){
				if (elements[i].checked == true) {
					var checkboxArray = new Array();
					checkboxArray[0] = checkboxNumber;
					checkboxArray[1] = elements[i].id;
					checkboxArray[2] = elements[i].value;
					
					checkboxes[checkboxes.length++] = checkboxArray;
				}
				checkboxNumber++;
			}
		}
	}

	return checkboxes;
}

// returns a string with a key/value pair where the key is the id of the
// checkbox
function getCheckboxUrlParams(table_name) {
	return getCheckboxParams(table_name, false, null, true);
}

// returns a string with a key/value pair where the key name is checkbox_1,
// checkbox_2...
function getCheckboxCheckParams(table_name, valueFunc) {
	return getCheckboxParams(table_name, true, "checkbox", true, valueFunc);
}

//returns a string with a key/value pair (key=value)
function getCheckboxParams(table_name, use_parameter_name, parameter_name, use_parameter_index, valueFunc) {
	var array = getCheckboxArray(table_name);
	var params = "";
	var last = array.length - 1;
	for (var i=0; i<array.length; i++) {
		var checkboxArray = array[i];
		var checkboxName = checkboxArray[1];
		var checkboxValue = checkboxArray[2];
		var param;
		if (use_parameter_name) {
			param = parameter_name;
			if (use_parameter_index) {
				param +=  "_" + (i + 1);
			}
		} else {
			param = checkboxName;
		}
		// This line is to avoid double encode issue, in case of the value of
		// the checkbox has been urlencoded before.
		checkboxValue = decodeURIComponent(checkboxValue);
		params += param + "=" + encodeURIComponent(valueFunc ? valueFunc(checkboxValue) : checkboxValue);
		
		if (i < last) {
			params += "&"
	}
	}	
	
	return params;
}

function doAction(fragment, table_name, ifrmAction, confirm_msg){
	var checkboxes = getCheckboxCheckParams(table_name);
	actionImpl(fragment, checkboxes, ifrmAction, confirm_msg);
}
function actionImpl(fragment, checkboxes, ifrmAction, confirm_msg) {
	if (checkboxes.length == 0) {
		alert(action_no_selection_msg);	
		return;
	}
	
	if (!confirm_msg) {
		if (ifrmAction == 'enable') {
			confirm_msg = enable_schecule_confirm_msg;	
		} else if (ifrmAction == 'disable') {
			confirm_msg = disable_schecule_confirm_msg;	
		} else if (ifrmAction == 'delete') {
			confirm_msg = delete_confirm_msg;	
		} else if (ifrmAction == 'deleteDataset') {
			confirm_msg = delete_confirm_msg;	
		}
	}
	

	var params = checkboxes;
	if (ifrmAction != '') {
		params += "&ifrmcmd=" + ifrmAction;
	}

	if (confirm_msg) {
		if (confirm(confirm_msg)) {
			fragment.retrieve(params);
		}
	} else {
		fragment.retrieve(params);
	}
}	

function doDeleteCapability(fragment, table_name) {
	var checkboxes = getCheckboxCheckParams(table_name);
	deleteCapabilityImpl(fragment, checkboxes);
}
function deleteCapabilityImpl(fragment, checkboxes) {
	if (checkboxes.length == 0) {
		alert(action_no_selection_msg);
		return;
	}

	var confirm_msg = delete_capability_confirm_msg;

	var params = checkboxes;
	params += "&ifrmcmd=delete";

	if (confirm_msg != '') {
		if (confirm(confirm_msg)) {
			fragment.retrieve(params);
		}
	} else {
		fragment.retrieve(params);
	}
}

function doDeleteTenants(fragment, table_name) {
	var checkboxes = getCheckboxCheckParams(table_name);
	deleteTenantsImpl(fragment, checkboxes);
}
function deleteTenantsImpl(fragment, checkboxes) {
	if (checkboxes.length == 0) {
		alert(action_no_selection_msg);
		return;
	}

	var confirm_msg = delete_tenants_confirm_msg;

	var params = checkboxes;
	params += "&ifrmcmd=deleteTenants";

	if (confirm_msg != '') {
		if (confirm(confirm_msg)) {
			fragment.retrieve(params);
		}
	} else {
		fragment.retrieve(params);
	}
}

function getTenantProfileSearchPath(tenantID) {
	return "/configuration/account[@tenantID='" + encodeURIComponent(tenantID.replace(/'/g,"''")) + "']";
}

function doDeleteTenantUserProfile(fragment, table_name) {
	var checkboxes = getCheckboxCheckParams(table_name, getTenantProfileSearchPath);

	if (checkboxes.length == 0) {
		alert(action_no_selection_msg);
		return;
	}
	
	deleteTenantUserProfileImpl(fragment, checkboxes); 
}

function deleteTenantUserProfileImpl(fragment, checkboxes) {
	var confirm_msg = delete_tenantuserprofile_confirm_msg;
	if (confirm_msg != '') {
		if (confirm(confirm_msg)) {
			var params = checkboxes;
			params+="&ifrmcmd=delete";
			fragment.retrieve(params);
		}
	} else {
		fragment.retrieve();
	}
}

function doEditDefaultUserProfile(tenantId, tenantName, backURL) {
	var urlParams = "?b_action=xts.run";
	urlParams += "&m=portal/properties_general.xts";
	urlParams += "&m_class=account";
	urlParams += "&m_obj="+getTenantProfileSearchPath(tenantId);
	urlParams += "&m_tenantId="+encodeURIComponent(tenantId);
	urlParams += "&m_tenantName="+encodeURIComponent(tenantName);
	urlParams += "&backURL=";
	urlParams += backURL;
	ui_modal_dialog.open(urlParams, false, true, true);
}

function doExportTenants(table_name, mPath, backURL) {
	var checkboxes = getCheckboxParams(table_name, true, "selectedTenants", false);
	exportTenantsImpl(checkboxes, mPath, backURL);
}

function exportTenantsImpl(checkboxes, mPath, backURL) {
	var urlParams = "?b_action=xts.run";
	urlParams += "&m_path=";
	urlParams += mPath;
	urlParams += "&m=portal/new_general.xts";
	urlParams += "&from_tool=true";
	urlParams += "&m_class=exportDeployment";
	urlParams += "&m_setArchiveChanged=true";
	urlParams += "&m_archive";
	urlParams += "&m_setArchiveChanged=true";
	urlParams += "&m_new_class=exportDeployment";
	urlParams += "&m_deploymentWizardPage=tenants";
	urlParams += "&backURL=";
	urlParams += backURL;
	urlParams += "&m_entireContentStoreSelect=true";
	urlParams += "&m_last_value_entireContentStoreSelect=true";
	urlParams += "&m_last_value_personalDataSelect=true";
	urlParams += "&m_personalDataSelect";
	urlParams += "&m_exportMethod=selectTenants";
	urlParams += "&m_wizardOp=update-method";
	if (checkboxes) {
		urlParams += "&" + checkboxes;
	} 
	else
	{
		urlParams += "&tenants";
	}
	ui_modal_dialog.open(urlParams, false, true, true);
}

function doTerminateSessions(fragment, table_name) {
	var checkboxes = getCheckboxCheckParams(table_name);
	terminateSessionsImpl(fragment, checkboxes);
}

function terminateSessionsImpl(fragment, checkboxes) {
	if (checkboxes.length == 0) {
		alert(action_no_selection_msg);
		return;
	}

	var confirm_msg = terminate_sessions_confirm_msg;

	var params = checkboxes;
	params += "&ifrmcmd=terminateSessions";

	if (confirm_msg != '') {
		if (confirm(confirm_msg)) {
			fragment.retrieve(params);
		}
	} else {
		fragment.retrieve(params);
	}
}

function doEnableDisableObj(fragment, table_name, isDisable) {
	var checkboxes = getCheckboxArray(table_name);
	var tenantIds = new Array();
	for (var i = 0; i < checkboxes.length; i++) {
		tenantIds[tenantIds.length]=checkboxes[i][2];
	}
	enableDisableObjImpl(fragment, tenantIds, isDisable);
}

function enableDisableObjImpl(fragment, tenantIds, isDisable) {
	if (tenantIds.length == 0) {
		alert(action_no_selection_msg);
		return;
	}
	var params = "&ifrmcmd=save&m_p_disabled=" + isDisable + "&m_class=tenant&m_obj=/directory//tenant[";

	for (var i = 0; i < tenantIds.length; i++) {
		if (i > 0) {
			params+=" or ";
		}
		var tenantId = decodeURIComponent(tenantIds[i]);
		params+="@tenantID='" + encodeURIComponent(tenantId.replace(/'/g,"''")) + "'";
	}
	params+="]";
	fragment.retrieve(params);
}

function doCreateContentUtilizationInfo(table_name, mPath, backURL) {
	var checkboxes = getCheckboxParams(table_name, true, "selectedTenants", false);
	createContentUtilizationInfoImpl(checkboxes, mPath, backURL);
}

function createContentUtilizationInfoImpl(checkboxes, mPath, backURL) {
	var urlParams = "?b_action=xts.run";
	urlParams += "&m_path=";
	urlParams += mPath;
	urlParams += "&m=portal/new_general.xts";
	urlParams += "&from_tool=true";
	urlParams += "&m_class=contentTask";
	urlParams += "&m_new_class=contentTask";
	urlParams += "&backURL=";
	urlParams += backURL;
	urlParams += "&contentTaskType=createContentUtilizationInfo";
	if (checkboxes) {
		urlParams += "&" + checkboxes;
	} 
	ui_modal_dialog.open(urlParams, false, true, true);
}

function doActionCancelInteractive(fragment, tableName, arguments,
		isGroupAction) {
	var params = '';
	
	if (arguments) {
		params = arguments;
	}

	if (isGroupAction) {
		var checkedPramsArray = getCheckboxArray(tableName);

		if (checkedPramsArray.length == 0) {
			alert(action_no_selection_msg);
			return;
		}

		for (var i=0; i<checkedPramsArray.length; i++) {
			var checkboxArray = checkedPramsArray[i];
			var checkboxIdx = checkboxArray[0];				
			var entriesInfo = entriesArray[checkboxIdx];		
		
			if (params != '') {
				params += '&';
			}
			params += 'requestID_' + i + '=' + entriesInfo[0]
					+ '&dispatcherName_' + i + '='
					+ encodeURIComponent(entriesInfo[1]) + '&reportName_' + i
					+ '=' + encodeURIComponent(entriesInfo[2]);
		}
	}	

	fragment.retrieve(params);	
}
/*******************************************************************************
 *  COGADMIN SYSMGMT WRAPPER FOR FRAGMENT EVENTS 
 ******************************************************************************/
 
var EVTKEY_COGADMIN_PREFIX = "com.cognos.cogadmin.";
var EVTKEY_RELOAD = "reload";
var PAGELET_TOP_HEIGHT = 60;
var FRAGMENT_TOP_HEIGHT = 34;
var FRAGMENT_MIN_HEIGHT = 500;

function setContentTableHeight (frgId,windowState,number){
	var defaultPageletHeight = (xClientHeight() < FRAGMENT_MIN_HEIGHT) ? FRAGMENT_MIN_HEIGHT
			: xClientHeight() - PAGELET_TOP_HEIGHT;
	var frgFrameId = frgId + "frame";
	var frgContentTableId = frgId + "contentTable";
	var fragmentOtherHeight = xHeight(frgContentTableId) ? (xHeight(frgFrameId)
			- xHeight(frgContentTableId) + 2) : 85;
	var num = number || 1;
	
	switch (windowState){
		case "maximized":
			xHeight(frgContentTableId,defaultPageletHeight - fragmentOtherHeight);
			break;
			
		case "extended":
		xHeight(frgContentTableId, defaultPageletHeight - FRAGMENT_TOP_HEIGHT
				- fragmentOtherHeight);
			break;
		
		case "normal":
		default:
		xHeight(frgContentTableId, (defaultPageletHeight / num)
				- fragmentOtherHeight);
	}
}

var appOnLeaveHandlers = {};
function regAppOnLeaveEvent (id, handler, context){
	appOnLeaveHandlers[id] = {};
	appOnLeaveHandlers[id]["conext"] = context;
	appOnLeaveHandlers[id]["handler"] = handler;
	
	window.onbeforeunload = function(evt){
		for (o in appOnLeaveHandlers){
			appOnLeaveHandlers[o]["handler"].apply(
					appOnLeaveHandlers[o]["conext"], [ evt ]);
		}
	};
}

/*
 * This function is introduced to unload the regestered event when fragment is
 * unloaded.
 */
function regFragEvent (frag,evt,handler,capture){
	var cap = capture || false;
	
	if (typeof frag == "string")
		frag = $(frag);
	
	if (frag) {
		frag.addEventListener(evt,handler,cap);
		frag.addEventListener("fragment.unload", function() {
				frag.removeEventListener(evt,handler,cap);
		}, cap);
		return true;
	} else 
		return false;
		
}

function proxyCogadminEvent (frag,evtName,type,payload){
	var evt = new _F_Event.Event();
	evt.initEvent(evtName, type, payload, false, true);
	evt.eventPhase = evt.AT_TARGET;
	frag.proxyEvent(evt);
}

function addCogadminEventListener(fragment, key, listener) {
	fragment.addEventListener(EVTKEY_COGADMIN_PREFIX + key, listener);
}

function removeCogadminEventListener(fragment, key, listener) {
	fragment.removeEventListener(EVTKEY_COGADMIN_PREFIX + key, listener);
}

function raiseCogadminEvent(fragment, key, payload) {
	fragment.raiseEvent(EVTKEY_COGADMIN_PREFIX + key, payload);
}

function addReloadEventListener(fragment, listener) {
	addCogadminEventListener(fragment,EVTKEY_RELOAD, listener);
}

function removeReloadEventListener(fragment, listener) {
	removeCogadminEventListener(fragment,EVTKEY_RELOAD, listener);
}

function raiseReloadEvent(fragment, payload, skipFocus) {
	if (!skipFocus) {
        fragment.afterRetrieve = function(evt) {
			fragment.removeEventListener("fragment.retrieve.after", fragment.afterRetrieve);
			ui_setFocus(fragment.div);
        }
        
        fragment.addEventListener("fragment.retrieve.after", fragment.afterRetrieve);
	} 
	raiseCogadminEvent(fragment, EVTKEY_RELOAD, payload);
}

/*
 * This function is used for those popup sub fragment only, to prevent the
 * following events (title_change/mode_change/windowstate_change/refresh) from
 * propergation. (This kind of propergation is something we don't want to see.)
 * 
 */
 //TODO: It's better to use popup dialog instead of popup fragment.
function stopDefaultPropagation (fragment) {
	var frag = $(fragment);
	
	frag.addEventListener("fragment.title.change", stopPropagation);
	frag.addEventListener("fragment.mode.change", stopPropagation);
	frag.addEventListener("fragment.windowstate.change", stopPropagation);
	frag.addEventListener("fragment.refresh.change", stopPropagation);
	
	function stopPropagation (evt) {
		evt.stopPropagation();
	}
}

/*******************************************************************************
 * END COGADMIN-SYSMGMT WRAPPER FOR FRAGMENT EVENTS     
 ******************************************************************************/
function includeClass(elt,cName) {
	var elt = xGetElementById(elt);
	if (elt && elt.className){
		var reg = new RegExp("(^|\\s)"+cName+"(\\s|$)");
		return reg.test(elt.className);
	} else {
		return false;
	}
}

// change the styles for a button during a mouseover
function mouseoverImage(item) {
	if (includeClass(item,'cogstyle-toolbar-imageNormal')) {
		item.className = 'cogstyle-toolbar-imageOver';
	}
	if (includeClass(item,'cogstyle-toolbar-imagePressed')) {
		item.className = 'cogstyle-toolbar-imageOverPressed';
	}
}
// change the styles for a button during a mouseout
function mouseoutImage(item) {
	if (includeClass(item,'cogstyle-toolbar-imageOver')) {
		item.className = 'cogstyle-toolbar-imageNormal';
	}
	if (includeClass(item,'cogstyle-toolbar-imageOverPressed')) {
		item.className = 'cogstyle-toolbar-imagePressed';
	}
}

function switchImageState(itemID_Release, item_Press) {	
	var item_Release = document.getElementById(itemID_Release);

	if (item_Release != null) {
		item_Release.className = 'cogstyle-toolbar-imageNormal';					
	}
	if (item_Press != null) {
		item_Press.className = 'cogstyle-toolbar-imagePressed';					
	}
}

// Walk the tree to see if we can find style.display == 'none'
function isHidden(obj) {
	if (obj.style && obj.style.display == 'none') {
		return true;
	} else if (obj.parentNode) {
		return isHidden(obj.parentNode);
	}
	
	return false;
}

// set the target height relative to the first parent that has height defined >
// minHeight. Otherwise, use minHeight
function setRelativeHeight(targetId, fragment, minHeight, offset) {
	var parent = fragment.parent;
	var iHeight = minHeight;
 	while (parent) {
		if (parent.div) {
			var _height = parseInt($(parent.div).style.height);
			if (_height) {
				if (offset) {
					_height = (_height * offset.percentage) + offset.pixels;
				}
				if (_height > minHeight) {
					iHeight = _height;
				}
				break;
			}
		} 
		parent = parent.parent;
	}
	var target = $(targetId);
	if (target) {
		$(targetId).style.height = iHeight + "px";
	}
}

function floatMath (operand1,operand2,operator) {
	var f1 = getFixedDecimal(operand1);
	var f2 = getFixedDecimal(operand2);
	var fixedDecimal = ((f1 - f2)>0) ? f1 : f2;
	var result;
	
	switch (operator) {
		case '-':
			result = operand1 - operand2;
			break;
		case '*':
			result = operand1 * operand2;
			fixedDecimal = f1 + f2;
			break;
		default:
			result = operand1 + operand2;
	}
	
	return result.toFixed(fixedDecimal);
	
	function getFixedDecimal (number) {
		var pre = number.toString().indexOf(".");
		if (pre == -1)
			return 0;
		else
			return fixedDecimal = number.toString().length - 1 - pre;
	}
}

function getExpandedTableGroups(table) {
	var expandedGroupKeys = new Array();
	var trs = table.getElementsByTagName('tr');
	for (var tr in trs) {
		var row = trs[tr];
		if (includeClass(row,"cogstyle-table-group")) {
			var img = row.getElementsByTagName("img")[0]; // the
															// expand/collapse
															// icon
			if (img.src.indexOf("collapse") >=0) { //the group is expanded
				expandedGroupKeys[expandedGroupKeys.length] = row
						.getAttribute("key");
			}
		}
	}
	return expandedGroupKeys;
}

function generateQueryString(currentString, newName, newValue, ignoreEmptyValues) {
	if (!currentString) {
		currentString="";
	}
	if (newName) {
		if (ignoreEmptyValues && (!newValue || newValue.length == 0)) {
			return currentString;
		}
		if (currentString.length > 0) {
			currentString+="&";
		}
		return currentString+newName+"="+newValue;
	}
	return currentString;
}

function importUserInterfaceProfiles(parentFrag, msg) {
	if (confirm(msg)) {
		var fragUrl='/cogadmin/controls/importUserInterfaceProfiles.xts';
		var frag = createFragment(parentFrag.id+'importUIProfiles', parentFrag.id+'importUIProfiles_div', fragUrl);
		frag.retrieve();
	}

}