/*
'**********************************************************************************************************
' Copyright (c) Epic Systems Corporation 1999-2006
' Name: CommonUtils.js
' Author:
'
' Description: common Javascript functions for use across pages
'
' Revision History
' *mds 11/02 55100 use iframe or image object to call keepalive.asp
'                  instead of frame.
' *mds 11/02 56226 call intKeepalive to maintain session for host
'                  application when in integration mode
' *BShah 01/03 57836 added new function disableButton
' *BShah 02/03 59392 added warning popup in checkActivity if activity=0
' *BShah 03/03 59392  added in logout which closes popup window if its open
' *jmh 03/04 74205 selectCheckBox checks for null chkBoxGrp
' *kad 7/04 80943 add sLogoutPage
' *kad 10/04 84847 fix timeout issue
' *lt  11/04 84062 add function captureBackEnterKey to absort backspace/Enter key
' *sc  11/05 101038 use document.getElementById() to get id'd elements, instead of document.elementname format
' *mjk 11/05 102456 code to enable popup calendar
' *mjk 11/05 101140 selectAllCheckboxes()
' *bshah 12/05 102930 writeCalendar, IsValidDate and IsNumericMinMax
' *mjk 2/06 107384 enableIfChecked, to enable buttons only when at least one checkbox is checked
' *sc   4/06 108755 split off many functions into additional .js files
' *lgi 04/06 109199 added enableIfReqFilled and removeWhiteSpace
'**********************************************************************************************************
*/

	var activity = 0;
	var TRefreshID = "";
	var TSessionID = "";
	var mycKeepAliveCnt = 0;
	var submitcount=0;
	var newwindow;

	/* ***** 'what' is a frame name - The function checks to see if the frame exists ***** */
	function findFrame(what) {
		for (var i=0;i<parent.frames.length;i++) {
			if (parent.frames[i].name == what)
				return true;
		}
		return false;
	}


	/* *****  Functions checks to see if there's any activity on the page, and if there is keeps the session alive	***** */
	function checkActivity(RefreshTimeOut,SessionTimeOut,WarningPopup,sLogoutPage){  //*kad 7/04 80943 add sLogoutPage

	// *mds++ 55100 11/02 use of iframe or image object to hit server, removes need for frames.
	//	if (parent.frames.length != 0) {	// check to see if frames exist
	//		if (findFrame("HiddenFrame")) {	// check to see if the hidden frame exists
	//			if (activity == 1) {
	//			 window.clearTimeout(TSessionID);
	//			 parent.HiddenFrame.location.href="./keepalive.asp";		//refresh the hidden frame to keep session alive
	//			 activity = 0;
	//			 TRefreshID=window.setTimeout('checkActivity(' + RefreshTimeOut + ',' + SessionTimeOut + ',"' + WarningPopup +'");',RefreshTimeOut);
	//			 TSessionID=window.setTimeout('logOut();',SessionTimeOut);
	//			}
	//		}
	//	}
		//return true;

		var img;

		if (activity == 1) {
			mycKeepAliveCnt++;

			if (document.images){
				img = new Image();
				img.src = "./keepalive.asp?cnt=" + mycKeepAliveCnt;
				window.clearTimeout(TSessionID);
			}
			// *sc 1/06 101038 use object, not iframe, for xhtml compliance
			else if (document.getElementById('mycKeepAliveFrameIE')) {
				document.getElementById('mycKeepAliveFrameIE').data="./keepalive.asp";
			}
			//else if (window.frames['mycKeepAliveFrameIE']){		// use the iframe if it's available
			//	window.frames['mycKeepAliveFrameIE'].location.href="./keepalive.asp";
			//	window.clearTimeout(TSessionID);
			//}
			//else if (document.layers['mycKeepAliveFrameNN']){ 	// use the layer if it's available
			//	document.layers['mycKeepAliveFrameNN'].src = document.layers['mycKeepAliveFrameNN'].src
			//	window.clearTimeout(TSessionID);
			//}

			intKeepalive();

			activity = 0;
			TRefreshID=window.setTimeout('checkActivity(' + RefreshTimeOut + ',' + SessionTimeOut +  ',"' + WarningPopup + '","' + sLogoutPage + '");',RefreshTimeOut); //*kad 10/04 84847 add sLogoutPage
			TSessionID=window.setTimeout('logOut("' + sLogoutPage + '");',SessionTimeOut); //*kad 7/04 80943 add sLogoutPage
		}
		// if warning message has to be popup
		else if (WarningPopup.length>0) {
			newwindow = window.open('',"_blank","'toolbar=no,location=no,screenX=350,screenY=300,left=350,top=300,directories=no,status=no,menubar=no,resizable=no,width=370,height=110");
			if (!newwindow.opener) newwindow.opener = window;
			var threshold=SessionTimeOut-RefreshTimeOut;
			newwindow.document.write('<html><head>');
			newwindow.document.write('<script language="javascript">');
			newwindow.document.write('setTimeout("self.close();",' + threshold + ')');
			newwindow.document.write('</script>');
			newwindow.document.write('</head><title>Warning</title>');
			newwindow.document.write('<body onload="window.focus();" bgcolor="#ECE9D8" leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0">');
			newwindow.document.write('<center>');
			newwindow.document.write('<font face="arial" font size="2">' + WarningPopup + '</font>');
			newwindow.document.write('<p><font face="arial" font size="2">Do you want to maintain your session?</font>');
			newwindow.document.write('<form><table><tr>');
			newwindow.document.write('<td><input type="button" style="width:65" value="Yes" onClick="if(!opener.closed) {opener.activity=1; opener.checkActivity(' + RefreshTimeOut + ',' + SessionTimeOut + ',\'' + WarningPopup + '\',\'' + sLogoutPage + '\');} self.close()"></td>'); //*kad 10/04 84847 add sLogoutPage
			newwindow.document.write('<td><input type="button" style="width:65" value="No" onClick="if(!opener.closed) opener.logOut(\'' + sLogoutPage + '\'); self.close()"></td>'); //*kad 7/04 80943 add sLogoutPage
			newwindow.document.write('</tr></table></form>');
			newwindow.document.write('</center></body></html>');
		}
	}


	/* ***** Function that logs you out of the session ***** */
	function logOut(sLogoutPage){  //*kad 7/04 add sLogoutPage
		if(newwindow)
		{
			if(!newwindow.closed){
				newwindow.close();
			}
		}
            if ((sLogoutPage != "") && (sLogoutPage != null) && (sLogoutPage != "undefined")) {  //*kad+i 7/04 80943 use logout page if available, otherwise use old hardcoded page
			self.location.href = sLogoutPage;
		}
		else {  //use MyChart default
			self.location.href="./bye.asp";
		}
		//return true;
	}


	/* ***** Function that updates variable that there is some activity on the page ***** */
	function SetActivity(){
		activity=1;
		//return true;
	}

	function SetBlurActivity(){
		SetActivity();
		//return true;
	}

	/* ***** Function that recognizes a key press ***** */
	function HandleKeyPress(evt,o){
	 var lKeyCode;
	 if (navigator.appName!="Netscape") {
		 lKeyCode = window.event.keyCode;
	 } else {
		 lKeyCode = evt.which;
	 }

	 SetActivity();
	 return true;
	}

	/* ***** Function that checks the text of the 'sElement' to be less than or equal to 'lMaxLength' ***** */
	/* ***** IsKeyPress is boolean - optional param - when set we are looking for the key press event ***** */
	function CheckLength(sElement,lMaxLength,sErrorMsg,IsKeyPress) {
		var origLen;
		var sMessage;

		origLen=lMaxLength;
		if ((IsKeyPress!="") && (IsKeyPress!=null) && (IsKeyPress=="1")) {
			lMaxLength=lMaxLength-1
		}

		sMessage = sElement.value.replace(/\r\n/g,'')
		if (sMessage.length>lMaxLength) {
			if (sErrorMsg=="") {
				sErrorMsg = "Text may not exceed " + origLen + " characters. \n";
			}
			alert(sErrorMsg);
			sElement.focus();
			return false;
		}
		return true;
	}


	/* ***** Function that recognizes a key press and also checks the text of the 'sElement' to be less than or equal to 'lMaxLength' ***** */
	function HandleKeyPressAndMaxLen(evt,sElement,lMaxLength,sErrorMsg){
		var lKeyCode;
		if (navigator.appName!="Netscape") {
		 lKeyCode = window.event.keyCode;
		} else {
		 lKeyCode = evt.which;
		}
		SetActivity();
		if ((lKeyCode == 8) || (lKeyCode == 0)) { //forgive backspace
			return true;
		} else {
			return CheckLength(sElement,lMaxLength,sErrorMsg,1);
		}
	}

	/* ***** Function that recognizes a blur event and also checks the text of the 'sElement' to be less than or equal to 'lMaxLength' ***** */
	function HandleBlurAndMaxLen(evt,sElement,lMaxLength,sErrorMsg){
		return HandleKeyPressAndMaxLen(evt,sElement,lMaxLength,sErrorMsg);
	}

	/* ***** Function that recognizes a key press and also checks the text of the 'sElement' to be less than or equal to 'lMaxLength' ***** */
	function HandleOnChangeAndMaxLen(sElement,lMaxLength,sErrorMsg){
		SetActivity();
		return CheckLength(sElement,lMaxLength,sErrorMsg);
	}




	/* ***** 'onLoad' fn. for the BODY tag of the inside page **** */
	function insideBodyLoad(sRefreshTimeout, sSessionTimeout, sWarningPopup, sTitle, sLogoutPage){ //*kad 7/04 80943 add sLogoutPage
		var sTimeoutParams
		sTimeoutParams='checkActivity(' + sRefreshTimeout + ', ' + sSessionTimeout + ',"' + sWarningPopup + '","' + sLogoutPage + '");'  //*kad 7/04 84847 add sLogoutPage
		TRefreshID=window.setTimeout(sTimeoutParams, sRefreshTimeout);
		TSessionID=window.setTimeout('logOut("' + sLogoutPage + '");', sSessionTimeout); //*kad 7/04 80943 add sLogoutPage
		top.document.title=sTitle;
		window.focus();
		return true;
	}




   /******** 'Function to get data from a single/array of objects' ********************************/
   function getObjectValue(obj) {
   	   var objLen,i,objValue

   	   objLen = 0;
   	   objLen = obj.length;
       objValue = "";
   	   if (objLen>0) {
   		   for(i=0;i<objLen;i++){
   			   objValue = objValue + obj[i].value;
   		   }
   	   }
   	   else {
   		   objValue=obj.value;
   	   }
   	   return objValue;
	}



	/* ***** Function to get keypress event to work for Netscape ***** */
	function doMainKeyPress(e) {
		return routeEvent(e)

	}
	if (navigator.appName=="Netscape") {
		window.captureEvents(Event.KEYPRESS)
		window.onkeypress=doMainKeyPress
	}

	//element.form.submitform.click()

	/* ***** Functions for Scheduling and Other Preferences page to submit the form when the user hits the 'Enter' key ***** */
	function submitForm(element) {
		if (element.form.submitcontrol.value=='submit form'){
			element.form.submitform.click();
			return false;
		//} else {
			//should add time to table
		}
	}
	function addFocus(element) {
		element.form.submitcontrol.value='nosubmit'
		return true;
	}
	function taKeyDown(element) {
		element.form.submitcontrol.value='nosubmit';
	}
	function recordKey(element) {
		if ((window.event.keyCode==13)&&(element.submitcontrol.value!='nosubmit')) {
			element.submitcontrol.value="submit form";
		} else {
			element.submitcontrol.value="";
		}
	}


	/* this function can be used to make sure that 'text' string does not have spaces in it
			returns true if space is found else returns flase */

  function containsSpace(text){
		for (var i=0; i<text.length; ++i) {
			if (text.charAt(i) == " ") return true;
		}
		return false;
	}


	/*sc 12/05 101038 now this checks for all invalid characters */
  function containsPunctuation(text){
		var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@._-";
		var utext = text.toUpperCase();
		for (var i=0; i<utext.length; ++i) {
			var ch = utext.charAt(i);
			if (validChars.indexOf(ch) < 0) return true;
		}
		return false;
	}


	/* this function can be used to pass a checkbox group and it alerts the user if atleast one has not been checked */
  /* returns true if atleast one checkbox has been checked else returns false */
	function selectCheckBox(chkBoxGrp){
      if ((chkBoxGrp!=null) && (document.all||document.getElementById)){
		for (var i=0; i < chkBoxGrp.length;i++){
			if (chkBoxGrp[i].checked==true) return true;
		}
		if (chkBoxGrp.checked==true) return true;    // cases where only one box in group

		alert("At least one checkbox must be checked");
		return false;
      }
      return true;
	}

	/* this function disables button after it is clicked second time and during second time it returns false so that
		so that form is not submited */
	function disableButton(formObj){
		if (submitcount==0){
			submitcount++;
			return true;
		}
		else{
			formObj.disabled=true;
			return false;
		}
	}

	/*
	/ Description: Enables the list of buttons (btns) if all input fields (nfo) are satisfied 
  / Inputs     : 	frmID- the id of the form to check
	/               btns - "^" delimited list of button names to disable/enable
	/     [arglist] nfo  - string formatted as "FormName^DisplayName^Key"
	/ Notes      : The key is used as a group ID. If one field within the KEY is filled,
	/							 then that satisfies the requirement for that whole group. See MedAdvice
	*/
	function enableIfReqFilled(frmID,btns) {
	  if (!document.getElementById) {return; }
		var frm,i,arr,errs,verify,name,disp,key,errCnt,input,list;
		frm=document.getElementById(frmID);
		if(!frm){ return; }
		list=btns.split("^");
		if(!list || list.length==0){ return; }
		var args=enableIfReqFilled.arguments;
		verify = new Array();
		errs   = new Array();
		errCnt=0;
	 	for(i=2;i<args.length;i++){
			arr   = args[i].split("^");
			name  = arr[0];
			disp  = arr[1] || name;
			key   = arr[2] || name;
			input = frm[name];
			if( input && !(verify[key]) ) {
				if( removeWhiteSpace(input.value).length == 0 ) {
					if(!errs[key]){	
						errs[key]=true; 
						errCnt++;				
					}
				}else{
					verify[key]=true;
					if(errs[key]){
						errs[key]=false;
						errCnt--;
					}
				}
			}
		}
		if( errCnt>0 ){
			for(i=0;i<list.length;i++){
				disableBtn(frm[list[i]]); 
			}
		}else{ 
			for(i=0;i<list.length;i++){
				enableBtn(frm[list[i]]); 
			}
		}
	}

	/* removes all whitespace from a string */	
	function removeWhiteSpace(txt){
		var str = ""+txt;
		str = str.replace(/\W/g,"");
		return str;
	}

	/* this function confirms whether user wants to delete messages or not*/
	function confirmDelete(sMessage){
			if(confirm(sMessage) == true) return true;
			return false;
	}

	// Set all checkboxes on a page.  Used in test results.
	//*mjk 11/05
	function setAllCheckboxes(master) {
		var value = master.checked;
		var list = document.getElementsByTagName("input");
		var n,ipt;
		for (n = 1; n < list.length; n++) {
			ipt = list[n];
			if (!ipt.getAttribute) { continue; }
			if (ipt.getAttribute("type") != "checkbox") { continue; }
			ipt.setAttribute("checked", value);
			ipt.checked = value;
		}
	}

	/*
	'-----------
	'Description: Write a select all button that will check all check boxes
	'             in the given form and checkbox group
	'Parameters: formname  - the name of the form
	'            groupname - the name of the checkbox group (NYI)
	'-----------
	*/
	function writeSelectAllButton(formname,groupname){
	  if( typeof(document)=='object' &&
	      formname != null &&
	      groupname != null &&
	      document.getElementById &&
	      typeof(document.getElementById(formname))=='object'){

	      document.write('<input class="button" onclick="checkAll(\'' + formname + '\',\'' + groupname + '\'); return false;" type="button" value="Select All" />')
	  }
	}
	/*
	'-----------
	'Description: Check all the check boxes in the given form and checkbox group
	'Parameters: formname  - the name of the form
	'            groupname - the name of the checkbox group (NYI)
	'-----------
	*/
	function checkAll(formname,groupname){
	  if( typeof(document)=='object' &&
	      formname != null &&
	      groupname != null &&
	      document.getElementById &&
	      typeof(document.getElementById(formname))=='object'){
	      var form = document.getElementById(formname);
	      var element,index=0;
	      while( element = form[index++] ){
	        if(element.type=='checkbox'){
	          element.checked = true;
	        }
	      }
	  }
	}


     function selectRadioButton(radButGrp){
 		if (document.all||document.getElementById){
 		  for (var i=0; i < radButGrp.length;i++){
		 	if (radButGrp[i].checked==true) return true;
		  }
		  if (radButGrp.checked==true) return true;    // cases where only one box in group

		  alert("Please make a selection before submitting.");
		  return false;
	    }
	    return true;
	}
    // use this to disable a button on a form. Call from the onsubmit event of a form.
    // there is another diableButton so small change in name.
	function disableButton1(oButton){
		if (typeof(oButton)=='object'){
			oButton.disabled=true;
		}
		return true;
	}


	var browser,version,total,thestring,place;
	function checkIt(agent,string){
		place = agent.indexOf(string) + 1;
		thestring = string;
		return place;
	}

	/* this is used to make the surrounding page match the current page */
	// IE: frames["mychartframe"].document.body.scrollHeight
	// OTHER: frames["mychartframe"].document.body.offsetHeight
	// Must launched on the body onload event handler for IE
	// Use document.documentElement if you are in Compat mode
	function dataTileLoad() {
		var agent = navigator.userAgent.toLowerCase();
		var isIE,isOpera,isWebKit,container;
		var sHeight,oHeight,iHeight;
		if (checkIt(agent,'konqueror')){       browser = "Konqueror"; }
		else if(checkIt(agent,'safari')){      browser = "Safari"; isWebKit=true; }
		else if(checkIt(agent,'omniweb')){     browser = "OmniWeb"; isWebKit=true;  }
		else if(checkIt(agent,'opera')){       browser = "Opera"; isOpera=true; }
		else if(checkIt(agent,'webtv')){       browser = "WebTV"; }
		else if(checkIt(agent,'icab')){        browser = "iCab"; }
		else if(checkIt(agent,'msie')){        browser = "Internet Explorer"; isIE=true; }
		else if(!checkIt(agent,'compatible')){ browser = "Netscape Navigator"; version = agent.charAt(8); }
		else{                                  browser = "Unknown"; }
		if (!version) version = agent.charAt(place + thestring.length);

		if( !parent || !parent.document || !window || !window.name){ return; }
		else if( parent.document.getElementById ){
			container = parent.document.getElementById(window.name);
		}else if( parent.document.all ){
			container = parent.document.all[window.name];
		}else{ return; }
		if( !container || !document || !document.body || !container.style || (typeof('container.style.height')=='undefined') ){ return; }

		if(isIE){
			iHeight = document.body.scrollHeight;
			container.style.height = iHeight + 16 +'px'; // account for possible horizontal scroll bar
		}else if(isWebKit){
			window.setTimeout('resizeWebKit("' + window.name +'");',250);
		}else if(isOpera){
			sHeight = (typeof(document.body.scrollHeight) != 'undefined' ? document.body.scrollHeight : 200);
			oHeight = (typeof(document.body.offsetHeight) != 'undefined' ? document.body.offsetHeight : 200);
			iHeight = (sHeight <= oHeight ? oHeight : sHeight); //max of the two measurements
			container.style.height = iHeight + 16 + 'px'; // plus some padding
		}else{
			container.style.height = 150 + 'px';
			sHeight = (typeof(document.body.scrollHeight) != 'undefined' ? document.body.scrollHeight : 200);
			oHeight = (typeof(document.body.offsetHeight) != 'undefined' ? document.body.offsetHeight : 200);
			iHeight = (sHeight <= oHeight ? oHeight : sHeight); //max of the two measurements plus some padding
			sHeight =  (typeof(document.documentElement.scrollHeight) != 'undefined' ? document.documentElement.scrollHeight : 0);
			iHeight = (sHeight <= iHeight ? iHeight : sHeight); //max of the two measurements
			container.style.height = iHeight + 16 + 'px'; // plus some padding
		}
	}

	/*
		Helper function to resize iframe
		used to work around timing issues in Apple WebKit-based browsers (mostly Safari)
	*/
	function resizeWebKit(sName)
	{
		if(document.getElementById) {
			var container,iHeight;
			container = parent.document.getElementById(sName);
			iHeight = document.body.scrollHeight;
 			container.style.height = iHeight + 16 +'px';
		}
	}

	/*
	'-----------
	'Description: checks whether the string is numeric or not
	'Parameters: strText - the string to check
	'            allowneg - whether to allow negative values or not
	'-----------
	*/

	function IsNumeric(strText,allowneg)
	//  check for valid numeric strings
	{
		var Result = true;
		var calcResult = parseFloat(strText);
		if (isNaN(calcResult))
		{
		  Result = false;
		}
		else
		{
		  if (allowneg==false)
		  {
		    if (calcResult<0)
		    {
		      Result = false;
		    }
		  }
		}
	   return Result;
	 }

	/*
	'-----------
	'Description: redirects to bye.asp. Used from 'Log Out'.
	'-----------
	*/
	function DoRedirect()
	{
		this.document.write('<br /><br /><br /><br /><center>You are being logged out</center>');
		window.location='./bye.asp';
		return false;
	}

	/*
	'-----------
	'Description: redirects to oebye.asp. For BannerOEPostLogin.html.
	'-----------
	*/
	function DoRedirectOE()
	{
		this.document.write('<br /><br /><br /><br /><center>You are being logged out</center>');
		window.location='./oebye.asp';
		return false;
	}
	/*
	'-----------
	'Description: validates file path and extension.
	'-----------
	*/
	function FileValidation()
	{
		if(document.getElementById) {
			var extension=document.getElementById("flowsheetform").datafile.value;
			var fileLength=extension.length
			if (fileLength==0)
			{
				alert('Please select a file before accepting.');
				return false;
			}
			extension=extension.substring((fileLength-3),fileLength);
			extension=extension.toLowerCase();
			if ((extension!="txt") && (extension!="xml"))
			{
				alert('You have selected a .' + extension + ' file. Please select a .xml or .txt file.');
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	/*
	'-----------
	'*lt+function 11/04 84062 add function to absort backspace/Enter key
	'Description: This function capture the backspace and enter for IE.
	'             The backspace will be ignored if not in text/text area/password field
	'	      The enter key will be ignored if not in text area/submit button
	'-----------
	*/

	function captureBackEnterKey() {
		SetActivity();
		if (window.event && ((window.event.keyCode == 8) || (window.event.keyCode == 13))) {
			var Elem=window.event.srcElement;
			var ElemFiringBS=Elem.type;
			if (!Elem.readOnly) {
				if ((ElemFiringBS == "text" || ElemFiringBS=="textarea" ||ElemFiringBS=="password") && (window.event.keyCode == 8)){
					return ;
				}
				if ((ElemFiringBS=="textarea" || ElemFiringBS=="submit") && (window.event.keyCode == 13)){
					return ;
				}

			}
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return false;
		}
	}


	function showItem(objID){
	  var tblObj;
	  if (document.getElementById){
	    tblObj=document.getElementById(objID);
	  }
	  else {
	    if (document.all) {
	      tblObj=document.all.item(objID);
	    }
	  }
	  if (tblObj != null){
	    tblObj.style.display="block";
	    return true;
	  }
	  return false;
	}

	function hideItem(objID){
	  var tblObj;
	  if (document.getElementById){
	    tblObj=document.getElementById(objID);
	  }
	  else {
	    if (document.all) {
	      tblObj=document.all.item(objID);
	    }
	  }
	  if (tblObj != null){
	    tblObj.style.display="none";
	    return true;
	  }
	  return false;
	}

/* Enable btns if any checkbox in a form is checked.
  Call with arguments formID, btnID, btnID, ... */
function enableIfChecked(formID) {
  if (!document.getElementById) {return; }
  var cb, btn, frm;
  var btns = new Array();
  var frm = document.getElementById(formID);
  if(!frm) { return; }
  var args = enableIfChecked.arguments;
  for(var i = 1; i < args.length; i++) {
      btn = document.getElementById(args[i]);
      if (btn) { btns.push(btn); }
  }
  var inp = frm.getElementsByTagName('input');
  var checked = false;
  for(var x = 0; x < inp.length; x++) {
     cb = inp[x];
     if(cb.type != 'checkbox') { continue; }
     if(cb.className.toLowerCase().indexOf('hidden') != -1) { continue; }
     if(cb.checked) {
         checked = true;
         break;
     }
  }
  for (var i in btns) {
    btn = btns[i];
    if(checked) {
      enableBtn(btn);
    } else {
      disableBtn(btn);
    }
  }
}

function enableBtn(btn) {
   if(btn && btn.removeAttribute) {
      btn.removeAttribute('disabled');
      btn.className = btn.className.replace(/\ ?disabled/, '');
   }
}
function disableBtn(btn) {
   var ds = 'disabled';
   if(btn) {
      btn.disabled = ds;
      if(btn.className.indexOf(ds) == -1) {
          btn.className = btn.className.replace(/\ *$/, '');
          if(btn.className.length > 0) { ds = ' ' + ds; }
          btn.className = btn.className + ds;
      }
   }
}

function getElementPosition(elem, container){
	if(!elem.offsetParent) { return; }
	var currentElement = elem;
	var left = 0;
	var top = 0;
	var chain = "";
	var topElement;
	while (currentElement){
	  topElement = currentElement;
	  if(currentElement.offsetParent && currentElement.offsetParent.tagName == "HTML") { break; }
	  if(container && currentElement == container) { break; }
	  left += currentElement.offsetLeft;
	  top += currentElement.offsetTop;
	  if (currentElement.scrollLeft) {
		left -= currentElement.scrollLeft;
	  }
	  if(currentElement.id.toLowerCase() == "wrap") {
	  left -= currentElement.offsetLeft;
	  top -= currentElement.offsetTop;
		break;
	  }
	  currentElement = currentElement.offsetParent;
	}


	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
	  left += document.body.leftMargin;
	  top += document.body.topMargin;
	}
	left += "px";
	top += "px";
	if (topElement.tagName == "HTML") {  // if we got all the way here, roll back to the body element
	topElement = topElement.getElementsByTagName("body")[0];
	if(topElement.offsetLeft) left -= topElement.offsetLeft;
	if(topElement.offsetTop) top -= topElement.offsetTop;
	}
	return {x:left, y:top, topElement:topElement};
}

	/**** PAMF Added Javascripts ***/

	/* Pop up new window */
	function popUpWindow(url, name, attributes)
	{
		window.open(url,name, attributes);
	}

	function Set_Cookie(name,value)
	{ 
		document.cookie = name + '=' + escape(value) ;
		return true;
	} 
	function Get_Cookie(name) 
	{
  		var start = document.cookie.indexOf(name + '=');
  		var len = start + name.length + 1;
  		if ((!start) && (name != document.cookie.substring(0,name.length)))
    			return "";
  		if (start == -1)
    			return "";
  		var end = document.cookie.indexOf(';',len);
  		if (end == -1) end = document.cookie.length;
  			return unescape(document.cookie.substring(len,end));
	}


	function SetCookiesForLinks(mode, strLink)
	{
		var cnt,len,prvlink,nxtlink,links,pos,page;
		cnt=0;
		prvlink="";
		nxtlink="";

		//Count onclick links in <tr>
		links = document.getElementsByTagName("tr")
		len= links.length;
		do 
		{
			url=links[len-1].onclick;
			//alert("url->" + url);
			if ((url != null) && (url.toString().indexOf(strLink))>=0) cnt=cnt+1;
			len--;
		}
		while (len>0);
		
		//check prv and nxt links
		len=document.links.length;
		windowURL=window.location.href
		windowPos=windowURL.indexOf("pg=")
		if (windowPos>=0)
		{
			curPage=windowURL.substring(windowPos+3,windowURL.length); 
		}
		else
		{
			curPage="1"
		}
		do
		{
			url=document.links[len-1].search;
			pos=url.indexOf("pg=")
			if (pos>=0) 
			{
				page=url.substring(pos+3,url.length); 
				if (parseInt(page) > parseInt(curPage)) nxtlink=document.links[len-1].href;
				if (parseInt(page) < parseInt(curPage)) prvlink=document.links[len-1].href;

			}
			len--;
		}
		while (len>0);

		//alert("prvlink->" + prvlink);
		//alert("nxtlink->" + nxtlink);
		//alert("cnt->" + cnt);
		Set_Cookie(mode + "prvlink",prvlink);
		Set_Cookie(mode + "nxtlink",nxtlink);
		Set_Cookie(mode + "total",cnt);
	}

	/* Add Prev/Next link */
	function AddPrevNextLinks(mode, param, linkName)
	{

		var url,pos;
		url=window.location.href;
		pos=url.indexOf("donotshow=");
		if ((pos == -1) && (url.indexOf("printmode=true") == -1))
		{

			var totnum,index;
			var page,path,pnlink;

			totnum=parseInt(Get_Cookie(mode + "total"));
			path=window.location.pathname;
			pos=url.indexOf(param);
			
			index=parseInt(url.substring(pos+param.length,url.length));
			pnlink=Get_Cookie(mode + "prvlink");
			document.write('<table cellpadding="3" cellspacing="0" border="0" width="100%"><tr><td class="plain" align="right">');
			if (index>1) document.write('<a href="'+url.substring(0,pos)+param+(index-1)+'">Previous ' + linkName + '</a>&nbsp;');
			else {
			if (pnlink!="") document.write('<a href="'+pnlink+'">Previous ' + linkName + '</a>&nbsp;');}

			pnlink=Get_Cookie(mode + "nxtlink");

			if (index<totnum) document.write('<a href="'+url.substring(0,pos)+param+(index-1+2)+'">Next ' + linkName + '</a>&nbsp;');
			else {
			if (pnlink!="") document.write('<a href="'+pnlink+'">Next ' + linkName + '</a>&nbsp;');}

			document.write('</td></tr></table>');
		}
	}
	/***** For Risk Calculator ***/
	var flag = true;
	var t;

	function increase(field, interval)
	{
		field.value = (field.value*10 + interval*10)/10;
		if (flag) 
		{
			var incFunc = "increase(document.forms[0]." + field.name + ", " + interval + ")";
			t = setTimeout(incFunc, 200);
		}
	}


	function decrease(field, interval)
	{
		field.value = (field.value*10 - interval*10)/10;
		if (flag) 
		{
			var decFunc = "decrease(document.forms[0]." + field.name + ", " + interval + ")";
			t = setTimeout(decFunc, 200);
		}
	}

	function recalculate(low, high, field)
	{
		clearTimeout(t);
		flag = false;
		if (validate(low, high, field) == 2)
		{
			alert("Please enter a number between " + low + " and " + high)
			field.focus();
			field.select();
			return false;
		}
		if (validate(low, high, field) == 1)
		{
			alert("Please enter a valid number!")
			field.focus();
			field.select();
			return false;
		}
		field.form.method = "post";
		field.form.submit();
		return false;
	}

	function checkEnter(e, low, high, field){ 
		var characterCode;
		if(e && e.which){ 
			characterCode = e.which; 
		}else{
			characterCode = e.keyCode; 
		}

		if(characterCode == 13){ 
			if (validate(low, high, field) == 2)
			{
				alert("Please enter a number between " + low + " and " + high)
				field.focus();
				field.select();
				return false;
			}
			if (validate(low, high, field) == 1)
			{
				alert("Please enter a valid number!")
				field.focus();
				field.select();
				return false;
			}
			field.form.submit();
			return false ;
		}
		else{
			return true; 
		}
	} 
	/* 1 - not number; 2 - not in range; 0 - valid number */
	function validate(min, max, field1)
	{	
		if (isNaN(field1.value))
			return 1;
		if (field1.value < min)
			return 2;
		if (field1.value > max)
			return 2;
		return 0; 
	}
	function calculate(low, high, field)
	{
		if (validate(low, high, field) == 2)
		{
			alert("Please enter a number between " + low + " and " + high)
			field.focus();
			field.select();
			return false;
		}
		if (validate(low, high, field) == 1)
		{
			alert("Please enter a valid number!")
			field.focus();
			field.select();
			return false;
		}
		field.form.submit();
		return true; 
	}
	function resetRiskValue(form)
	{
		form.firstTime.value = "Yes"
		form.submit();
		return true; 
	}
	function chooseStyle(title, days){ 
		if (document.getElementById)
		{
			setStylesheet(title)
			setCookie("parxsheet", title, days)
		}
	}

	function setCookie(name, value, days) {
		var expireDate = new Date()
		//set "expstring" to either future or past date, to set or delete cookie, respectively
		var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5)
		document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
	}

	function setStylesheet(title)
	{
		var i, cacheobj, altsheets=[""]
		for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) {
			if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title
				cacheobj.disabled = true
				altsheets.push(cacheobj) //store reference to alt stylesheets inside array
				if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter
					cacheobj.disabled = false //enable chosen style sheet
			}
		}
	}

	function indicateSelected()
	{
		var selectedtitle=getCookie("parxsheet")
		if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored
			setStylesheet(selectedtitle)
	}
	
	function getCookie(Name) { 
		var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	}

	/* Suppress 'Change Component selection' and Back buttons*/
	function SuppressButtons()
	{
		var url,pos;
		url=window.location.href;
		pos=url.indexOf("donotshow=");
		if(pos > 0) 
		{
			document.forms[1].style.visibility = "hidden";
			document.write("<style>.back { display: none;} </style>");
			document.write("<div class='SHback'>");
			document.write("<a class='button' href='inside.asp?mode=resltsum' title='Back'>Back to the Test Result Summary</a>");
			document.write("</div>");
			
		}
		
	}
