// General.js - HQMS JavaScript support functions
var errorlog = new Array();
var JS_Debug_Mode=true;
var m_cField = ''; //Add notes global parameter
var m_cTitle = ''; //Add notes global parameter

// Remote Scripting through XML...
function loadDataIsland(cDataIsland, cQueryString)
	{
		//reload current record	
			document.all(cDataIsland).src = 'default.asp?' + cQueryString;
	}

//****************************************************************************
//  GROUP FUNCTIONS

function errormsg(errnum, errtext)
{
	this.errnum = errnum;
	this.errtext = errtext;
}

//  END GROUP FUNCTIONS
//****************************************************************************

//****************************************************************************
//	DOCUMENT FUNCTIONS

function ViewTemplate(cGUID, bNewWindow){
/*	var nOpt = nDocViewOpt;
	if(nOpt=='2'){
		bRes = window.confirm('Would you like to use the built in HQMS Viewer to view this document?');
		if(bRes){
			nOpt='1';
		} else {
			nOpt='0';
		}
	}
	if(nOpt=='1'){
		if(bNewWindow==null) bNewWindow=true;
		cURL = 'default.asp?class=doc&method=tmpviewer&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
	} else { */
		if(bNewWindow==null) bNewWindow=true;
		cURL = 'default.asp?class=doc&method=viewtemplate&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
/*	}	*/
}

function ViewDocument(oData, bNewWindow){
	
	if(oData[0]==null){
		var cGUID = oData;
	} else {
		var cGUID = oData[0];
	}

	var cURL = 'default.asp?class=doc&method=ViewOptions&GUID=' + cGUID;
	if(bNewWindow==null) bNewWindow=false;
	if(bNewWindow){
		window.open(cURL, 'Window_' + cGUID, "location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, titlebar=no, toolbar=no, height=400, width=400");
	} else {
		document.location.href=cURL;
	}

/*	var nOpt = nDocViewOpt;
	if(nOpt=='2'){
		bRes = window.confirm('Would you like to use the built in HQMS Viewer to view this document?');
		if(bRes){
			nOpt='1';
		} else {
			nOpt='0';
		}
	}
	if(nOpt=='1'){
		if(bNewWindow==null) bNewWindow=true;
		cURL = 'default.asp?class=doc&method=docviewer&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
	} else {
		if(bNewWindow==null) bNewWindow=true;
		cURL = 'default.asp?class=doc&method=viewdoc&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
	}
*/
}

function ViewRev(cGUID, bNewWindow){
/*	var nOpt = nDocViewOpt;
	if(nOpt=='2'){
		bRes = window.confirm('Would you like to use the built in HQMS Viewer to view this document?');
		if(bRes){
			nOpt='1';
		} else {
			nOpt='0';
		}
	}
	if(nOpt=='1'){
		if(bNewWindow==null) bNewWindow=true;
		cURL = 'default.asp?class=doc&method=revviewer&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
	} else {
*/
		if(bNewWindow==null) bNewWindow=false;
		cURL = 'default.asp?class=doc&method=viewrev&guid=' + cGUID[0];
		if(bNewWindow){
			window.open(cURL);
		} else {
			document.location.href=cURL;
		}
/*	} */
}




//  END DOCUMENT FUNCTIONS
//****************************************************************************

//****************************************************************************
//   Error FUNCTIONS

function loadErrorDialog(oArray){
	window.showModalDialog('hqms_ErrorDialog.htm',oArray,'dialogHeight:525px;dialogWidth:700px;status:no;center:yes;help:no');
}

function ErrorDialog(cErrorXML){
	var oErrorArray = new Array(1);			
	oErrorArray[0]=cErrorXML;			
	loadErrorDialog(oErrorArray);			
}

//   END Email FUNCTIONS
//****************************************************************************

//****************************************************************************
//   Email FUNCTIONS

function loadEmailDialog(){
	var cURL='default.asp?class=Email&method=Dialog';
	window.showModalDialog(cURL,'','dialogHieght:600px;dialogWidth:550px;status:no;center:yes;help:no');
}

//   END Email FUNCTIONS
//****************************************************************************

//****************************************************************************
// ADD COMMENTS

function GetComments(cTitle,cExisting){
	var oArgs=new Array(cExisting,cTitle);
	var cComments = window.showModalDialog('hqms_AddCommentsDialog.htm',oArgs,'resizable:yes;dialogHeight:260px;dialogWidth:500px;status:no;scroll:yes;help:no;center:yes')
	return cComments;
}

//****************************************************************************




//************************************************************************************
function AddDev()
	 {
	
		AddDeviationWindow('LoadNewDeviation', 'Add Deviation');
	 }
	 
function LoadNewDeviation(cGUID)
	 {
		if(cGUID){	
			if(cGUID != '' && cGUID !=  '0'){
				document.location.href = 'default.asp?class=deviation&method=detail&editmode=true&new=true&GUID=' + cGUID;
			}
		}		
	 }
	 

// LoadReport & Chart Functionality

function LoadReport(cReportGUID, nSystemID, cKey){
	var cURL='default.asp?class=report&method=DetailReport&reportGUID=' + cReportGUID + '&systemID=' + nSystemID + '&key=' + cKey;
	window.open(cURL,'ReportOptions','height=645,width=650,resizable=yes,scrollbars=yes');	
}


function LoadReportOptionsPage(cReportGUID, nSystemID, cKey){
	var cURL='default.asp?class=report&method=optionsPage&reportGUID=' + cReportGUID + '&systemID=' + nSystemID + '&key=' + cKey;
	document.location.href=cURL;
}


function LoadChart(cChartGUID, nSysID, cKey)
{
	var cURL = 'default.asp?class=chart&method=optionspage&chartguid=' + cChartGUID + '&systemid=' + nSysID + '&key=' + cKey;
	//window.open(cURL, 'ChartOptions', 'height=645,width=650,resizable=yes,scrollbars=yes');
	document.location.href=cURL;
}



// This function is used by list/detail screens that do not have a specific reportGUID, but are requesting
// printing based on a supplied query string. Based on SystemID/bSinglePage, a list of available reports
// will be presented to the client (the whereclause travels through).
// Note: If only one report is available then (subsequent) options page is presented directly.
function ReportRequest(cWhereClause, nSystemID, bSinglePage, cKey)
{
	var cURL = 'default.asp?class=report&method=DetailReportRequest&whereclause=' + cWhereClause + '&systemid=' + nSystemID + '&singlePage=' + bSinglePage + '&key=' + cKey;
	//showModalDialog(cURL,null,'status:no;dialogHeight:350px;dialogWidth:350px');
	window.open(cURL,'ReportOptions','status=no,height=345,width=650,resizable=yes');

}

// Frames Navigation Functions
/*******************************
	* NavFrameRestore() - resets navigation (left-hand) frame to last saved state
	* NavFrameLoad(cURL, nWidth) - loads (main) nav frame with cURL and sets width to narrow (1) or wide (2)
	* NavFrameHide(bReset) - closes NavFrame and optionally resets
	- Modifications 12/3/01 - bm: Changed NavFrameLoad to use search pane.
*******************************/ 
function NavFrameRestore(){
	top.NavFrameRestore();
}

function NavFrameLoad(cURL, nWidth){
	top.SearchFrameLoad(cURL, nWidth);
	
}
function NavFrameHide(bNoReset){
	top.closef();
	if (bNoReset!=true) top.NavFrameRestore();
	
}


// Main Frame Function returns reference to main (client area) frame. for use by call-back fucntions
function ContentFrame(){
	return top.ContentFrame();
	
}

// loads page into content frame
function loadPage(cURL){
	top.ContentFrameLoad(cURL);
}

function loadRedirect(){
	var cURL = 'default.asp?class=Core&method=GetRedirect';
	loadPage(cURL);
}
//****************************************************************************************************************************************************************************************************
//****************************************************************************************************************************************************************************************************
//ShowCalendar 
//X,Y Coordinates to position calendar
//oElement.value will be set to selected date

function dateCallBack(){

	EventDataChanged();
}

function ShowCalendar(x,y,oElement,oForm) {
	
try{
		
	//Set Ref to Element
		oDateBox=oElement;
		//Get Initial Value of Date Box
	
		cDate = formatDate(new Date(oDateBox.value),'MM/dd/y');
	
	//Need to validate date
		var oDateHandler = new DateManip();

		if(!oDateHandler.isProperDate(cDate)){
			var oDate = new Date();
			cDate = oDate.toString();
			cMonth =oDate.getMonth().toString();
			cYear = oDate.getFullYear().toString();
			cDay = oDate.getDate().toString();
			
		}else{
			var oDate = new Date(cDate);
			
			cMonth =oDate.getMonth().toString();
			cYear = oDate.getFullYear().toString();
			cDay = oDate.getDate().toString();
		
		}		
		

	show_calendar('all.' + oElement.name,cMonth,cYear,"MONTH DD, YYYY",cDay);
	return null	
		
	//Create Div
		var oDiv = document.createElement('<div id="CalDiv" style="position:absolute; width:160px; height:170px; z-index:2; left: 290px; top: 2px; background-color: #FF3300; visibility: hidden">');
		var cApp='            <applet mayscript code="tcaldate.class" width="160" height="170" name="tL1" id="tL1" VIEWASTEXT>';
		cApp+='              <param name="link" value="%M/%D/%Y">';
		cApp+='              <param name="script" value="javascript:SeeDate(\'%M/%D/%Y\')">';
		cApp+='              <param name="target" value="_none">';
		cApp+='              <param name="font" value="Arial">';
		cApp+='              <param name="fontsize" value="12">';
		cApp+='              <param name="fontstyle" value="1">';
		cApp+='              <param name="bgcolor" value="10079472">';
		cApp+='              <param name="bgcolor2" value="16711411">';
		cApp+='              <param name="bgcolor3" value="400">';
		cApp+='              <param name="startsunday" value="0">';
		cApp+='              <param name="t_col1" value="400">';
		cApp+='              <param name="t_col2" value="8421520">';
		cApp+='              <param name="t_col3" value="14737663">';
		cApp+='              <param name="min" value="1/1/1950">';
		cApp+='              <param name="max" value="12/31/2049">';
		cApp+='              <param name="weeknumber"    value="no">';
		cApp+='              <param name="Copyright" value="RBL : rbl@berthou.com">';
		cApp+='              <param name="Current" value="' + cDate + '">';
		cApp+='            </applet>';
		

		document.body.appendChild(oDiv);		
		oDiv.innerHTML = cApp;
		oDiv.style.pixelLeft = x;
	oDiv.style.pixelTop = y;
	oDiv.style.visibility = 'visible';

} catch(e){
	alert(e.message);
}

}
//These functions supports the ShowCalendar Function - Cal Applet
//Do Not Call These
var oDateBox;
var oFrm;
function SeeDate(i){oDateBox.value=formatDate(new Date(i),'MMM dd, yyyy');HideDate();}
function HideDate(){CalDiv.style.visibility='hidden';document.body.removeChild(CalDiv);}
//Do Not Call These
//Thank You
//-->
//****************************************************************************************************************************************************************************************************
//***************************************************************************************************************************************************************************************************


//******************************************************************************************************
// Global Tab Handling Stuff ***************************************************************************

var Glb_CurrentTab;
var Glb_CurrentTabName='';
var Glb_CurrentTabOldStyle='';
var Glb_bInUse=false;
var Glb_URLArray=new Array();


function Glb_LoadTab(){
	Glb_CurrentTab.innerHTML = document.all('Glb_XML_Tab').selectSingleNode('hgXML/HTMLTab').text;
	
	try{
		eval('DIV' + Glb_CurrentTabName + 'Init()');
	} catch(e){
		//do nothing
	}
	Glb_TabLoadComplete();
}

function Glb_ReadyStateChanged(){
	if(document.all.Glb_XML_Tab.readyState=='complete'){
		Glb_LoadTab();
	}
}

function ShowTab(cName,cStateVar,bPersistCurTab)
{	
	// Attempt raise an Pre-Tab event on the user's page. If the 
	// user is not supporting the function, the error will be ignored.
	// It is used only to notify the user page that a tab has been clicked,
	// in case they want to perform a specific action.
	
	try {
		EventPreTab(cName);
	} catch(e) {} // ignore errors
	
	// Deal With In Use
		if(Glb_bInUse){
			
			Glb_URLArray[Glb_URLArray.length]=cName;
		} else {
			
			Glb_bInUse=true;
			
		// Try to change style
			try{
				document.all['nav' + Glb_CurrentTabName].className=Glb_CurrentTabOldStyle;
			} catch(e){
				//ignore
			}
			
		//Hide Current Tab if set
			if(Glb_CurrentTab!=null && bPersistCurTab!=true){
				try{
					Glb_CurrentTab.style.display='none';
					Glb_CurrentTab.style.visiblity='hidden';
				} catch(e){
					alert('Error loading tab: Unable to hide previous tab (' + Glb_CurrentTabName + ')');
				}
			}

	
		//Set Current Tab to Requested Tab
			try{
				eval('Glb_CurrentTab=DIV' + cName);
			} catch(e){
				alert('Error loading tab: ' + cName + '\n\nWill attempt to load General Tab');
				cName = 'General';
				eval('Glb_CurrentTab=DIV' + cName);
			}

			try{
				Glb_CurrentTabOldStyle=document.all['nav' + cName].className;
			} catch(e){
				//ignore
			}
			
			try{
				document.all['nav' + cName].className='navHighlight';
			} catch(e){
				//ignore
			}
			try{
				if(cStateVar>''){
					StoreStateSetting(cStateVar,cName);
				}
			} catch(e){
				//ignore
			}


			Glb_CurrentTabName=cName;
			
		// Handle Null Tab
			if(Glb_CurrentTab==null){
				alert('Error loading tab: unable to locate tab ' + cName);
			}
	
		//Show Requested Tab
			if(Glb_CurrentTab.innerHTML==''){
				//Load Tab
					Glb_CurrentTab.innerHTML='Page is loading . . . . ';
					eval('document.all(\'Glb_XML_Tab\').src=DIV' + cName + 'Default');
					//Glb_TabLoadComplete();
			} else {
				Glb_TabLoadComplete();
			}

		//Display Tab		
			try{
				Glb_CurrentTab.style.display='';
				Glb_CurrentTab.style.visibility='visible';
			} catch(e){
				alert('Error loading tab: unable to set style on tab ' + cName);
			}
		}

}

function Glb_TabLoadComplete(){
	
	Glb_bInUse=false;
	if(Glb_URLArray.length>0){
		var cItem=Glb_URLArray[0];
		Glb_URLArray=Glb_URLArray.slice(1,Glb_URLArray.length);
		ShowTab(cItem,'');
	}
	
	// Attempt raise an Post-Tab event on the user's page. If the 
	// user is not supporting the function, the error will be ignored.
	// It is used only to notify the user page that a tab change has been completed.
	// in case they want to perform a specific action.
	
	try {
		EventPostTab(cName);
	} catch(e) {} // ignore errors

}

function debug(cText){
	try{
		divdebug.innerHTML += '<br>' + cText;
	} catch(e){
		//nothing
	}
}

//*******************************************************************************************************



//*******************************************************************************************************
// XML Object Handling *********************************************************************************
var bXMLObjInUse=false;
var XMLObjWait=new Array();
function UseXMLObj(cURL,cFunction){
	
	var cFunc='';
	if(cFunction>''){
		cFunc=cFunction;
	} else {
		cFunc='IgnoreXMLObj';
	}
	if(bXMLObjInUse){
	
		XMLObjWait[XMLObjWait.length]=new Array(cURL,cFunc);
	} else {
		bXMLObjInUse=true;
		XMLObjWait[0]=new Array(cURL,cFunc);
		
	 //If the seconfrom exists(no error) then submit it by form
	 //else submit it by query string method 
	try{
	   if(document.all.SecondForm.srcsend.value == "list"){
				document.all.SecondForm.submit();
			}else {document.all.XMLObj.src=cURL;}
		}catch(e){document.all.XMLObj.src=cURL;}
		  
	}
}

function XMLObjReadyStateChanged(){
	/* Need a try here cause the when back button the iFrame reloads, calls Loaded()
	 which calls on readystatechange in the XMLOB which errors ot cause XMLObjWait
	 below is here--will apply proper fix later */
 try{
	if(document.all.XMLObj.readyState=='complete'){
		try{
			top.frameContentHeader.resetTimeout();		
		}catch(e) { 
			try{
				window.opener.top.frames['frameContentHeader'].resetTimeout();
			} catch(e){
				//nothing
			}
		}
		var cFunction=XMLObjWait[0][1];
		XMLObjWait=XMLObjWait.slice(1,XMLObjWait.length);	
		eval(cFunction + '()');
	}
	}catch(e){}
}

function UseXMLObjComplete(){
	
	if(XMLObjWait.length>0){
		var cURL=XMLObjWait[0][0];
		document.all.XMLObj.src = cURL;
	} else {
		bXMLObjInUse=false;
	}
	return true;
}

function IgnoreXMLObj(){
	UseXMLObjComplete();
}

function StoreStateSetting(cName,cValue){
	UseXMLObj('default.asp?method=state&var=' + cName + '&value=' + cValue);
}


function XMLObjStr(cQuery){
	//Returns a String Value from the XMLObj for XML Query cQuery
		try{
			var c = XMLObj.selectSingleNode(cQuery).text;
			return c
		} catch(e){
			return '';
		}
}

function XMLObjNum(cQuery){
	//Returns a Numeric Value from the XMLObj for XML Query cQuery
		try{
			var n = parseInt(XMLObj.selectSingleNode(cQuery).text);
			if(isNaN(n)){
				return 0;
			} else {
				return n;
			}			
		} catch(e){
			return 0;
		}
}

function XMLObjXML(cQuery){
	//Returns XML from the XMLObj for XML Query cQuery
		try{
			var c = XMLObj.selectSingleNode(cQuery).xml;
			return c;
		} catch(e){
			return '';
		}
}




// *****************************************************************************************************

//*********************
//This set of functions assumes that the XML request is in the format of GetXMLResponse() from VB
//<response><result/><message/><error/><data/><navigation><text/></navigation></response>
//*********************


function GetXMLObjResult(){
	var bReturn=false;
	try{
		bReturn = ('True' == document.all.XMLObj.selectSingleNode('response/result').text);
	} catch(e){
		bReturn = false
	}
	return bReturn;
}

function GetXMLObjMessage(){
	var cReturn='';
	try{
		cReturn = document.all.XMLObj.selectSingleNode('response/message').text;
	} catch(e){
		cReturn = '';
	}	
	return cReturn;
}

function GetXMLObjErrorXML(){
	var cReturn='';
	try{
		cReturn = document.all.XMLObj.selectSingleNode('response/error/root').xml;
	} catch(e){
		cReturn = '';
	}	
	return cReturn;
}

function DisplayXMLObjError(){
	var cErr = GetXMLObjErrorXML();
	ErrorDialog(cErr);
}

function GetXMLObjDataXML(){
	var cReturn='';
	try{
		cReturn = document.all.XMLObj.selectSingleNode('response/data').xml;
	} catch(e){
		cReturn = '';
	}		
	return cReturn;
}

function GetXMLObjDataText(){
	var cReturn='';
	try{
		cReturn = document.all.XMLObj.selectSingleNode('response/data').text;
	} catch(e){
		cReturn = '';
	}		
	return cReturn;
}


// *******************************************************************************
// NEW PART

// this will return a string =     ID,PartNumber

function NewPartDialog(){
	//	var Result=showModalDialog('default.asp?class=core&method=AddPart','','status:no;dialogHeight:200px;dialogWidth:400px');
	var Result = showModalDialog('default.asp?class=Part&method=NewDialogPage','','resizable:yes;status:no;dialogHeight:300px;dialogWidth:600px');
	return Result;
}

// *******************************************************************************

// ***********************************************************************************
// GROUP DETAILS

function GroupMemberPopup(cGroupGUID){
	var cURL = 'default.asp?class=UserGroup&method=ListMembers&GUID=' + cGroupGUID;
	var x=window.showModalDialog(cURL,'','dialogHeight:400px;dialogWidth:600px;resizable:yes;help:no');
	if(x!=null){
		document.location.href=x;
	}
}

// ***********************************************************************************


// ***********************************************************************************
// RELATIONSHIP SUPPORT FUNCTIONS
	
var z_RelationshipType
var z_RelationshipName
var z_RelationshipID
var z_RelationshipTab

function AddRelationship(nID,nType,cName, nOptions,cTab){
	z_RelationshipType = nType;
	z_RelationshipName = cName;
	z_RelationshipID = nID;
	z_RelationshipTab = cTab;
	cGroups=UserGroupListFind();	
	UseXMLObj('default.asp?class=core&method=relationship&command=add&Rtype=' + z_RelationshipType + '&RName=' + z_RelationshipName + '&ID=' + z_RelationshipID + '&Groups=' + cGroups + '&Tab=' + z_RelationshipTab,'Refresh' + z_RelationshipName);	
}

function RelationshipSelected(cGroups){
	UseXMLObj('default.asp?class=core&method=relationship&command=add&Rtype=' + z_RelationshipType + '&RName=' + z_RelationshipName + '&ID=' + z_RelationshipID + '&Groups=' + cGroups + '&Tab=' + z_RelationshipTab,'Refresh' + z_RelationshipName);
}

function DeleteRelationshipOnOff(nID, nType,cName,cTab){
	
	var bOn=false;
	
	try{
		eval('var div_dc=DIV' + cName + 'DeleteCancel');
		eval('var div_pd=DIV' + cName + 'PerformDelete');
		eval('var oDelBoxes = document.all.Del' + cName);
		if(oDelBoxes.length!=null){
			for(var x=0;x<oDelBoxes.length;x++){
				if(oDelBoxes[x].style.visibility=='visible'){
					oDelBoxes[x].style.visibility='hidden';				
				} else {
					bOn=true;
					oDelBoxes[x].style.visibility='visible';
				}
			}
		} else {
			if(oDelBoxes.style.visibility=='visible'){
				oDelBoxes.style.visibility='hidden';
			} else {
				bOn=true;
				oDelBoxes.style.visibility='visible';
			}
		}
		
		if(bOn){
			div_dc.innerHTML = '<a href=\"javascript:DeleteRelationshipOnOff(' + nID + ',' + nType + ',\'' + cName + '\',\'' + cTab + '\')\"><img src=\"images/cancelIcon.gif\" border=\"0\" alt=\"Cancel Delete\" onMouseOver=\"window.status=\'Cancel Delete\';return true\" onMouseOut=\"window.status=\'\'; return true\"></a>';
			div_pd.innerHTML = '<table widt\"100%\"><tr><td>Select the records to delete then <a href=\"javascript:DeleteRelationship('+ nID + ',' + nType + ',\'' + cName + '\',\'' + cTab + '\')\" onMouseOver=\"window.status=\'Delete ' + cName + '\';return true\" onMouseOut=\"window.status=\'\'; return true\">click here...</a></td><td><a href=\"javascript:DeleteRelationship(' + nID + ',' + nType + ',\'' + cName + '\',\'' + cTab + '\')\" onMouseOver=\"window.status=\'Delete ' + cName + '\';return true\" onMouseOut=\"window.status=\'\'; return true\"><img src=\"images/deleteIcon.gif\" border=\"0\" alt=\"Delete ' + cName + '\"></a></td></tr></table>';			
			
		} else {
			div_pd.innerHTML='';
			div_dc.innerHTML='<a href=\"javascript:DeleteRelationshipOnOff(' + nID + ',' + nType + ',\'' + cName + '\',\'' + cTab + '\')\"><img src=\"images/deleteIcon.gif\" border=\"0\" alt=\"Delete ' + cName + '\" onMouseOver=\"window.status=\'Delete ' + cName + '\';return true\" onMouseOut=\"window.status=\'\'; return true\"></a>';
		}
		
		
	} catch(e){
		// ignore
	}	
}

function DeleteRelationship(nID,nType,cName,cTab){
	var cDel='';
	try{
		eval('var oDelBoxes = document.all.Del' + cName);	
		if(oDelBoxes.length!=null){
			for(var x=0;x<oDelBoxes.length;x++){
				if(oDelBoxes[x].checked){
					cDel+=oDelBoxes[x].value + ',';
				}
			}
		} else {
			if(oDelBoxes.checked){
				cDel+=oDelBoxes.value + ',';
			}
		}
		if(cDel>''){
			UseXMLObj('default.asp?class=core&method=Relationship&command=remove&Rtype=' + nType + '&RName=' + cName + '&ID=' + nID + '&Groups=' + cDel + '&Tab=' + cTab,'Refresh' + cName);
		}
	
	} catch(e){
		//ignore
	}
}

function RefreshRelationship(cName){
	try{
		eval('var oDiv=DIV' + cName);
		oDiv.innerHTML = '';
		ShowTab(cName);
	} catch(e){
		//alert(e.description);
	}
}


function formatDate(date,format) {
// ***********************************************************************************

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// !!!!THIS FUNCTION IS CASE SENSITIVE SO BE CAREFULL OF THE FORMAT THAT YOU SEND!!!!
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "m/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

	
	format = format+"";
	var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var result = "";
	var i_format = 0;
	var c = "";
	var token = "";
	var y = date.getYear()+"";
	var M = date.getMonth()+1;
	var d = date.getDate();
	var H = date.getHours();
	var m = date.getMinutes();
	var s = date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	// Year
	if (y.length < 4) {
		y = y-0+1900;
		}
	y = ""+y;
	yyyy = y;
	yy = y.substring(2,4);
	// Month
	if (M < 10) { MM = "0"+M; }
		else { MM = M; }
	MMM = MONTH_NAMES[M-1];
	// Date
	if (d < 10) { dd = "0"+d; }
		else { dd = d; }
	// Hour
	h=H;
	K=H;
	k=H+1;
	if (h > 12) { h-=12; }
	if (h == 0) { h=12; }
	if (h < 10) { hh = "0"+h; }
		else { hh = h; }
	if (H < 10) { HH = "0"+K; }
		else { HH = H; }
	if (K > 11) { K-=12; }
	if (K < 10) { KK = "0"+K; }
		else { KK = K; }
	if (k < 10) { kk = "0"+k; }
		else { kk = k; }
	// AM/PM
	if (H > 11) { ampm="PM"; }
	else { ampm="AM"; }
	// Minute
	if (m < 10) { mm = "0"+m; }
		else { mm = m; }
	// Second
	if (s < 10) { ss = "0"+s; }
		else { ss = s; }
	// Now put them all into an object!
	var value = new Object();
	value["yyyy"] = yyyy;
	value["yy"] = yy;
	value["y"] = y;
	value["MMM"] = MMM;
	value["MM"] = MM;
	value["M"] = M;
	value["dd"] = dd;
	value["d"] = d;
	value["hh"] = hh;
	value["h"] = h;
	value["HH"] = HH;
	value["H"] = H;
	value["KK"] = KK;
	value["K"] = K;
	value["kk"] = kk;
	value["k"] = k;
	value["mm"] = mm;
	value["m"] = m;
	value["ss"] = ss;
	value["s"] = s;
	value["a"] = ampm;
	while (i_format < format.length) {
		// Get next token from format string
		c = format.charAt(i_format);
		token = "";
		while ((format.charAt(i_format) == c) && (i_format < format.length)) {
			token += format.charAt(i_format);
			i_format++;
			}
		if (value[token] != null) {
			result = result + value[token];
			}
		else {
			result = result + token;
			}
		}
		
	return result;
	}
	
	
function LoadConfigRights(cXML)
{
	//called once when loading the config rights xml
	
	//set the private XML Object src to the xml passed
		RightsXML.loadXML = cXML;
}

function HasRecordRight(cRight, cModule, cRightsString)
{
	//looks up the right under the module in the rights xml object
	//returns true if position is a 1, false otherwise
	var oNode;
	var cRightPos;
	var bHasRight = false;
	
	//check the attributes first then the child nodes
		oNode = XMLRights.selectSingleNode("hgXML/Rights/SystemLevel/Module[@id='" + cModule + "']")
		if(oNode)
		{
			cRightPos = oNode.attributes.getNamedItem(cRight).nodeValue + '';
			
			if(cRightValue == ''){
				oNode = XMLRights.selectSingleNode("hgXML/Rights/SystemLevel/Module[@id='" + cModule + "']/" + cRight)
				if(oNode){
					cRightPos = oNode.text + '';
				}
			}
		}
		
	//if pos found, then check the rights string
		if(cRightPos != '' && cRightsString != ''){
			bHasRight = (cRightsString.charAt(Val(cRightPos)) == '1');
		}
		
	//return
		return bHasRight;
}


function DayDiffFromToday(cDate){
	try{
		var oToday=new Date();
		var oDate=new Date(cDate);
		var nToday=oToday.getTime();
		var nDate=oDate.getTime();
		var nDiff=Math.abs(nToday-nDate);
		var nDayDiff=Math.round(nDiff / (1000 * 60 * 60 * 24));
		return nDayDiff;
	} catch(e){
		return null;
	}
}


function AddAlerts(cGUID, cAlert, bDialog){
	if(bDialog){
		var cAlert = window.prompt('Please enter the Alert',cAlert);
	}
	
	UseXMLObj('default.asp?class=alert&method=addalerts&guid=' + cGUID + '&alert=' + cAlert,'AddAlertsComplete');
	
}

function AddAlertsComplete(){
	try{
		if(XMLObj.selectSingleNode('response/result').text='True'){
			alert('Alerts have been added successfully');
		} else {
			alert('An error was encountered adding alerts: ' + XMLObj.selectSingleNode('response/error').text);
		}
	} catch(e){
		alert(e.description);
	}	
	UseXMLObjComplete();
}

// Declare IS_ID
IS_IE = navigator.appName.indexOf("Microsoft") != -1;

// Trap the key press event
function TrapEnter(func, context) {
	
	return function(e) {		
		
		// Get the Event object
		keyCode = IS_IE ? window.event.keyCode : e.which;
		if (keyCode == 13) {
			// Call user-supplied hook
			func(context);
			// Disable further handling of this event
			if (IS_IE) {
				window.event.returnValue = false;
			} 
			else {
				return false;
			}
				
		}
	};
}

function inlineTrapEnter(func, context) {	
			
	// I had to add this function because the other TrapEnter function does not 
	// work when assigned inside of a tag
	
	// Get the Event object
	keyCode = IS_IE ? window.event.keyCode : e.which;
	if (keyCode == 13) {
		// Call user-supplied hook
		try{
			window.event.srcElement.blur();
		} catch(e){
			//Ignore
		}
		func(context);
		// Disable further handling of this event
		if (IS_IE) {
			window.event.returnValue = false;
		} 
		else {
			return false;
		}
				
	}
}


function CreateNewXMLObj(cData){
	//Returns an XML Object with the passed XML Loaded
	var oSourceXML = document.all.RandomUse; // new ActiveXObject("Msxml2.DOMDocument"); // Create an XML object	
		
	try {		
	oSourceXML.loadXML(cData);				
	} catch(e) {
		alert('Error parsing XML: ' + oSourceXML.parseError.reason);
	}  // ignore errors

	return oSourceXML;

}

function UserGroupNewDialog(){
	var cURL='default.asp?class=UserGroup&Method=newdialogpage';
	return PopUp(cURL, 300, 600);
}

//*********************************************************************************/
// SELECT PARTS AFFECTED ADD WINDOW

function SelectPartAffectedAddWindow(cCallBack,aVals,nMode,cTitle){
	var cURL='default.asp?class=PartAffected&method=NewDialogPage&callback=' + cCallBack + '&Mode=' + nMode + '&Title=' + cTitle;
	var cResult=window.showModalDialog(cURL,aVals,"resizable:yes;dialogHeight:525px;dialogWidth:500px;help:no");
	if(cResult!=''){
		eval(cCallBack + '(' + cResult + ')');
	}
}

function SendEmailNotices(){
		try{
			var cSubject = document.all.DetailRecordset.selectSingleNode('record/subject').text;
		} catch(e){
			var cSubject = '';
		}
		var cURL = 'default.asp?class=email&method=DetailMessage&GUID=' + cGUID + '&subject=' + cSubject;
		var re=/#/g;
		var cURL=cURL.replace(re,'');						
		location.href(cURL);
	}


function ToggleClass(obj) {
	switch (obj.className) {
		case "inputView":
			obj.className = "inputEdit";
			break;
		case "inputViewRequired":
			obj.className = "inputEditRequired";
			break;
		case "inputEdit":
			obj.className = "inputView";
			break;
		case "inputEditRequired":
			obj.className = "inputViewRequired";
			break;
	}
}

function ToggleReadOnly(obj) {
	switch (obj.className) {
		case "inputView":
			obj.readOnly = false;
			break;
		case "inputViewRequired":
			obj.readOnly = false;
			break;
		case "inputEdit":
			obj.readOnly = true;
			break;
		case "inputEditRequired":
			obj.readOnly = true;
			break;
	}
}

function ToggleDisabled(obj) {
	switch (obj.className) {
		case "inputView":
			obj.disabled = false;
			break;
		case "inputViewRequired":
			obj.disabled = false;
			break;
		case "inputEdit":
			obj.disabled = true;
			break;
		case "inputEditRequired":
			obj.disabled = true;
			break;
	}
}

function hasDetailAccess(cRightName){
	try{
		oNode = document.all.RightsXML.selectSingleNode('detail/' + cRightName.toLowerCase());
		if(oNode!=null){
			if(oNode.text=='true'){
			  return true;
			} else {
			  return false;
			}
		} else {
			return true;
		}
	} catch(e){
		return true;
	}
}
function hasListEditAccess(cTabName,cRightName){
	try{
		var cRights=cTabName+"RightsXML";
		var cRightsXML = eval(document.all[cRights]);
		oNode = cRightsXML.selectSingleNode('detail/' + cRightName.toLowerCase());
		if(oNode!=null){
			if(oNode.text=='true'){
			  return true;
			} else {
			  return false;
			}
		} else {
			return false;
		}
	} catch(e){
		return false;
	}
}
function loadFrames(leftFrameURL,mainFrameURL) {
	eval(top.leftFrameMenu.location=leftFrameURL);
	eval(top.mainContent.location=mainFrameURL);
}


//********************************************************************************
//initARSecurity()
//	Loops through hgSECURE Elements and hides or shows based on access
//********************************************************************************
function initARSecurity(){
	var oElems = document.getElementsByName('hgSECURE');
	var cAttr = '';
	var oAttr;
	var bSet = false;
	try{
		for(var x=0; x<oElems.length; x++){
			try{
				oAttr = oElems[x];
				for(cAttr in oAttr){
					if(cAttr=="access"){
						bSet=false;								
						try{
							if(oAttr[cAttr] == "False"){
								//oElems[x].innerHTML = '';
								oElems[x].style.display='none';
								oElems[x].style.visibility='hidden';				
							}
							bSet=true;
						} catch(e){}
						try{
							if(!bSet){
								oElems[x].style.display=(oAttr[cAttr]=="True") ? '' : 'none';		
								oElems[x].style.visibility=(oAttr[cAttr]=="True") ? 'visible' : 'hidden';
							}
						} catch(e){}
					}
				}
			}catch(e){ alert(e.description); }
		}
	}catch(e){ alert(e.description); }
}
//********************************************************************************


//********************************************************************************
//SetupSecurityField()
//  Prepares the security level field by removing the levels that the user does
//    not have access too.
//********************************************************************************
function SetupSecurityField(oSecurityLevelIDElement){
	var cLevel = '1';
	
	try{
		if(document.all.DetailRecordset.selectSingleNode('record/securitylevelid').text == '')
			document.all.DetailRecordset.selectSingleNode('record/securitylevel').text = 'None';
	}catch(e) { /* Ignore */ }
	
	try{
		if(cUserSecLevel > ''){
			for(i = 0; i< cUserSecLevel.length; i++){
				if(cUserSecLevel.substr(i,1) == 0){			
					for(y = 0; y < oSecurityLevelIDElement.length; y++){
						if(cLevel == oSecurityLevelIDElement.options(y).value){
							try{
								oSecurityLevelIDElement.options.remove(y)
							}catch(e){
								//alert(e.description);
							}
						}
					}	
				}
				//increment counter
					cLevel = '0' + cLevel;
			}
		}else{
			var cLength = oSecurityLevelIDElement.length; 
			for(i=0; i < cLength - 2; i++){
				oSecurityLevelIDElement.options.remove(2);
			}	
		}	
	} catch(e){
		//
	}
}
//********************************************************************************



	// Add Notes - Supports the Write Only Fields
		/*function AddNotes(cField, cTitle){
			if(!bInEditMode){
				showEditMode(true,true);
			}
			var oDate=new Date();
			var AddNote = GetComments(cTitle,document.all.DetailRecordset.selectSingleNode('record/' + cField).text);
			if(AddNote!=null){
				var AddingNote='\n' + cUserName + ' - ' + formatDate(oDate,'MM/dd/yyyy hh:mm:ss a') + '\n' + AddNote + '\n';
				document.all.DetailRecordset.selectSingleNode('record/' + cField).text+=AddingNote;
				try{
					bDataChanged=true;
				} catch(e){
					//nothing
				}
			}
			return AddNote;
		}*/
		function AddNotes(cField, cTitle){
			m_cField = cField;
			m_cTitle = cTitle;

			if(!bInEditMode){				
				if(bLockDetailRecord){
					//mb:8/29/2003 - setup global Object for 3rd level callback
					oIFrameSupport = new IFrameSupport('AddNotesEditMode','AddNotesFail');
				}
				showEditMode(true,true);
				if(!bLockDetailRecord) AddNotesEditMode();
			}else{
				AddNotesEditMode();
			}
		}
		
		function AddNotesEditMode(){
			if(m_bEditMode){
				var oDate=new Date();
				var AddNote = GetComments(m_cTitle,document.all.DetailRecordset.selectSingleNode('record/' + m_cField).text);
				if(AddNote!=null){
					var AddingNote='\n' + cUserName + ' - ' + formatDate(oDate,'MM/dd/yyyy hh:mm:ss a') + '\n' + AddNote + '\n';
					document.all.DetailRecordset.selectSingleNode('record/' + m_cField).text+=AddingNote;
					try{
						bDataChanged=true;
					} catch(e){
						//nothing
					}
				}
				return AddNote;
			}
			oIFrameSupport = null;
		}
		
		function AddNotesFail(){
			oIFrameSupport = null;
			
		}		

	function HideBody(){
		document.body.style.visibility='hidden';
		document.body.style.display='none';
	}
	
	function ShowBody(){
		document.body.style.visibility='visible';
		document.body.style.display='';
	}
	
	function NodeAttribute(oNode, cAttribute, cDefault){
		
		if(!(cDefault!=null)) cDefault='';
		
		try{
			//First Try to Get Attribute using passed case
			var oAttribute = oNode.attributes.getNamedItem(cAttribute);
			if(oAttribute!=null){
				return oAttribute.text;
			}
		
		} catch(e){
			//Passed case failed so loop through attributes and test each one.
		}
			
		try{
			var cAttrib = cAttribute.toLowerCase();
			for(var x=0;x<oNode.attributes.length;x++){
				oAttribute = oNode.attributes.item(x);
				var cName = oAttribute.nodeName;
				cName = cName.toLowerCase();
				if(cName==cAttrib){
					return oAttribute.text;
				}		
			}
		} catch(e){
			//Ignore
		}
		
		//didn't find it return ''
		return cDefault;
	}
	
	function GetProperCaseAttribute(oNode, cAttribute){
	
		try{
			var cAttrib = cAttribute.toLowerCase();
			for(var x=0;x<oNode.attributes.length;x++){
				oAttribute = oNode.attributes.item(x);
				var cName = oAttribute.nodeName;
				cName = cName.toLowerCase();
				if(cName==cAttrib){
					return oAttribute.nodeName;
				}		
			}
		} catch(e){
			//Ignore
		}
	
	}
	
	function TerminateSession(nGUID)
	{

		if(confirm('Are you sure you want to terminate this User Session? \nWarning: If the user is currently logged in, they will be\nforced out of the system the next time their credentials\nare validated and it is possible that he/she may lose data.\nDo you want to proceed?')){
			UseXMLObj('default.asp?class=activeusersessions&method=terminatesession&guid=' + nGUID[0], 'TerminateSessionComplete');
		}
		
	}
	
	function TerminateSessionComplete()
	{
		if(XMLObj.selectSingleNode('response/result').text == 'False'){			
			ErrorDialog(XMLObj.selectSingleNode('response/error/root').xml);
			UseXMLObjComplete();
		}else{
			UseXMLObjComplete();		
			refreshList(true);
		}
	}
	
	function ViewDeletedRecord(cGUID)
	{
		window.open('default.asp?class=deleteditems&method=viewrecord&guid=' + cGUID, 'deleteditems', 'resizable=yes,scrollbars=yes,status=no,toolbar=no');
	}
	
	function ViewTrailRecord(cGUID)
	{
		window.open('default.asp?class=audittrails&method=viewrecord&guid=' + cGUID, 'audittrails', 'scrollbars=yes,statusbar=no,toolbar=no, height=400, width=600, resizable=yes');
	}
	
	function PurgeAll()
	{
		if(confirm('Are you sure you want to purge all records?\n**WARNING** All traceability for these records will be lost.')){
			UseXMLObj('default.asp?class=deleteditems&method=purgeall', 'PurgeAllComplete');
		}
	}
	
	function PurgeAllComplete()
	{
		if(XMLObj.selectSingleNode('response/result').text == 'False'){
			ErrorDialog(XMLObj.selectSingleNode('response/error/root').xml);
			UseXMLObjComplete();
		}else{
			UseXMLObjComplete();
			refreshList(true);
		}
	}
	
	function JS_Debug(cData){
		if(JS_Debug_Mode){
			try{
				var oDiv = DIV_JS_DEBUG;
			} catch(e){
				var oDiv = null;
			}
			if(oDiv==null){
				var oDiv = document.createElement('<div id="DIV_JS_DEBUG"></div>');
				document.body.insertAdjacentElement('BeforeEnd',oDiv);
				oDiv.style.backgroundColor='#EEEEEE';
				oDiv.style.borderStyle='dashed';
				oDiv.innerHTML='<b>DEBUG MODE</b><br>'
			}		

			oDiv.innerHTML = oDiv.innerHTML + cData + '<br>';
			
		}
	}
	
	function DoNothing(){
		//this function is used to do nothing from built in return points
		// do not delete
	}
	
	
//Apply's MaxLength for text area's
function maxlength(element, maxvalue)
     {
     var q = eval("document.all." + element + ".value.length");
     var r = q - maxvalue;
     var msg = "Sorry, you have entered "+q+" characters into the "+
       "text area box you just completed. It can return no more than "+
       maxvalue+" characters to be processed. Please abbreviate "+
       "your text by at least "+r+" characters";
     if (q > maxvalue){
      alert(msg);
      eval("document.all('" + element + "').focus()");
     }
      
}	
function LoadManagementAlertReference(oParam){
	var oXML = CreateNewXMLObj(oParam[1]);
	var cURL = 'default.asp?class=core&method=detailpage&guid=' + oXML.selectSingleNode('data/z:row').attributes.getNamedItem('referenceguid').text;
	document.location.href=cURL;
}

function PopUp(cURL, nHeight, nWidth) {
	return window.showModalDialog(cURL,'','resizable:yes;dialogHeight:' + nHeight + 'px;dialogWidth:' + nWidth + 'px;status:no;center:yes;help:no');
}


function AddToForm(oFormName,cElementName,cElementValue){
// appends to given form passed name & value
	var oElement = document.createElement("INPUT");
	oElement.id = cElementName;
	oElement.name = cElementName;
	oElement.type = "hidden";		
	oElement.value = cElementValue;
	oFormName.appendChild(oElement);
	oElement = null;		
}
	
function RemoveFromForm(oFormName,cElementName){
	try{
		var oElement = oFormName.elements(cElementName);
		oFormName.removeChild(oElement);
		oElement = null;
	}catch(e){}
}

function Stnd_Home_InitPage(){
	initARSecurity();      
	initLayout();	
	document.body.style.visibility='visible';	
}

function ShowReports(nSystemID){
	document.location.href="default.asp?class=report&method=ListPage&systemID=" + nSystemID;
}

function closeWindow(){
	window.close();
}






//*****************************	
//SYSTEM XML FUNCTIONS
//*****************************
function createXMLIsland(cName,cData){
	cName = 'XML_'+cName;
	var oXML = document.getElementById(cName);
	
	if(oXML==null){
		var oXML = document.createElement('<xml>');
		oXML.id = cName;
		document.body.appendChild(oXML);
	}
	oXML.loadXML(cData)
	return oXML;
}
	
function initSysXML(nSystemID){
	cSysXMLName = "Sys" + nSystemID;
	var oXML = document.all[cSysXMLName];
	if(oXML==null){
		oXML = document.createElement('<xml>');
		oXML.id = cSysXMLName;	
		document.body.appendChild(oXML);

		//eval(cSysXMLName + '.async=false');
		//eval(cSysXMLName + '.src="xml/client/' + nSystemID + '.xml"');

		

	//	var oXML = document.all[cSysXMLName];
	//	if(oXML.xml==''){
	//		alert("couldn't load system xml for SystemID: " + nSystemID);
	//	}
	
	
		var cPath = "xml/client/"+nSystemID+".xml";
		try{
			//make an XMLHTTP request to download file
			//Done this way to utilize client-side caching of files
			var oReq = new ActiveXObject("Microsoft.XMLHTTP");
			oReq.open("GET",cPath,false);
			oReq.send();
			
			//get just the root w/out the document type node
			//the document type causes a parse error
			var cXML = oReq.responseXML.documentElement.xml;
			oXML.async=false;
			oXML.validateOnParse = false;
			
			//attempt the load the responseXML into our newly created xml object
			if(!oXML.loadXML(cXML)){
				alert("couldn't load system xml for SystemID: " + nSystemID + '\n' + oXML.parseError.reason);
			}
		}catch(e){}
	
	
	
	}
	return oXML;
}

function GetAttr(oNode, cAttributeName, cDefault){
	var oAttr = oNode.attributes.getNamedItem(cAttributeName);
	if(oAttr!=null){
		return oAttr.text;
	} else {
		if(cDefault==null) cDefault = '';
		return cDefault;
	}
}

function FieldDefNode(nSystemID, cFieldID){
	var oXML = initSysXML(nSystemID);
	var oNode = oXML.selectSingleNode('hgXML/fielddefs/field[@id="' + cFieldID + '"]');
	if(oNode==null){
		return;
	} else {
		return oNode;
	}
	
}


var bFieldLayoutDefNodeErr = false;
function FieldLayoutDefNode(nSystemID, cFieldID){
	var oNode = FieldDefNode(nSystemID, cFieldID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('layoutdef');
		if(oSubNode==null){
			if (!bFieldLayoutDefNodeErr){
				alert("couldn't load field layout def node for " + cFieldID + " in System " + nSystemID);
				bFieldLayoutDefNodeErr=true;
			}
			return;
		}
		return oSubNode;
	} else {
		return;
	}
}

function FieldQueryDefNode(nSystemID, cFieldID){
	var oNode = FieldDefNode(nSystemID, cFieldID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('querydef');
		if(oSubNode==null){
			return;
		}
		return oSubNode;
	} else {
		return;
	}
}

var bTemplatesNodeErr = false;
function TemplatesNode(nSystemID){
	var oXML = initSysXML(nSystemID);
	var oNode = oXML.selectSingleNode('hgXML/templates');
	if(oNode!=null){
		return oNode;	
	} else {
		if(!bTemplatesNodeErr){
			alert("Unable to load Templates Node for " + nSystemID);
			bTemplatesNodeErr = true;
		}
		return;
	}
}

var bTemplateNodeErr = false;
function TemplateNode(nSystemID, cTemplateID){
	var oNode = TemplatesNode(nSystemID);
	if(oNode !=null){
		var oSubNode = oNode.selectSingleNode('template[@id="' + cTemplateID + '"]');
		if(oSubNode != null){
			return oSubNode;
		} else {
			if(!bTemplateNodeErr){
				alert("Unable to load template node for " + cTemplateID + " in System " + nSystemID);
				bTemplateNodeErr = true;
			}
			return;
		}
	}
}

var bTemplateLayoutNodeErr = false;
function TemplateLayoutNode(nSystemID, cTemplateID){
	var oNode = TemplateNode(nSystemID, cTemplateID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('layout');
		if(oSubNode!=null){
			return oSubNode;
		} else {
			if(!bTemplateLayoutNodeErr){
				alert("Unable to load Template Layout Node for " + cTemplateID + " in System " + nSystemID);
				bTemplateLayoutNodeErr = true;
			}
			return;
		}
	}
}

var bTemplateQueryNodeErr = false;
function TemplateQueryNode(nSystemID, cTemplateID){
	var oNode = TemplateNode(nSystemID, cTemplateID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('query');
		if(oSubNode!=null){
			return oSubNode;	
		} else {
			if(!bTemplateQueryNodeErr){
				alert("Unable to load Template Query Node for " + cTemplateID + " in System " + nSystemID);
				bTemplateQueryNodeErr = true;
			}
			return;
		}
	}
}

function ColumnDefNode(nSystemID, cColumnDefID){
	var oXML = initSysXML(nSystemID);
	var oNode = oXML.selectSingleNode('hgXML/columndefs[@id="' + cColumnDefID + '"]');
	if(oNode!=null){
		return oNode;
	} else {
		//alert("Unable to load Columndefs Node for " + cColumnDefID + " in System " + nSystemID);
		return;
	}
}

function TemplateLayoutColNode(nSystemID, cTemplateID, cFieldID){
	var oNode = TemplateLayoutNode(nSystemID, cTemplateID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('layoutcol[@id="' + cFieldID + '"]');
		if(oSubNode!=null){
			return oSubNode;		
		} else {
			//alert("Unable to load LayoutCol Node " + cFieldID + " in Template " + cTemplateID + " in System " + nSystemID);
			return;
		}
	}
}

function TemplateQueryColNode(nSystemID, cTemplateID, cFieldID){
	var oNode = TemplateQueryNode(nSystemID, cTemplateID);
	if (oNode!=null){
		
		var oSubNode = oNode.selectSingleNode('querycol[@id="' + cFieldID + '"]');
		if(oSubNode!=null){
			return oSubNode;
		} else {
			//alert("Unable to load QueryCol Node " + cFieldID + " in Template " + cTemplateID + " in System " + nSystemID);
			return;
		}

	}
}

function ColumnDefFieldNode(nSystemID, cColumnDefID, cFieldID){
	var oNode = ColumnDefNode(nSystemID, cColumnDefID);
	return oNode.selectSingleNode('columndef[@id="' + cFieldID + '"]');
}


function TemplateAttribute(nSystemID, cTemplateID, cAttribute, cDefault){
	var oNode = TemplateNode(nSystemID, cTemplateID);
	return GetAttr(oNode, cAttribute, cDefault);
}

function TemplateLayoutIdentity(nSystemID, cTemplateID){
	var oNode = TemplateLayoutNode(nSystemID,cTemplateID);
	var oSubNode = oNode.firstChild;
	var cID = GetAttr(oSubNode,'id','hgguid');
	return cID;
}

function TemplateLayoutAttribute(nSystemID, cTemplateID, cAttribute, cDefault){
	if(cAttribute=='identity'){
		return TemplateLayoutIdentity(nSystemID, cTemplateID);
	} else {
		var oNode = TemplateLayoutNode(nSystemID,cTemplateID);
		return GetAttr(oNode,cAttribute,cDefault);
	}
}

function ColumnDefFields(nSystemID, cColumnDefID){
	//Public Function for retrieving collection of fields in columndef
		var oNode = ColumnDefNode(nSystemID,cColumnDefID);
		var oArrayFields = new Array();
		for (var oField = oNode.firstChild; oField!=null; oField = oField.nextSibling){
			oArrayFields[oArrayFields.length] = oField.attributes.getNamedItem('id').text;
		}
		return oArrayFields;
}

function LayoutColAttribute(nSystemID, cTemplateID, cFieldID, cAttribute, cDefault){
	//Public Function for retrieving field attributes for a layout
		try{
			var cAttr = '';
	
			var oNode = TemplateLayoutColNode(nSystemID, cTemplateID, cFieldID);
			if(oNode!=null){
				cAttr = GetAttr(oNode, cAttribute, '');
			}
				
			if(cAttr!='') return cAttr;
		
			var cColumnDefID = TemplateAttribute(nSystemID, cTemplateID, 'columndefid', '');
			if(cColumnDefID!=''){
				var oNode = ColumnDefFieldNode(nSystemID, cColumnDefID, cFieldID);
				if(oNode!=null){
					cAttr = GetAttr(oNode, cAttribute, '');
					if(cAttr!='') return cAttr;
				}
			}	
		
			cAttr = FieldLayoutDefAttribute(nSystemID, cFieldID, cAttribute,'');
			if(cAttr!='') return cAttr;
		
			return FieldAttribute(nSystemID, cFieldID, cAttribute, cDefault);
		} catch(e){
			alert(nSystemID + ', ' + cTemplateID + ', ' + cFieldID + ', ' + e.description);
			return cDefault;
		}	
}

function QueryColAttribute(nSystemID, cTemplateID, cFieldID, cAttribute, cDefault){
	//Public Function for retrieving field attributes for a layout
		try{
			var cAttr = '';
	
			var oNode = TemplateQueryColNode(nSystemID, cTemplateID, cFieldID);
			if(oNode!=null){
				cAttr = GetAttr(oNode, cAttribute, '');
			}
				
			if(cAttr!='') return cAttr;
		
			var cColumnDefID = TemplateAttribute(nSystemID, cTemplateID, 'columndefid', '');
			if(cColumnDefID!=''){
				var oNode = ColumnDefFieldNode(nSystemID, cColumnDefID, cFieldID);
				if(oNode!=null){
					cAttr = GetAttr(oNode, cAttribute, '');
					if(cAttr!='') return cAttr;
				}
			}	
		
			cAttr = FieldQueryDefAttribute(nSystemID, cFieldID, cAttribute,'');
			if(cAttr!='') return cAttr;
		
			cAttr = FieldLayoutDefAttribute(nSystemID, cFieldID, cAttribute,'');
			if(cAttr!='') return cAttr;
		
			return FieldAttribute(nSystemID, cFieldID, cAttribute, cDefault);
		} catch(e){
			alert(nSystemID + ', ' + cTemplateID + ', ' + cFieldID + ', ' + e.description);
			return cDefault;
		}	
}


function FieldAttribute(nSystemID, cFieldID, cAttribute, cDefault){
	//<hgXML><fielddefs><field ATTR>
	var oNode = FieldDefNode(nSystemID,cFieldID);
	if(oNode!=null){
		return GetAttr(oNode, cAttribute, cDefault);
	} else {
		return cDefault;
	}
}


function FieldLayoutDefAttribute(nSystemID, cFieldID, cAttribute, cDefault){
	//<hgXML><fielddefs><field><layoutdef ATTR>
	var oNode = FieldLayoutDefNode(nSystemID, cFieldID);
	if(oNode!=null){
		return GetAttr(oNode, cAttribute, cDefault);
	} else {
		return cDefault;
	}
}

function FieldQueryDefAttribute(nSystemID, cFieldID, cAttribute, cDefault){
	//<hgXML><fielddefs><field><querydef ATTR>
	var oNode = FieldQueryDefNode(nSystemID, cFieldID);
	if(oNode!=null){
		return GetAttr(oNode, cAttribute, cDefault);
	} else {
		return cDefault;
	}
}

function GetApprovalSystemNode(nSystemID, cTemplateID){
	var oNode = TemplateNode(nSystemID, cTemplateID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('approvalsystem');
		if(oSubNode!=null){
			return oSubNode;
		}
	}
	return;
}

function GetStateSystemNode(nSystemID){
	var oXML = initSysXML(nSystemID);
	if(oXML!=null){
		var oNode = oXML.selectSingleNode('hgXML/states');
		if(oNode!=null){
			return oNode;
		}
	}
	return;
}

function GetStateNode(nSystemID, cStateID){
	var oNode = GetStateSystemNode(nSystemID);
	if(oNode!=null){
		var oSubNode = oNode.selectSingleNode('state[@id="' + cStateID + '"]');
		return oSubNode;
	} 
}

function GetStateAttribute(nSystemID, cStateID, cAttribute, cDefault){
	var oNode = GetStateNode(nSystemID, cStateID);
	if(oNode!=null){
		return GetAttr(oNode, cAttribute, cDefault);
	} else {
		return cDefault;
	}
}

function TemplateSaveURL(nSystemID, cTemplateID,cDefault){
	var oNode = TemplateNode(nSystemID, cTemplateID);
	var oSaveURLNode = oNode.selectSingleNode('listsaveurl');
	if(oSaveURLNode!=null){
		return unEncode(oSaveURLNode.text);
	} else {
		return cDefault;	
	}
}

function unEncode(cString){
	//replace all greater than signs
	if(cString.indexOf('&gt;') > -1){
		do{
			cString = cString.replace('&gt;', '>');
		}
		while (cString.indexOf('&gt;') > -1)
	}

	//replace all less than signs
	if(cString.indexOf('&lt;') > -1){
		do{
			cString = cString.replace('&lt;', '<');
		}
		while (cString.indexOf('&lt;') > -1)
	}
	
	//replace all single quotes	
	if(cString.indexOf('&apos;') > -1){
		do{
			cString = cString.replace('&apos;', '\'');
		}
		while (cString.indexOf('&apos;') > -1)
	}
	if(cString.indexOf('&amp;') > -1){
		do{
			cString = cString.replace('&amp;', '&');
		}
		while (cString.indexOf('&amp;') > -1)
	}
	
	return cString;
}
function GetQuantity(cTabID,fieldid,fieldname,partguid,fieldtype)
{
	
	try{
	var rslist = eval("rs"+cTabID);
	var sysxml = eval(cTabID+"SystemID");
	var olistxml = rslist.selectSingleNode("rs:data");
	 for(var i = 0 ; i < olistxml.childNodes.length ; i++)
	    {
	var currnode = olistxml.childNodes[i];
	  
	 //alert(currnode.xml)
	 var cpartguid = currnode.attributes[1].text;
	   
	   if(partguid == cpartguid)
	  {
		  
		 return currnode.attributes.getNamedItem(fieldname).text;
	  }
	 }
	 }
	catch(e)
	{
		switch(fieldtype)
		{
		case 'integer':	
		return 0;
		break;
		case 'string':
		return '';
		break;
		}
		alert(e.description);
	}
 }
//*****************************	
//SYSTEM XML FUNCTIONS END
//*****************************


//*****************************
//STATUS BAR FUNCTIONS
//*****************************

var oWin_Stat = new Array();

function SetDefaultStatus(cStat){
	window.defaultStatus=cStat;
}
function ClearDefaultStatus(){
	window.defaultStatus='Ready';
}

function AddStatus(cStat){
	if(window.status!=''){
		oWin_Stat.push(window.status);
	}
	window.status = cStat + ' . . .';
}

function ShowStatus(cStat){
	window.status = cStat;
}

function RemoveStatus(){
	if(oWin_Stat.length!=0){
		window.status = oWin_Stat.pop();
	} else {
		window.status = '';
	}
}

function ClearStatus(){
	oWin_Stat = new Array();
	window.status = '';
}

//*****************************
//STATUS BAR FUNCTIONS END
//*****************************
//******************************
//CONTEXT MENU FUNCTIONS START
//******************************
function displayMenu() {
	bCopyDisabled = true;
	bPasteDisabled = true;
	bItemsDisabled = false;
	bStateDisabled = false;
	DIVContextMenu.style.leftPos+=10;
	DIVContextMenu.style.posLeft=(event.clientX+document.body.scrollLeft);
	DIVContextMenu.style.posTop=(event.clientY+document.body.scrollTop);
	DIVContextMenu.style.display="";
	DIVContextMenu.setCapture();

	//test if user is in edit mode and if there is data in the clipboard
	try{
		if(window.clipboardData.getData > ''){
			enableAllMnuNamed('mnuPaste');
			bPasteDisabled = false;
		}else{
			disableAllMnuNamed('mnuPaste');
			bPasteDisabled = true;	   
		}
	}catch(e){}
	
	//test is user has only text selected
	if(document.selection.type == 'Text'){
		enableAllMnuNamed('mnuCopy');
		bCopyDisabled = false;
	}else{
		disableAllMnuNamed('mnuCopy');
		bCopyDisabled = true;
	}
	
	//verify that user is an admin
	if(!isAdmin()){		
		disableAllMnuNamed('mnuXML');
		disableAllMnuNamed('mnuSource');
		disableAllMnuNamed('mnuSysXML');
		bItemsDisabled = true;
	}
	
	//verify that user is actually logged in to the program
	if(CurrentUserInfo.xml==''){
	   disableAllMnuNamed('mnuState');
	   bStateDisabled = true;
	}else{
		bStateDisabled = false;
	}
}
function switchMenu() {   
   el=event.srcElement;
   if (el.className=="menuItem") {
      el.className="highlightItem";
	  var el2 = el.nextSibling;
	  if(el2!==null) el2.className = "highlightItem";
   } else if (el.className=="highlightItem") {
      el.className="menuItem";
	  var el2 = el.nextSibling;
	  if(el2!==null) el2.className = "menuItem";	  
   }
}
function GetCleanURL(){
    var CleanURL = document.location.href;
    if(CleanURL.indexOf('#')!=-1){
        CleanURL = CleanURL.substring(0,CleanURL.indexOf('#'));
    }
    return CleanURL;
}

function clickMenu() {
	DIVContextMenu.releaseCapture();
	DIVContextMenu.style.display="none";
	el=event.srcElement;
	switch(el.id){
		case 'mnuCopy':
			if(!bCopyDisabled){
				var oRange = document.selection.createRange();
				oRange.execCommand('Copy',false,oRange.text);
			}
			break;
		case 'mnuPaste':
			try{
				if(!bPasteDisabled){
					if(document.selection.type == 'Text' || document.selection.type == 'None'){						
						var oRange = document.selection.createRange();		
						var pe = oRange.parentElement();
						if(pe.tagName.toLowerCase() != 'body' && pe.isContentEditable){
							oRange.execCommand('Paste',false,window.clipboardData.getData('Text'));
						}
					}
				}
			}catch(e){ }
			break;
		case 'mnuRefresh':
			document.URL=GetCleanURL();
			break;
		case 'mnuState':
			if(!bStateDisabled){
				if(confirm('You will be deleting all your state information.\nThis will log you out and require you to re-login.\nAre you sure you want to continue?')){
					loadPage('default.asp?class=MyHQMS&method=ClearState');
				}
			}
			break;
		case 'mnuXML':
			if(!bItemsDisabled){
				if(isAdmin()){
					var cDat='';
					try{
						var cFrameName = window.frameElement.name;
					}catch(e){ var cFrameName = ''; }
					
					oWin = window.open('','_new');
					try{
						oWin.document.write('<html><body><textarea name="txtPage" cols="100" rows="30"></textarea></body></html>');
					}catch(e){
						alert('There is another support window already open.\nPlease close the other support window before you open another.');
						return;
					}
					try{
						if(cFrameName > ''){
							var oElems = top.frames(cFrameName).document.getElementsByTagName('xml');
						}else{
							var oElems = document.getElementsByTagName('xml');
						}
					}catch(e){
						var oElems = document.getElementsByTagName('xml');
					}finally{
						for(var x=0;x<oElems.length;x++){
							cDat += 'XML Object: ' + oElems[x].id + '\n';
							cDat += oElems[x].xml + '\n\n\n';
						}					
						oWin.document.all.txtPage.value = cDat;			
					}
				}
			}
			break;
		case 'mnuSource':
			if(!bItemsDisabled){			
				if(isAdmin()){
					try{
						var cFrameName = window.frameElement.name;
					}catch(e){ var cFrameName = ''; }
					
					oWin = window.open('','_new');
					try{
						oWin.document.write('<html><body><textarea name="txtPage" cols="100" rows="30"></textarea></body></html>');
					}catch(e){
						alert('There is another support window already open.\nPlease close the other support window before you open another.');
						return;
					}					
					try{
						if(cFrameName > ''){
							oWin.document.all.txtPage.value = top.frames(cFrameName).document.body.innerHTML;
						}else{
							oWin.document.all.txtPage.value = document.body.innerHTML;
						}
					}catch(e){
						oWin.document.all.txtPage.value = document.body.innerHTML;
					}
				}
			}
			break;
		case 'mnuSysXML':
			if(!bItemsDisabled){		
				if(isAdmin()){
					window.open('default.asp?class=systemxml&method=editsystem','_new');
				}
			}
			break;
   }
}

function isAdmin(){
	var bAdmin = false;
	if(cUserGroups==''){
		return false;
	}else{
		var oGroups = cUserGroups.split(';');
		for(var i=0; i<oGroups.length; i++){
			if(oGroups[i].toLowerCase()=='admin') bAdmin = true;
		}
		return bAdmin;
	}
}

function enableAllMnuNamed(cID){
	var oElem = document.getElementsByName(cID);
	for(var i = 0; i < oElem.length; i++){
		oElem[i].className = 'menuItem';
	}
}

function disableAllMnuNamed(cID){
	var oElem = document.getElementsByName(cID);
	for(var i = 0; i < oElem.length; i++){
		oElem[i].className = 'itemDisabled';
	}	
}
//***************************
//CONTEXT MENU FUNCTIONS END
//***************************
//*******************************
//RECORD LOCKING FUNCTIONS START
//*******************************

function LockRecord(cGUID){
	var cURL = 'default.asp?method=lockrecord&GUID=' + cGUID;
	document.all.XMLObj.async = false;
	document.all.XMLObj.src = cURL;
	document.all.XMLObj.async = true;
	var cResult = document.all.XMLObj.selectSingleNode('response/result').text;
	var cMsg = document.all.XMLObj.selectSingleNode('response/message').text;
	if(cResult == 'True'){
		return true;
	}else{
		alert(cMsg);
		return false;
	}
}

function UnlockRecord(cGUID){
	var cURL = 'default.asp?method=unlockrecord&GUID=' + cGUID;
	document.all.XMLObj.async = false;
	document.all.XMLObj.src = cURL;
	document.all.XMLObj.async = true;
	
	return true;
}

//****************************
//RECORD LOCKING FUNCTIONS END
//****************************

//error logging functions
function logerror(errnum,errtext)
{
	errorlog[errorlog.length]=errormsg(errnum,errtext);
}
function DisplayErrorLog()
{
	var bgcolor = new Array();
	var cHTML='';
	cHTML+="<body>";
	cHTML+="<div><table border=1 width=190 height=190><tr><td><center>";
	cHTML+="<div id=\"scrollobject\" STYLE=\"overflow: auto; width: 480px; height: 300;border-left: 1px gray solid; border-bottom: 1px gray solid;padding:0px; margin: 0px;vscroll:'true';background-color:'lavender'\"><table   id=\"tblerrorlog\" colspan=\"100%\">";
	if(errorlog.length<1)
	{
		cHTML+="<tr><td>There were no errors</td></tr>";
	}
	else
	{
	for(var i=0;i<errorlog.length;i++)
	{
		cHTML+="<tr style=\"background-color:'pink'\" colspan=\"100%\">";
		cHTML+="<td class=\"small\" colspan=\"20%\">"+errorlog[i].errnum+"</td>";
		cHTML+="<td class=\"small\" colspan=\"80%\">"+errorlog[i].errtext+"</td></tr>";
	}
	}
	cHTML+="</table></div></center></td></tr></table></div></body>";
	var opopup = window.createPopup();
	opopup.document.body.innerHTML=cHTML;
	opopup.show(100,100,200,200,document.body);
}	
