/********  Function Retrieving items or Set item values  *************/
//+----- Get dll path from config -----
var gsDLLPath=getDLLPath();
var gnHintLimit=123;// truncate the display value if it exceeds limit
var gbIE5=IsIE5();
var gbIEVersion = GetIEVersion();

function IsIE5(){
	var gbIE5=false;
	var userAgent=navigator.userAgent;
	var MSIEIndex=userAgent.indexOf("MSIE");
	if (userAgent.indexOf("Win") != -1 && userAgent.indexOf("MSIE") != -1 && userAgent.substring((MSIEIndex+5),(MSIEIndex+6)) > 4)
		gbIE5=true;
	return gbIE5;
}

function GetIEVersion(){
    var userAgent=navigator.userAgent;
	var MSIEIndex=userAgent.indexOf("MSIE");
	if (userAgent.indexOf("Win") != -1 && userAgent.indexOf("MSIE") != -1)
	    return userAgent.substring((MSIEIndex+5),(MSIEIndex+6));
	else 
	    return -1;
}

function GetClientHeight(){
    return (gbIEVersion<7)?document.body.clientHeight:document.documentElement.clientHeight; 
}

function GetClientWidth(){
    return (gbIEVersion<7)?document.body.clientWidth:document.documentElement.clientWidth; 
}

function truncateStr(sV, nLimit){return sV;
	if (sV.length > nLimit) return sV.substr(0,nLimit)+" ...";
	else return sV;
}

function getDLLPath(){
    return "exec/httpsrvr.dll";
    /*
    // Load configuration from xml file 
	var configXML = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
	configXML.async = false;
	configXML.validateOnParse = false;
	configXML.load('../../config.net.xml');	
	if(configXML==null){
		configXML.load('config.net.xml');	
	}
	if(configXML.parseError.errorCode == 0){
		var oDllPath=configXML.selectSingleNode("//variables/variable[@name='dll']/@value");
		return oDllPath.nodeValue;	
	}else 
		return '';
    */
}
	
//+------------------------------------
// getItem - get an element by id
// Arguments:	id
// Returns:		object with the id
//+------------------------------------
function getItem(id){
	return(document.getElementById(id));
}

//+------------------------------------
// getItems - get elements by id
// Arguments:	id
// Returns:		objects with the id
//+------------------------------------
function getItems(id){
	return(document.getElementsByName(id));
}

//+------------------------------------
// getItemValue - get value by id
// Arguments:	id
// Returns:		Return the value of the object if exists,
//				otherwise return null.
//+------------------------------------
function getItemValue(id){
	var o=getItem(id);
	if(o != null) return(o.value);
	else return(null);
}

//+------------------------------------
// setItemValue - set value by id
// Arguments:	id
// Returns:		Set value of the object if exists,
//				otherwise do nothing.
//+------------------------------------
function setItemValue(id,sV){
	var o=getItem(id);
	if(o != null) o.value=sV;
}

function getValueIdFromDispId(id){
	return(id.substr(1,id.length));
}

function getDispIdFromValueId(id){
	return("_"+id);
}

//to see if a check box or radio button checked.
function isChecked(id, sV){
	if(typeof(sV) !='undefined'){
		var o=getItems(id);
		for(var i=0; i<o.length; i++){
			if(o[i].value == sV)return o[i].checked;
		}
	}else{
		var o=getItem(id);
		return(o.checked);
	}
}
function checkIt(id, sV, bCheck){
	if(typeof(sV) !='undefined'){
		var o=getItems(id);
		for(var i=0; i<o.length; i++){
			if(o[i].value == sV)o[i].checked = bCheck;
		}
	}else{
		var o=getItem(id);
		o.checked=bCheck;
	}
}

function focusOnIt(id){
	var o=getItem(id);
	try{
	    //elementOnFocus(o);
	    o.focus();	    
	}catch(e){}
}
//+----------------------------------------------------------------------------------------
//  Function:       enable
//  Description:    Enables or disable a form control.  If disable, uncheck/de-select it. 
//  Arguments:      id			- control id
//					value - if only need to enable/disable the one which has this value.
//-----------------------------------------------------------------------------
function enable(id, bDisabled, value){
	var o=getItems(id);
	if(typeof(value) == 'undefined'){
		for(var i=0; i<o.length; i++){ 
			o[i].disabled=bDisabled;
			if(o[i].checked && bDisabled)o[i].checked=false;
		}
	}else{
		for(var i=0; i<o.length; i++){
			if(o[i].value==value){ 
				o[i].disabled=bDisabled;
				if(o[i].checked && bDisabled)o[i].checked=false;
				return;
			}
		}
	}
}

//+------------------------------------
// isNotEmpty
//	function: - 
//+------------------------------------
function isNotEmpty(sV){
	return(typeof(sV) != 'undefined' && sV != '');
}

function newWindow(URL,name,menubar,resizable, scrollbars, x,y){
	var sPath = getAbsPath();
	if(sPath!=''){
		if(URL.indexOf(DIR)!=-1){
			sPath=sPath.substring(0,sPath.indexOf(gsDLLPath));
			if(URL.indexOf(DIR)!=-1)URL=URL.replace(DIR,'');
		}
		URL=sPath+URL;
	}
	window.open(URL,name,"toolbar=0,location=0,directories=0,status=0,menubar="+menubar+",scrollbars="+scrollbars+",resizable="+resizable+",WIDTH="+x+",HEIGHT="+y);
	//o.focus();
}

function childWindow(URL,name,menubar,resizable, scrollbars, x,y){
	return(window.open(URL,name,"toolbar=0,location=0,directories=0,status=1,menubar="+menubar+",scrollbars="+scrollbars+",resizable="+resizable+",WIDTH="+x+",HEIGHT="+y));
}

function closeWindow(){
	window.close();
}

//focus on parent window after Lookup New update.
function focusParentWin(){
	window.close();window.opener.focus();
}

/*************************** Functions handling show/hide/toggle items  ***********************/
//show items
function show(id){
	var o=getItems(id);
	for(var i=0; i<o.length; i++){
		if(o[i].style.display!=''){
		    o[i].style.display="";
		}
	}
}

//hide items
function hide(id){
	var o=getItems(id);
	for(var i=0; i<o.length; i++){ 
		if(o[i].style.display!='none')o[i].style.display="none";
	}
}

//toggle items
//action is a script that has to be executed when it's shown - used by GUI Wizard
function toggle(id, action){
	var o=getItems(id);
	for(var i=0; i<o.length; i++){		
		if (o[i].style.display=="") o[i].style.display="none";	
		else{
			o[i].style.display="";
			if(action!='')eval(action);
		}
	}
}

//show one item
function show1(id){
	var o=getItem(id);
	if(o!=null){
	    o.style.display="";
	}
}

//hide one item
function hide1(id){
	var o=getItem(id);
	if(o!=null)o.style.display="none";
}

//toggle one item
function toggle1(id){
	var o=getItem(id);
	if(o!=null){
		if (o.style.display=="") o.style.display="none";
		else o.style.display="";
	}
}

//+----------------------------------------------------------------------------
//  Function:       toggleWithImg
//  Description:    Expanding/colapsing and toggle plus/minus signs for grouping.
//					It is also use by edit mode to hide/show security fields.
//  Arguments:      divId - div id for grouping
//-----------------------------------------------------------------------------
function toggleWithImg(divId){	
	var img=getItems("img_"+divId);
	var a=getItems("a_"+divId);
	for(var k=0; k<img.length; k++){
		if(img[k].src.indexOf("plus.gif") != -1){
			img[k].src=img[k].src.replace("plus.gif","minus.gif");
			//img[k].alt="Click to hide";	
			var alt=img[k].alt;
			img[k].alt=alt.replace("show", "hide");		
			if(a!=null){a[k].title=img[k].alt;}				
			show(divId);	
		}else{
			img[k].src=img[k].src.replace("minus.gif", "plus.gif");
			//img[k].alt="Click to show";
			var alt=img[k].alt;
			img[k].alt=alt.replace("hide", "show");
			if(a!=null)a[k].title=img[k].alt;
			hide(divId);
		}
	}
}
function showWithImg(divId){	
	var img=getItems("img_"+divId);
	var a=getItems("a_"+divId);
	for(var k=0; k<img.length; k++){	
		img[k].src=img[k].src.replace("plus.gif","minus.gif");
		var alt=img[k].alt;
		img[k].alt=alt.replace("show","hide");	
		if(a!=null)a[k].title=img[k].alt;		
		show(divId);		
	}
}
function hideWithImg(divId){	
	var img=getItems("img_"+divId);
	var a=getItems("a_"+divId);
	for(var k=0; k<img.length; k++){
		img[k].src=img[k].src.replace("minus.gif", "plus.gif");
		var alt=img[k].alt;
		img[k].alt=alt.replace("hide","show");
		if(a!=null)a[k].title=img[k].alt;
		hide(divId);
	}
}

/********************  Functions displaying errors ******************/
//+------------------------------------
// showParseError
//	function: 
//+------------------------------------
function showParseError(o, file, bPrompt) {
    if(typeof(bPrompt)=='undefined') bPrompt=true;	
        if (o.parseError.errorCode != 0) {
  	        var s='Invalid XML file: '+ file +'!\n'
              +'File URL: '+o.parseError.url+'\n'
              +'Line No.: '+o.parseError.line+'\n'
              +'Character: '+o.parseError.linepos+'\n'
              +'File Position: '+o.parseError.filepos+'\n'
              +'Error Code: '+o.parseError.errorCode+'\n'
              +'Description: '+o.parseError.reason+'\n' 
              +'Source Text: '+o.parseError.srcText;       
            if(bPrompt) alert(s);
  	        return true;
        }else return false;  
}

//+------------------------------------
// showError
//	function: 
//+------------------------------------
function showError(file, Msg) {	
  	var s='Error in function - '+ file +'!\n\r'
      +'Description: '+Msg;
  	alert(s);	  
}

//encode params for multipost
function URLEncodeForPost(sV){
	//%, &, +, carriage return, line feed, tab
	return sV.replace(/%/g, "%25").replace(/&/g, "%26").replace(/\r/g, "%0D").replace(/\n/g,"%0A").replace(/\t/g, "%09").replace(/\+/g,"%2B");
}

//+------------------------------------
// URLEncode
//	function:	encode url for posting
//	Arguments:	s - string which needs to be URL encoded
//				sEncode - the character that needs to be URL encoded.
//				if sEncode is missing, it URL encodes:
//				% | & | carriage return | line feed | tab
//	Returns: s - URL encoded string
//+------------------------------------
function URLEncode(s, sEncode){
	switch(sEncode){
		case "'":
			s=s.replace(/'/g, "%27"); 
			break;
		case '"':		
			s=s.replace(/"/g, "%22"); 	
			break;
		case '&':		
			s=s.replace(/&/g, "%26"); 	
			break;
		case '%':		
			s=s.replace(/%/g, "%25"); 	
			break;
		default:
			s=s.replace(/%/g, "%25").replace(/&/g, "%26").replace(/"/g, "%22").replace(/'/g, "%27").replace(/\r/g, "%0D").replace(/\n/g,"%0A").replace(/\t/g, "%09").replace(/\+/g,"%2B").replace(/=/g,"%3D").replace(/#/g,"%23");						
			break;
	}
	return s;
}

function URLDecode(s){
	return s.replace(/%25/g, "%").replace(/%26/g, "&").replace(/%22/g, '"').replace(/%27/g, "'").replace(/%0D/g, "\r").replace(/%0A/g,"\n").replace(/%09/g, "\t").replace(/%2B/g,"+").replace(/%3D/g,"=").replace(/%23/g,"#").replace(/%3A/g,":");									

}

//+------------------------------------
// HTMLEncode
//	function:	HTML encode input string
//	Arguments:	s - string which needs to be HTML encoded
//				sEncode - the character that needs to be HTML encoded.
//				if sEncode is missing, it HTML encodes:
//				
//	Returns: s - HTML encoded string
//+------------------------------------
function HTMLEncode(s, sEncode){
	switch(sEncode){
		case "'"://single quote
			s=s.replace(/'/g, "&apos;"); 
			break;			
		case '"'://double quotes
			s=s.replace(/"/g, "&quot;")
			break;	
		case '&'://ampersands
			s=s.replace(/&/g, "&amp;");
			break;	
		case '<'://less than
			s=s.replace(/</g, "&lt;");
			break;	
		case '>'://greater than
			s=s.replace(/>/g, "&gt;");
			break;	
		case ' '://space
			s=s.replace(/ /g, "+");
			break;	
		default:
			s=s.replace(/'/g, "&apos;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&/g, "&amp;");				
			break;	
	}
	return s;
}
function HTMLDecode(s, sEncode){ 
	switch(sEncode){
		case "&apos;"://single quote
			s=s.replace(/&apos;/g, "'");
			break;	
		case "&quot;"://double quotes
			s=s.replace(/&quot;/g, '"');
			break;	
		case "&amp;"://ampersand
			s=s.replace(/&amp;/g, "&");
			break;	
		case "&lt;"://ampersand
			s=s.replace(/&lt;/g, "<");
			break;	
		case "&gt;"://ampersand
			s=s.replace(/&gt;/g, ">");
			break;	
		default:
			s=s.replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");				
			break;			
	}
	return s;
}

//add a javascript escape - \
function escape(s,sEscape){
	if(s.indexOf(sEscape)!=-1){
		var a=s.split(sEscape);
		s=a.join("\\"+sEscape);
	}
	return s;
}
//+------------------------------------
// XMLEncode
//+------------------------------------
function XMLEncode(s){
	s=s.replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&/g, "&amp;");				
	return s;
}
/***************  Microsoft User Store functions ******************/
function isUSerStoreCorrupted(sn){
	try{
		var o=getItem(sn);	
		o.load(sn);
		return false;
	}catch(e){ 
	    var o=getItem(sn);	
	    o.save(sn); //reset
		alert("You probably have a corrupted user data.  The data is reset.");
		return false;
	}
}

function isPost(sURL){
	if(sURL.indexOf("?")==-1)return true;
	else false;
}

//+--------------------------------------------------------------
//  Function:       setUserStoreData
//  Description:    Saves user data to microsot user store.
//  Arguments:      sn - microsoft user store name
//                  pn - param name
//                  pv - param value
//  Returns:        none
//---------------------------------------------------------------
function setUserStoreData(sn, pn, pv){
	if(pn.charAt(0)=='0')return;
	var o=getItem(sn); //get store
	//alert(o.XMLdocument.xml);
	try{ o.load(sn); o.setAttribute(pn,pv); o.save(sn); return true;
	}catch(e){
		//showError("setUserStoreData()", e.description);
	}
}

//+--------------------------------------------------------------
//  Function:       getUserStoreData
//  Description:    Retrives a value from miscrosot user data store.
//  Arguments:      sn - microsoft user store name
//                  pn - param name which you need get the value
//  Returns:        param value if exists, null if not.
//---------------------------------------------------------------
function getUserStoreData(sn, pn){

	if(pn.charAt(0)=='0')return;//this is for NB=0
	try{
		var o=getItem(sn);	
		if(o != null){o.load(sn);return(o.getAttribute(pn));}
		else return '';
	}catch(e){ 
		//showError("getUserStoreData()", e.description);
	}
}

//+----------------------------------------------------------------------------
//  Function:       deleteUserStoreData
//  Description:    Deletes a value from microsoft user data store and update the store.
//  Arguments:      sn - microsoft user store name
//                  pn - param name which you need delete
//  Returns:        none
//-----------------------------------------------------------------------------
function deleteUserStoreData(sn, pn){
	if(pn.charAt(0)=='0')return;
	try{
		var o=getItem(sn);	
		o.load(sn); o.removeAttribute(pn); o.save(sn);
	}catch(e){ 
		showError("deleteUserStoreData()", e.description); 
	}
}

function resetCustomization(sn, sNB, sType){
	var o=getItem(sn);  o.load(sn); 		
	switch(sType){
		case "search":
			o.removeAttribute(sNB+"SHTYP");
			o.removeAttribute(sNB+"CNT");
			o.removeAttribute(sNB+"ListColumns");
			o.removeAttribute(sNB+"DisplayStyle");
			if(sNB!=''){
				o.removeAttribute(sNB+"GD");
				for(var i=0; i<gaGridList.length; i++){					
					o.removeAttribute(sNB+"SFTYP"+i);
					o.removeAttribute(sNB+"SCNT"+i);
				}
			}else{
				o.removeAttribute("SFTYP");
				o.removeAttribute("SFCNT");
			}
			break;
		case "detail":
			o.removeAttribute(sNB+"DHTYP");
			if(sNB!=''){
				o.removeAttribute(sNB+"GD");
				for(var i=0; i<gaGridList.length; i++){					
					o.removeAttribute(sNB+"DFTYP"+i);
					o.removeAttribute(sNB+"DCNT"+i);
				}
			}else{
				o.removeAttribute("DFTYP");
				o.removeAttribute("DFCNT");
			}
			break;
		case "query":
			o.removeAttribute(sNB+"QHTYP");
			o.removeAttribute(sNB+"QFTYP");	
			break;
	}
	o.save(sn);
}

//+----------------------------------------------------------------------------
//  Function:       resetStore
//  Description:    Deletes all entries of microsoft user data store.
//  Arguments:      sn - microsoft user store name
//                  dn - the div id (with user store class) which we use to load the store.
//								(It can be same as store name or different. 
//								- Our table layout store name is different from its div id)
//  Returns:        none
//-----------------------------------------------------------------------------
function resetStore(dn, sn){
	try{
		var o=getItem(dn);  o.load(sn); 
  		var dom=o.XMLDocument.childNodes[0];
  		//remove all child nodes
  		var nCnt=dom.childNodes.length;
		for (var i=0; i<nCnt; i++) dom.removeChild(dom.childNodes[0]);
 		//remove all atrribute nodes
  		nCnt=dom.attributes.length;
  		for (var i=0; i<nCnt; i++) o.removeAttribute(dom.attributes[0].nodeName);
		o.save(sn);
	}catch(e){showError("resetStore()", e.description);}
}

//+----------------------------------------------------------------------------
//  Function:       getSessionData
//  Description:    Gets value from user session store. Session store keeps 
//					parameters used across notebooks and servers. E.g. last used: 
//					HTYP (Header type - table | view | list)
//					FTYP (Footer type - table | view | list)
//					CNT  (Header records per page - 5 | 10 | ...)
//					FCNT (Footer records per page - 5 | 10 | ...)
//					QHTYP (Advanced searching header type - detail | table)
//					QFTYP (Advanced searching footer type - detail | table)
//
//					Here is a sample of Session store data:
//					<ROOTSTUB HTYP="table" CNT="20"/>
//  Arguments:      sn - microsoft user store name
//                  pn - param name which you need get the value
//					pv - default value for paramName.
//  Returns:        param value of paramName in store if exists, paramValue if not.
//-----------------------------------------------------------------------------
function getSessionData(sn, pn, pv){
	if(pn.charAt(0)=='0'){
	    return pv;
	}
	try{
		var sV=getUserStoreData(sn, pn);  
		if(sV != null && sV != 'undefined' && sV != '')return sV;
		else return pv;
	}catch(e){ showError("getSessionData()", e.description); }
}

function addUserStoreDataValue(sn, pn, pv){
	if(pn.charAt(0)=='0')return; //this is to fix params from NB=0.
	//add it if not exist
	//append value if exists
	try{
		var os=getItem(sn);	 os.load(sn);
		var sV=os.getAttribute(pn);
		if(sV != null){
			if(sV.indexOf(pv)==-1){ os.setAttribute(pn, sV+pv); os.save(sn); }
		}else{ sV=os.setAttribute(pn,pv); os.save(sn); }
	}catch(e){ showError("addUserStoreDataValue", e.description); }//alert(os.XMLDocument.xml);
}

function deleteUserStoreDataValue(sn, pn, pv){
	//delete it if exist
	//dont do anything if it doesn't
	try{
		var os=getItem(sn);	 os.load(sn);
		var sV=os.getAttribute(pn);
		if(sV != null){
			if(sV.indexOf(pv) != -1){ os.setAttribute(pn, sV.replace(pv,'')); os.save(sn); }
		}
	}catch(e){ showError("deleteUserStoreDataValue()", e.description); }
}

//+-----------------------------------------------------
// initializeDom - initialize dom object
//+-----------------------------------------------------
function initializeDom(oXML){		
	oXML.async=false;
	oXML.validateOnParse=false;
	try{
  		oXML.setProperty("MaxXMLSize", 0); //unlimited file size - supported by MSXML 3.0 SP4
  	}catch(e){}

}

function getDom(){
    var oXML = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
	oXML.async=false;
	oXML.validateOnParse=false;
	try{
  		oXML.setProperty("MaxXMLSize", 0); //unlimited file size - supported by MSXML 3.0 SP4
  	}catch(e){}
	return oXML;
}

//+-----------------------------------------------------
// preparePage
//	function: initialize objects to be use for client-side dom xml parsing
//			(it is used by client-side sorting/grouping
//+-----------------------------------------------------	
function preparePage(){
  	// get the reference to the XML document parser
  	goXML = getDom();
  	goXSL = getDom();
  	
  	if(goXML != null & goXSL != null){
  	    return true;
  	}
  	/*
  	goXML=new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
  	initializeDom(goXML);
  	// get the reference to the XSL stylesheet parser
  	goXSL=new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
  	initializeDom(goXSL);
	//xslTrans=new ActiveXObject('Msxml2.XSLTemplate.3.0');
  	return true;
  	*/
}

//+-----------------------------------------------------
// updateParamNode
//	function: update param node if exist. add node if not.
//+-----------------------------------------------------	
function updateParamNode(oXML, Name,Value){
  	var o=oXML.selectSingleNode("//PARAM[@Name='"+Name+"']/@Value");
  	if(o != null) o.nodeValue=Value;
  	else{
  		//var params=oXML.childNodes[0].childNodes[0].childNodes[1];  //this works for XMLALL
  		var ps=oXML.documentElement.childNodes[0].childNodes[1];  // this works for both XMLALL and XML from response.
  		var p=ps.appendChild(oXML.createElement("PARAM"));	
  		p.setAttribute("Name",Name);
  		p.setAttribute("Value",Value);
  	}
}

//+----------------------------------------------------------------------------
//  Function:       setWindowStatus
//  Description:    set window status and body title based on event type
//	Arguments:		sType - post | getNewRow (advanced searching) | sort
//					status - waiting | ready
//-----------------------------------------------------------------------------
function setWindowStatus(sType, status){
	var sMSG='';
	if(status=='waiting'){
		gbReady=false;		
		document.body.style.cursor='wait';	
		var oWait = getItem('divWait');
		if(event != null){
		    oWait.style.left = event.pageX?event.pageX:event.clientX;
		    oWait.style.top = event.pageY?event.pageY:event.clientY;
		}else{
		    oWait.style.left = GetClientWidth() / 2;
		    oWait.style.top = GetClientHeight() / 2;
		}
		
		oWait.style.display = '';
		
		switch(sType){
			case 'post':
				sMSG='Retrieving data from server.';
				break;
			case 'getNewRow':
				sMSG='Creating new row. ';
				break;
			case 'sort':
				sMSG='Sorting. ';
				break;
			case 'load':
				sMSG='Loading. ';
				break;
			case 'redirect':
				sMSG='Redirecting. ';
				break;
			default:
			    sMSG=sType + '. ';;
		}
		sMSG=sMSG+'Please wait...';
		document.body.title=sMSG;
		window.status=sMSG;					
	}else{//ready
		gbReady=true;
		window.status='';	
		document.body.style.cursor='auto';		
		hide1('divWait');
		document.body.title='';
	}
	return true;
}

/************ functions to manipulate URL *******************/
//+----------------------------------------------------------------------------
//  Function:       removeURLParam
//  Description:    Removes a parameter from URL
//  Arguments:      sURL - url
//                  name - param name which needs to be removed.
//  Returns:        the new url which has a parameter removed.
//-----------------------------------------------------------------------------
function removeURLParam(sURL, name){	
		if(sURL.indexOf(name)!=-1){
		var s=(sURL.indexOf('&amp;')!=-1)?'&amp;':'&';
		var aParams=sURL.split(s);
		for (var i=0; i<aParams.length; i++){
			var aName = aParams[i].split("=");
			if(aName[0] == name)
				aParams[i]='';
		}
		var sNewURL = '';
		for (var i=0; i<aParams.length; i++){
			if(aParams[i] != ''){
				sNewURL = sNewURL + aParams[i] + s;
			}
		}
		return sNewURL.substring(0,sNewURL.lastIndexOf(s));
	}else return sURL;
	/*
	if(typeof(value) == 'undefined'){
		var sLeft = sURL.substring(0,sURL.indexOf('&amp;'+name+'='));
		var sRight = sURL.substring(sURL.indexOf('&amp;'+name+'=')+1,sURL.length);
		return(sLeft+sRight.substring(sRight.indexOf('&amp;'),sRight.length));
	}else{
		return(sURL.replace('&amp;'+name+'='+value,''));
	}
	*/
}

//+----------------------------------------------------------------------------
//  Function:       replaceURLParam
//  Description:    Replace a paramter value for a URL
//  Arguments:      sURL - url
//                  name - param name whose value needs to be replaced.
//					value - new value for the parameter
//  Returns:        url with a parameter's value replaced.
//-----------------------------------------------------------------------------
function replaceURLParam(sURL, name, value){	
	var s=(sURL.indexOf('&amp;')!=-1)?'&amp;':'&';
	return removeURLParam(sURL, name)+s+name+'='+value;
}

//+----------------------------------------------------------------------------
//  Function:       getURLParamValue
//  Description:    Retrieve a parameter's value from url.
//  Arguments:      sURL - url
//                  name - param name whose value needs to be retrieved.
//  Returns:        Returns value of the parameter if it exists in the URL,
//					otherwise returns an empty string.
//-----------------------------------------------------------------------------
function getURLParamValue(sURL, name){	
    //extract paramter part
    var a=sURL.split("?");
    if(a.length==2)sURL = a[1];
    
	var value='';
	var s=(sURL.indexOf('&amp;')!=-1)?'&amp;':'&';
	var aParams=sURL.split(s);
	for (var i=0; i<aParams.length; i++){
		var sName = aParams[i].substring(0,aParams[i].indexOf("="));
		if(sName == name){
			value=aParams[i].substring(aParams[i].indexOf("=")+1,aParams[i].length);
		}
	}
	return value;
}

//send request using xmlhhtp and return response.
function GetXMLHTTPResponse(sURL){
	var xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 	
	xmlhttp.Open("get", sURL, false);
	xmlhttp.Send('<?xml version="1.0"?><empty/>');
	return xmlhttp.responseXML;
}

function getAbsPath(){
	//use absolute URL - in case link is launched from saved report
	var o=getItem("absPath");
	if (o != null){
		var s= o.href;
		return s.substring(0,s.indexOf("main"));
	}else return '';
	//"http://"+location.hostname+location.pathname
}

function getRootPath(){
	var sPath=getAbsPath();
	if(sPath!=''){
		sPath=sPath.substring(0,sPath.indexOf(gsDLLPath));
		return sPath;
	}else return '';
}

//+----------------------------------------------------------------------------
//  Function:       NestedWorksheet2
//  Description:    Expand worksheet2map for report.
//  Arguments:      id - the record id which has the worksheet2map.
//					sNB - notebook name
//					aQuery - query string
//					aHeaderType - header type
//-----------------------------------------------------------------------------
function NestedWorksheet2(id, sNB, aQuery, aHeaderType){
	var oImg=getItem("img_"+id);
	var oDiv = getItem(id);

	if(oImg.src.indexOf("plus")!=-1){//expand it
		var sURL = "main" + LINK +
			"?NB=" + sNB +
			"&QRY=" + aQuery +
			"&TYP=report" + 
			//"&TYP=" + ParamsForm["pTYP"].value + //for more nested - later
			"&HTYP=" + aHeaderType +
			"&bContent=true";
		
		//URL=URL.replace("search","report");	
		//use absolute URL - in case link is launched from saved report
		
		sURL=getAbsPath()+sURL;
		var xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 	
		xmlhttp.Open("POST", sURL, false);
		xmlhttp.Send('');
		var s=xmlhttp.responseText;	
		try{		
			oDiv.innerHTML = s;
			oDiv.style.display="";
			if(oDiv.parentElement.parentElement.tagName == 'TR')//this is only for tabular
			    oDiv.parentElement.parentElement.style.display='';
			oImg.src=oImg.src.replace("plus","minus"); 
		}catch(e){	
			alert(e.description);
			return;
		}
	}else{//hide it.
		oDiv.style.display='none';
		if(oDiv.parentElement.parentElement.tagName == 'TR')
		    oDiv.parentElement.parentElement.style.display='none';
		oImg.src=oImg.src.replace("minus", "plus");
	}
}

function bookmarkSearch(type){
	var sL=location.href;
	var sURL=(type==REPORT)?gURL:gURL+addPersonalizationParams();
	if(sL.indexOf("?")!=-1)
		window.external.AddFavorite(sL.substring(0,sL.indexOf("?"))+"?"+sURL,document.title);
	else
		window.external.AddFavorite(sL+"?"+sURL,document.title);
}

function HideRightMenu(){
	hide("DivRightMenu");
}
/* expand/collapse all audit fields */
function showAudit(){
	var oDiv=getItems('__audit');
	for(var i=0; i<oDiv.length; i++){
		var o=oDiv[i].parentElement;
		if(o!=null){
		    o.style.display="";
		}
	}
	HideRightMenu();
}
function hideAudit(){
    if(gbIEVersion>6){
        window.location = document.location.href;//TODO:need to work on post pages
    }else{
	    var oDiv=getItems('__audit');
	    for(var i=0; i<oDiv.length; i++){
		    var o=oDiv[i].parentElement;
		    if(o!=null)o.style.display="none";
	    }
	}
	HideRightMenu();
}

//+----------------------------------------------------------------------------
//  Function:       getElementLeft
//  Description:    loop through parentElement to get the ultimate offsetLeft position of source element
//  Arguments:      eElement - event source element
//-----------------------------------------------------------------------------
function getElementLeft(eElement)
{
    var nLeftPos = eElement.offsetLeft;          
    var eParElement = eElement.offsetParent;     
    while (eParElement != null)
    {                                           
        nLeftPos += eParElement.offsetLeft;      
        eParElement = eParElement.offsetParent;  
    }
    return nLeftPos;                            
}
//+----------------------------------------------------------------------------
//  Function:       getElementTop
//  Description:    loop through parentElement to get the ultimate offsetTop position of source element
//  Arguments:      eElement - event source element
//-----------------------------------------------------------------------------
function getElementTop(eElement)
{
    var nTopPos = eElement.offsetTop;            
    var eParElement = eElement.offsetParent;    
    while (eParElement != null)
    {                                            
        nTopPos += eParElement.offsetTop;        
        eParElement = eParElement.offsetParent;  
    }
    return nTopPos;                             
}

//bring up LM Web user manual
function help(){
	newWindow(DIR+'help/LawManager_Enterprise_5.htm', 'help' ,0, 1, 1, 800, 800);
}   

function defaultStatusHint(){
	var sHTML="";
	if(gbHintOnMouseOver)sHTML=" onMouseOver=\"window.status=this.title;return true;\" onMouseOut=\"window.status='';return true;\"";
	//if(gbHintOnFocus)sHTML+=" onFocus=\"window.status=this.title;return true;\"";
	return sHTML;
}


//***********  PopupMenuMoveFocus *******************************
//Handle focusing for popup menus which are not embeded 
//in document order with their input fields - lookup / memo
//It is called from a hidden link placed on menu.
//If it's fired from "TAB", move focus to the first link except the hidden anchor.
//If it's fired from "SHIFT + TAB", move focus on the input field which "owns" the menu. 
//***************************************************************
function PopupMenuMoveFocus(BackItemId, MenuId){
	var oMenu = getItem(MenuId);	
	if(geKeyCode == nTAB_KEYCODE && geShift){
		if(BackItemId!=''){
		    focusOnIt(BackItemId);
		}
		oMenu.style.display="none";
		geOpenMenuID='';
	}
	else{ 
		//find focus link in oMenu - need to find second link - first one is the hidden close button
		var oForwardItem=GetPopupMenuFirstFocus(oMenu);	
		try{
		    elementOnFocus(oForwardItem);
		    oForwardItem.focus(); 
		    oForwardItem.select(); 		    
		}catch(e){}
	}
	geShift=false;
	geKeyCode='';
}

//recursive function to get the first link which is not the move focus anchor link.
function GetPopupMenuFirstFocus(oMenu){
	for(var i=0; i<oMenu.children.length; i++){ //IE specific
		var oChild=oMenu.children[i];
		if(oChild.tagName=='A' && oChild.id!='MoveFocusAnchor'){
			return oChild;
		}else{ 
			oChild=GetPopupMenuFirstFocus(oChild);
			try{
				if(oChild.tagName=='A' && oChild.id!='MoveFocusAnchor')return oChild;
			}catch(e){};			
		}
	}
}

function getContainerId(node){
    if(node!=null){
        var oParent = node.parentElement;   
        var nCnt = 5;
        for(var i=0; i<nCnt; i++){
            if(typeof(oParent.id)!='undefined'){
                return oParent.id;
            }
            oParent = oParent.parentElement;                
        }
    }
}

//remove "-hl" in classNames
function dehighlight(node){
    if(node!=null && node.className!=null){
        var className = node.className;
        if(className.indexOf("-hl")!=-1)
            node.className = className.split("-hl").join("");
        else if(className.indexOf("-on")!=-1)
            node.className = className.split("-on").join("");    
    }    
}

//add "-hl" to classNames
function highlight(node){
    if(goHighlighted!=''){
        if(goHighlighted.tp.substr(0,2) == 'rc'){
            dehighlightChildren(goHighlighted);
        }else {
            dehighlight(goHighlighted);
        }
    }
    if(node!=null && node.className!=null){
        var className = node.className;
        if(className.indexOf('-hl')!=-1)return;
        if(className.substr(className.length-1, 1) != " ")className += " ";
        if(className.indexOf("-on")!=-1)
            node.className = className.split("-on").join("-hl");            
        else if(className.indexOf('-hl')==-1)
            node.className = className.split(" ").join("-hl ");
    }
}
//set to "on" style
function highlighton(node){
    if(node!=null && node.className!=null){
        var className = node.className;
        if(className.indexOf("-on")!=-1)return;
        if(className.substr(className.length-1, 1) != " ")className += " ";    
        if(className.indexOf("-hl")!=-1)
            node.className = className.split("-hl").join("-on");
        else{
            node.className = className.split(" ").join("-on ");
        }
    }
}

/*
    e       focusable element
    cc      cell container
    rc      row container
*/
function highlightParent(node){
    if(node!=null){   
        if(node.tp == 'e1'){
            window.status=node.title+' Hold CTRL key and click to open in a new window.';
        }else if(node.tp == 'e0'){
            window.status = truncateStr(node.title, gnHintLimit);
        }            
        //var oParent = node.parentElement;   
        var oParent = node;   
        var nCnt = 6;
        for(var i=0; i<nCnt; i++){
            if(oParent != null){
                if(typeof(oParent.tp)!='undefined' && oParent.tp.substr(0,1) != 'e'){
                    if(oParent.tp.substr(0,2) == 'cc') {
                        highlight(oParent);
                    }else if(oParent.tp.substr(0,2) == 'rc') {
                        highlightChildren(oParent);
                    }
                    goHighlighted = oParent;
                    return;
                }
                oParent = oParent.parentElement;   
            }else{
                return;
            }             
        }
    }
}

/* me0 | me1    -   menu focusable element 
   mc           -   menu container
*/
function highlightParentToolBarMenu(node){
    resetHighlightedObjs();
    if(node!=null){
        if(node.tp == 'me1'){
            window.status=node.title+' Hold CTRL key and click to open in a new window.';
        }else if(node.tp == 'me0'){
            window.status=node.title;
        }
        var oParent = node.parentElement;   
        var nCnt = 5;
        for(var i=0; i<nCnt; i++){
            if(oParent != null){
                if(typeof(oParent.tp)!='undefined'){
                    if(oParent.tp.substr(0,2) == 'mc') {
                        highlightToolBarMenuItem(oParent);
                        goHighlighted = oParent;
                        return;
                    }
                } 
                oParent = oParent.parentElement;  

            }else{
                return;
            }             
        }
    }
}

//highlight table td cells
function highlightChildren(node){
    resetHighlightedObjs();
    for(var i=0;i<node.childNodes.length;i++){
        highlight(node.childNodes[i]);
    }
}

//dehighlight table td cells
function dehighlightChildren(node){
    for(var i=0;i<node.childNodes.length;i++){
        dehighlight(node.childNodes[i]);
    }
}

function resetHighlightedObjs(){
    if(goHighlighted!=''){
        if(goHighlighted.tp.substr(0,2) == 'rc' || goHighlighted.tp.substr(0,2) == 'mc'){
            dehighlightChildren(goHighlighted);
        }else {
            dehighlight(goHighlighted);
        }
    }
}

function createOneBorder(bId, bWidth, bHeight, bLeft, bTop){
    var obj = document.createElement("DIV") ;
    with (obj) {
        id = bId;
        with (style) {
            fontSize="1px";
	        height = bHeight;
	        width  = bWidth;
	        backgroundColor = "#FFBD3A" ;
	        borderColor = "#FFBD3A" ;
	        position = "absolute" ;
	        left = bLeft;
	        top = bTop;
	        zIndex = 2 ;
	        display = "none";
        }
    }
    return obj;
}
function repositionOneBorder(bId, bWidth, bHeight, bLeft, bTop){
    var obj = document.getElementById(bId);
    with (obj) {
        with (style) {
	        left = bLeft;
	        top = bTop;
	        width = bWidth;
	        height = bHeight;
        }
    }
}

function highlightBorder(mOverItem){
    var obj = new Bounds(mOverItem);
    x = obj.X,
    y = obj.Y - 1;
    x1 = obj.X1 + 1;
    y1 = obj.Y1;
    var t = 2; //border thickness
    var obj1, obj2, obj3, obj4;
    if(document.getElementById("border1") == null){
        obj1 = createOneBorder("border1", x1 - x, t, x, y);
        obj2 = createOneBorder("border2", t, y1 - y, x1 - t, y);
        obj3 = createOneBorder("border3", x1 - x, t, x, y1 - t);
        obj4 = createOneBorder("border4", t, y1 - y, x, y);
        document.body.insertAdjacentElement("afterBegin", obj1);
        document.body.insertAdjacentElement("afterBegin", obj2);
        document.body.insertAdjacentElement("afterBegin", obj3) ;
        document.body.insertAdjacentElement("afterBegin", obj4) ;
    }else{
        obj1 = document.getElementById("border1");
        obj1.style.left = x;
        obj1.style.top = y;
        obj1.style.width = x1 - x;
        obj2 = document.getElementById("border2");
        obj2.style.left = x1 - t;
        obj2.style.top = y;
        obj2.style.height = y1 - y;
        obj3 = document.getElementById("border3");
        obj3.style.left = x;
        obj3.style.top = y1 - t;
        obj3.style.width = x1 - x;
        obj4 = document.getElementById("border4");
        obj4.style.left = x;
        obj4.style.top = y;
        obj4.style.height = y1 - y;
    }
    obj1.style.display = "";
    obj2.style.display = "";
    obj3.style.display = "";
    obj4.style.display = "";
}

function dehighlightBorder(){
    obj1 = document.getElementById("border1");
    obj2 = document.getElementById("border2");
    obj3 = document.getElementById("border3");
    obj4 = document.getElementById("border4");
    obj1.style.display = "none";
    obj2.style.display = "none";
    obj3.style.display = "none";
    obj4.style.display = "none";
}

function Bounds(el) {
	this.X = null;
	this.Y = null;
	this.X1 = null;
	this.Y1 = null;

	var pos = getOffSetArray(el);
	this.X = pos[0];// + el.offsetLeft;
	this.Y = pos[1];// + el.offsetTop;
	this.X1 = this.X + parseInt(el.offsetWidth);
	this.Y1 = this.Y + parseInt(el.offsetHeight);
}

function getOffSetArray(el) {
	var pos = new Array();
	pos[0] = 0;
	pos[1] = 0;
	while (el != null) {
		pos[0] += el.offsetLeft ;
		pos[1] += el.offsetTop ;
		el = el.offsetParent ;
	}
	return pos;
}

function refresh(URL){
    if(typeof(URL)=="undefined"){
        URL = fixURL(document.location.href);
    }

    //check url length to decide if do post
    var bPost=false; 
	if(URL.length > gnURLLenLimit)bPost=true;
	if(bPost){	
		var oDiv=getItem("URLDiv");
		oDiv.innerHTML=getURLPostForm(URL);
		var oURLForm=getItem("URLForm");
		oURLForm.submit();
	}else{
        window.location.href = URL;
    }
    return;
}
function fixURL(sURL){
   if(sURL.substr(sURL.length - 1,1)=="#"){ //dev#3369 need to strip off # at the end of URL
        return sURL.substring(0, sURL.length - 1);
   } else {
        return sURL;
   }
}

function getURLPostForm(URL){
	var a= URL.split("?");
	var s=a[1].split("&");
	var sHTML='<form id="URLForm" action="'+a[0]+'" method="post">';
	for(var i=0; i<s.length; i++){
		var n=s[i].indexOf("="); //can't use split because there is = sign in QRY
		var name=s[i].substring(0,n);
		var value=s[i].substring(n+1,s[i].length);
		if(value != '')
			sHTML+='<input type="hidden" name="'+name+'" value="'+HTMLEncode(URLDecode(value),'"')+'"/>'; //need to decode because the form will encode it.
	}
	sHTML+='</form>';
	return sHTML;
}
