	<!--

var popupTarget;
var popupID;
var popupModifier;
var lastPopup = 0;
var PWindow;
var TPNextPos = 1;
var onload_actions = new Array();
var default_actions = new Array();
var delete_actions = new Array();
var kb_actions = new Object();

var nonDataSuffix;
var d = document;

//regCodes = new Array(/\\\\d/ig,/\(/ig,/\)/ig, /\?/ig, /\*/ig);
//myCodes = new Array("#", "", "", "", "", "");

//checkRegCodes = new Array(/\\\\d/ig, /\?/ig, /\*/ig);
//checkMyCodes = new Array("#", "", "", "");

var calcItems;
var regColsRows = /(SUM\(|=)*\s*(\w+[\s\w]*)\[([^!\d#\s]*)(#?)([!\d]*)(:?)([^!\d#\s]*)(#?)([!\d]*)\]\)*/i;
var valColsRows = new Array('all', 'operation', 'tableName', 'column', 'numberSign', 'row', 'colon', 'column2', 'numberSign2', 'row2');

var newStyleUpdate=false;
var ssError = false;
var start, end;
var frmUpdate;
var inputCatalog;
//onload_actions.push("alert('!' + getElementByName('Display All Text'))");
tabs_ = new Object();
function checkTab(obj) {
	if (event.keyCode != 9) return true;
	if (!obj.getAttribute('ts')) return true;
	var target_tabs = tabs_[obj.getAttribute('ts')];
	if (!target_tabs) return true;
	//window.status = target_tabs.length;
	
	for (var j=0; j < target_tabs.length; j++) {
		//window.status = window.status +  '|' + (!obj.name) + '{' + obj.getAttribute('tab')  + '}' + target_tabs[j][0] + '|';
		if ((obj.name && obj.name == target_tabs[j][1]) || (!obj.name && obj.getAttribute('tab') == target_tabs[j][0])) {
			//window.status = window.status + 'f' + j;
			if (event.shiftKey) {
				if (j == 0) {
					try {target_tabs[target_tabs.length-1][2].focus();} catch (e) {return true;}
					window.event.returnValue = false;
					window.event.cancelBubble = true;
				} else if (target_tabs[j-1]) {
					try {target_tabs[j-1][2].focus();} catch (e) {return true;}
					if (target_tabs[j-1][2].getAttribute('button') == 'true') target_tabs[j-1][2].setAttribute('ts', obj.getAttribute('ts'));
					
					window.event.returnValue = false;
					window.event.cancelBubble = true;
					return false;
				}
			}
			else { 
				if (j == target_tabs.length-1) {
					try {target_tabs[0][2].focus();} catch (e) {return true;}
					window.event.returnValue = false;
					window.event.cancelBubble = true;
					return false;
				} else if (target_tabs[j+1]) {
					//window.status = window.status + '!'
					//setTimeout("tabs[" + (j) + "][2].focus();", 1000);
					try {target_tabs[j+1][2].focus();} catch (e) {return true;}
					if (target_tabs[j+1][2].getAttribute('button') == 'true') target_tabs[j+1][2].setAttribute('ts', obj.getAttribute('ts'));
					
					window.event.returnValue = false;
					window.event.cancelBubble = true;
					//window.event.preventDefault();
					//event.cancelBubble = true;
					return false;
				}
			}
		}
	}
	//window.status = window.status + 'nf'; 
}

function loadTabs() {
	var obj, selects = document.getElementsByTagName('SELECT');
	for (var j=0; j < selects.length; j++) {
		obj = selects[j].getAttribute('tab');
		if (obj) {
			if (!tabs_[selects[j].getAttribute('ts')]) tabs_[selects[j].getAttribute('ts')] = new Array();
			tabs_[selects[j].getAttribute('ts')].push ( [parseFloat(obj), selects[j].name, selects[j]] );
		}
	}
	var inputs = document.getElementsByTagName('INPUT');
	for (var j=0; j < inputs.length; j++) {
		if (inputs[j].type != 'hidden') {
			obj = inputs[j].getAttribute('tab');
			if (obj) {
				if (!tabs_[inputs[j].getAttribute('ts')]) tabs_[inputs[j].getAttribute('ts')] = new Array();
				tabs_[inputs[j].getAttribute('ts')].push ( [parseFloat(obj), inputs[j].name, inputs[j]] );
			}
		}
	}
	var textarea = document.getElementsByTagName('TEXTAREA');
	for (var j=0; j < textarea.length; j++) {
		obj = textarea[j].getAttribute('tab');
		if (obj){
			if (!tabs_[textarea[j].getAttribute('ts')]) tabs_[textarea[j].getAttribute('ts')] = new Array();
			tabs_[textarea[j].getAttribute('ts')].push ( [parseFloat(obj), textarea[j].name, textarea[j]] );
		}
	}
	//alert(tabs_);
	for (var arry in tabs_) {
		tabs_[arry] = tabs_[arry].sort(bytab);
		tabs_[arry].push([999, '', document.getElementById('Save').parentNode] );
		//alert(tabs_[arry]);
	}
	//tabs_ = tabs_.sort(bytab);
	//alert(tabs_);
}
function bytab(obj1, obj2) {
	if (obj1[0] < obj2[0])
		return -1;
	if (obj2[0] < obj1[0])
		return 1;
	if (obj1[1] < obj2[1])
		return -1;
	if (obj2[1] < obj1[1])
		return 1;
	return 0;
};

function update_pagename_in_pkg(Page, Label) {
	document.getElementById('divPageName').innerHTML = Label;
	document.title = Label;
	return '|@@a=sp@@sp=base_UpdatePageNameDirect ' + Page + ', !v!, null, null@@v2=' + Label + '!#!#@@|'
}


	function LS_last() {
		var url=document.location.href;
		url = url.replace(/&p_id=(\d)*/,'');
		var sp = getURLParm('start', '');
		var lp = document.frmSelections.lastpage.value;
		if (sp == '') {
			document.location.href = document.location.href+'&amp;start=' + lp;
		} else {
			document.location.href=url.replace('start=' + sp,'start=' + lp);
		}
	}
	function LS_first() {
		var url=document.location.href;
		url = url.replace(/&p_id=(\d)*/,'');
		var sp = getURLParm('start', '');
		if (sp == '')
			document.location.href = document.location.href + '&start=1';
		else
			document.location.href=url.replace('start=' + sp,'start=1');
	}
	function LS_next() {
		var url=document.location.href;
		url = url.replace(/&p_id=(\d)*/,'');
		var sp = getURLParm('start', '');
		if (sp == '') {
			sp = document.frmSelections.startpage.value;
			if (!sp || sp == '') document.location.href = document.location.href+'&start=2';
			else document.location.href = document.location.href+'&start=' + (parseInt(sp)+1);
		} else {
			document.location.href=url.replace('start=' + sp,'start=' + (parseInt(sp)+1));
		}
	}
	function LS_prev(){
		var url=document.location.href;
		url = url.replace(/&p_id=(\d)*/,'');
		var sp = getURLParm('start', '');
		if (sp == '') {
			sp = document.frmSelections.startpage.value;
			document.location.href = document.location.href+'&start=' + (parseInt(sp)-1);
		} else
			document.location.href=url.replace('start=' + sp,'start=' + (parseInt(sp)-1));
		
	}

	function LS_next_Ajax() {
		go_searchP2(TPNextPos + 1);
		TPNextPos +=1;
		return false;
	}
	function LS_prev_Ajax() {
		go_searchP2(TPNextPos - 1);
		TPNextPos = TPNextPos - 1;
		return false;
	}
	function LS_first_Ajax() {
		go_searchP2(1);
		TPNextPos = 1;
		return false;
	}
	function LS_last_Ajax() {
		go_searchP2($('lastpage').value);
		TPNextPos = $('lastpage').value;
		return false;
	}

function go_searchP2(start) {
	var str = '';
	document.body.style.cursor='wait';
	if ($('spin')) $('spin').style.display='';
	str = document.getElementById('FullLast_searchP').value;
	var url = 'linkedsearch_direct.asp';		
	var pars = str +'&start=' + start + '&rndNum=' + Math.random()*9999;
	var target = 'TwoPaneSearchResults';	
	var myAjax = new Ajax.Updater(target, url, { method: 'get', parameters: pars, onComplete: function (){if ($('spin')) $('spin').style.display='none'; InitMenu('menuBargrid1');  if ($('XMLRequestJava')) eval($('XMLRequestJava').value); document.body.style.cursor='default';} });			
	return false;
}

function RemoveItemFastSQL(Page, ButtonName, Parm, Val) {

	readform();
	
	var posturl = 'pageactions.asp?action=route&amp;formatoption=refresh&amp;retrievemode=page&amp;buttonid=' + Page + '/' + ButtonName + '&amp;passthroughparms=yes&amp;' + Parm + '=' + Val;

      //var posturl = 'pageactions.asp?action=update2&amp;formatoption=refresh&amp;retrievemode=page';
      //var posturl = 'bgsave.asp';
      var pars = Form.serialize('frmUpdate'); 
	pars = pars + '&rndNum=' + Math.random()*9999;
	//var pars = '&CurrURL=' + escape(window.location.href);

	alert(pars);
      var myAjax = new Ajax.Request(posturl, { method: 'post', postBody: pars, onFailure: function (){SaveFailed();}, onSuccess: function (){if($('spin')) {$('spin').style.display='none';} }});
      //var myAjax = new Ajax.Updater('divMessage', posturl, { method: 'get', parameters: pars, onComplete: function (){if($('spin')) {$('spin').style.display='none';} AfterSave(); } });
      //var myAjax = new Ajax.Updater('divMessage', posturl, { method: 'post', parameters: pars, onComplete: function (){if($('spin')) {$('spin').style.display='none';} AfterSave(); } });
      return false;
}


function addReplaceURLParm(url,parm,parmval) {
	
	var newStr;
	parm = parm.replace(/\?/gi, '\\\?');
	var re = new RegExp(parm + "=([^&]*)","gi");
	
	newStr = url;
	if (newStr == null)			 // if no cookies for this page, set this one as only one
		newStr = parm + '=' + parmval;
		
	else if (newStr.match(re)) {	// if this name value, already set, update
		newStr = newStr.replace(re, parm + '=' + escape(parmval)); 
		}
	else						// if this name value not present in cookie, add it to end
		newStr = newStr + '&' + parm + '=' + parmval;
	
	//alert('addReplaceURLParm='+newStr);
	return newStr;

}

function AjaxSave() {
      //alert('AjaxSave');
      divMessage.innerHTML='Saving...please wait.';
      //readform();
      if (document.BeforeBGSave)   {
	BeforeBGSave();	//author can create this function in the Page Template 
   	}
	else try {if(BeforeBGSave) BeforeBGSave();} catch(e) {}   //needed try-catch after finding AfterBGSave dynamically added via subpage
								//not visible with document.AfterBGSave but otherwise this check throws an error.

      //var posturl = 'pageactions.asp?action=update2&amp;formatoption=refresh&amp;retrievemode=page';
      var posturl = 'bgsave.asp';
      var pars = Form.serialize('frmUpdate'); 
	//alert(pars);
	//alert(pars.length);
      //var myAjax = new Ajax.Request(posturl, { method: 'post', postBody: pars, onFailure: function (){SaveFailed();}, onSuccess: function (){if($('spin')) {$('spin').style.display='none';} AfterSave(); }});
      //var myAjax = new Ajax.Updater('divMessage', posturl, { method: 'get', parameters: pars, onComplete: function (){if($('spin')) {$('spin').style.display='none';} AfterSave(); } });
      var myAjax = new Ajax.Updater('divMessage', posturl, { method: 'post', parameters: pars, onComplete: function (){if($('spin')) {$('spin').style.display='none';} AfterSave(); } });
      return false;
}

function AfterSave() {
 //alert('AfterSave');
 var Pos;
 var JobTypeVal;
 var JobID;
 var JobOffice;
 var JobNum;
 if (document.AfterBGSave) { 
	AfterBGSave(); //author can create this function in the Page Template
 } 
 else try {if(AfterBGSave) AfterBGSave();} catch(e) {}  //needed try-catch after finding AfterBGSave dynamically added via subpage
							//not visible with document.AfterBGSave but otherwise this check throws an error.

 //AutoAdjustElementTitle();
 //if (document.AutoAdjustElementTitle) {AutoAdjustElementTitle(); }

divMessage.innerHTML='Save Complete.';
if (document.frmSelections) document.frmSelections.Saved.value = '1';
if (document.frmSelections) 
{
	if (document.frmSelections.pkg2.value.indexOf('t=Jobs@@@@f=JobType') > -1) 
	{
		window.location.reload();
		//alert('Found JobType!');
		//Pos = document.frmSelections.pkg2.value.indexOf('f=JobType');
		//JobTypeVal = document.frmSelections.pkg2.value.substr(Pos, document.frmSelections.pkg2.value.length)
		//Pos = JobTypeVal.indexOf('!#!#@@');
		//JobTypeVal = JobTypeVal.substr(0,Pos);
		//JobID = JobTypeVal.substr(JobTypeVal.indexOf('@@i=') + 4, JobTypeVal.indexOf('@@v2=') - JobTypeVal.indexOf('@@i=') - 4);
		//alert(JobTypeVal);
		//alert('Job ID = ' + JobID);
		//JobTypeVal = JobTypeVal.substr(JobTypeVal.indexOf('@@v2=') + 5, JobTypeVal.length - JobTypeVal.indexOf('@@v2='));
		//alert('JobType = ' + JobTypeVal);
		//JobOffice = getElementByName('Office').options[getElementByName('Office').selectedIndex].text;
		//JobOffice = JobOffice.substr(0,2).toUpperCase();;
		//alert('JobOffice = ' + JobOffice);
		//JobNum = JobTypeVal + JobID + JobOffice;
		//alert('JobNum = ' + JobNum);
	}
	if (document.frmSelections.pkg2.value.indexOf('t=Jobs@@@@f=Office') > -1) 
	{
		window.location.reload();
	}
}
try { clearChanged(); } catch (e) {}
PotentialRefresh();
//alert('PotentialRefresh just ran!');
}

function AutoAdjustElementTitle() {
 //alert('AutoAdjustElementTitle');
 var DivTitle = document.getElementById('divPageNameFirst');
 var PageTitle = getElementByName('Title');
 if ((DivTitle)&&(PageTitle)){
	DivTitle.innerHTML = getElementByName('Template').value + ': ' + PageTitle.value;
	}
}
	
var regExp_removetags = /<\/?[^>]+>/gi;
function RemoveTags(xStr){
	xStr = xStr.replace(regExp_removetags,"");
	return xStr;
}

function inc_back_count() {
	var bc = parseInt(getURLParm('bc', 0));
	return '&bc=' + ++bc;
}
function go_back_count() {
	var bc = parseInt(getURLParm('bc', 0));
	setTimeout("history.go(" + -bc + ");", 1);
}
function getContentDocument(obj) {
	if (obj.contentDocument) {
		//alert('w3c');
		return obj.contentDocument;
	}	else if (obj.contentWindow) {
		//alert('ie5.5-6p');
		return obj.contentWindow.document;
	}	else if (obj.document && !failed) {
		//alert('ie5m');
		return obj.document;
	} else {
		alert('Houston we have an IE 5.0 PC.');
		return null;
	}
}
function urlReplace(obj, url) {	//JS2FIREFOX [added]:
	var io = getContentDocument(obj);
	io.location.replace(url);
}
function submit_bg_form(form) {
	form.submit();
}
function handPointer(obj) { // JS2FIREFOX [added]: utility function added for mouseovers 
			obj.style.cursor =  'hand';
			if (obj.style.cursor != 'hand') obj.style.cursor = 'pointer';
			//if (obj.getAttribute('title')) setStatus( obj.getAttribute('title') );
		}
function getElementByName(name) {
	if (!name || name == '') return null;
	// the inputs aren't cataloged, until an element is requested (no reason to add load time if it's not used)
	if (!inputCatalog) catalogAllInputs();
	
	var obj = inputCatalog[name];
	return (obj ? obj : document.getElementById(name)); 
}
var regGetField = new RegExp();
regGetField.compile("f=([^@]*)", "i");
function catalogAllInputs() {
	//var startTime = new Date();
	inputCatalog = new Object();
	catalogItems('INPUT');
	catalogItems('SELECT');
	catalogItems('TEXTAREA');
	//window.status = 'Catalog time:' + ((new Date()).valueOf() - startTime.valueOf())/1000 + 'ms'; 
}
function catalogItems(type) {
	var objs = document.getElementsByTagName(type);
	for (var j=0; j < objs.length; j++) {
		//if (type == 'SELECT') alert('found select');
		
		if ((type == 'INPUT' && objs[j].type == 'hidden') || !objs[j].getAttribute('name') || (objs[j].getAttribute('name').substr(0, 3) != 'Val' && objs[j].getAttribute('name').substr(0, 10) !='TargetLink')) continue;
		//if (type == 'SELECT') alert('doing select');
		catalogItem(objs[j]);
	}
}
function catalogItem(obj) {
	var name = null;
	var	pkg = obj.getAttribute('pkg');
		if (pkg && pkg != '') {
			// if this is a package based item, look for field name in pkg attribute
			var search = regGetField.exec(pkg);
			if (search && search[1]) name = search[1];
		}
		if (!name) {
			// if we didn't find a name earlier, then look for the 'Label' hidden input in the same cell as the input
			var inner_inputs = (obj.parentNode ? obj.parentNode.getElementsByTagName('INPUT') : null);
			if (inner_inputs && inner_inputs.length < 10) // if there are too many inputs, something is fishy and I don't trust the situation
			for (var i=0; i < inner_inputs.length && !name; i++) {
				if (inner_inputs[i].getAttribute('name') && inner_inputs[i].getAttribute('name') == 'Label') name = inner_inputs[i].getAttribute('value');
			}
		}
		if (!name) {
			name = obj.getAttribute('name');
		}
		if (name && name != '') inputCatalog[name] = obj;
}
function showFirstTab() {
	var tabs = divTabRow.getElementsByTagName('TD');
	//alert(tabs.length);
	tabs[0].onclick();
}
function load_help(template) {
	var tabname = '';
	var tab;
	try {
		if (selected_tab) tab = document.getElementById('divTab' + selected_tab);
		if (tab) tabname = tab.firstChild.innerHTML;
	} catch (e) {}
	if (template=='') template = PageName;
	window.open('help/help.asp?template=' + template + '#' + tabname, 'Help','toolbar=no,status=no,scrollbars=yes,menubar=no,resizable=yes,width=640,height=500'); return false;
}

function load_clientQA(id) {
	//alert('load clientqa for id='+id);
    //document.getElementById('clientQA').style.display='';
    var posturl = 'clientqa.asp';
    var pars = 'id='+id + '&rnd=' + Math.random() * 9999;
	//var myAjax = new Ajax.Updater('clientQAContents', posturl, { method: 'get', parameters: pars, 
	//						onComplete: function (){ AlterAllSelects('hidden'); } });
	if (pars!='') posturl = posturl+'?'+pars;
	//Dialog.alert({url: posturl, options: {method: 'get'}},  {windowParameters: {className: "alphacube", width:550}, okLabel: "Close", top: 100});
	Dialog.confirm({url: posturl, options: {method: 'get'}},  
					{windowParameters: {className: "alphacube", draggable:true, resizable: false, width:550,height:400, style:"background-color: FFFFCC;"}, 
						okLabel: "Save", 
						ok: function (){ 
							//alert('Saved.');
							save_clientQA();
							return true;
							} , top: 10});
      return false;
}
function save_clientQA() {
	//alert('save_clientQA callback');
    divMessage.innerHTML='Saving...please wait.';
	if (document.BeforeBGSave)   {
		BeforeBGSave();	//author can create this function in the Page Template 
	}
	else try { if(BeforeBGSave) BeforeBGSave();} catch(e) {}   //needed try-catch after finding AfterBGSave dynamically added via subpage
	CalcPercentCompleteQA();
	var posturl = 'clientqa.asp';
	var pars = Form.serialize('frmUpdate'); 
	pars = 'action=update&'+pars;
	//alert('posturl='+posturl+'\nparameters='+pars);
	var myAjax = new Ajax.Updater('somedivnotpresent', posturl, { method: 'post', parameters: pars, 
						onSuccess: function(resp) {
									//alert('success');
									//processEnroll(resp);
									var tx = resp.responseText;
									//alert('save_clientQA:'+tx);
									if (tx.indexOf('updated.')>-1) {
										divMessage.innerHTML='Questions and Answers saved.';
										said = $('salesAssignmentID').value;
										//alert(said);
										ajaxSaveNotes(said,'QA updated.');
									}
								} 
					});
	return false;
}
function CalcPercentCompleteQA() {

 var QARecCount = $('RecCount').value;
 var QANumComplete = 0;
 var QAPercentComplete;
 var allTextAreaObjs = document.getElementsByTagName('textarea');
 if(allTextAreaObjs)
 {
  for(var selectCounter = 0;selectCounter<allTextAreaObjs.length;selectCounter++)
  {
   var currentSelectObj = allTextAreaObjs.item(selectCounter);
   if(currentSelectObj.name.substr(0, 7) == 'textQA_'){
	//alert(currentSelectObj.name);
	if(currentSelectObj.innerHTML.length > 0){
		QANumComplete++;
	}
   }
  }
 }
	//alert('QANumComplete: ' + QANumComplete);
	QAPercentComplete = (QANumComplete / QARecCount) * 100
	QAPercentComplete = Math.round(QAPercentComplete) 
	$('QAPctComplete').value = QAPercentComplete
	if (QAPercentComplete > 20 && $('Reassign_CSD_Div')){$('Reassign_CSD_Div').style.display='';};
	if (QAPercentComplete < 20 && $('Reassign_CSD_Div')){$('Reassign_CSD_Div').style.display='none';};
}
function load_helpv2(template) {
	  document.getElementById('HelpResourceDiv').style.display='';
      var posturl = 'VersaITHelpv2.asp';
      var pars = 'action=get&page=' + template + '&rnd=' + Math.random() * 9999;
	  var myAjax = new Ajax.Updater('HelpContents', posturl, { method: 'get', parameters: pars, 
							onComplete: function (){ AlterAllSelects('hidden'); slideIn(); } });
      return false;
}

function close_help() {
	AlterAllSelects('');
	document.getElementById('HelpResourceDiv').style.display = 'none';
	document.getElementById('HelpResourceDiv').style.left = '-320px';
	document.getElementById('HelpResourceDiv').style.top = '-320px';
}

function AlterAllSelects(visibility)
{
 var allSelectObjs = document.getElementsByTagName('select');
 if(allSelectObjs)
 {
  for(var selectCounter = 0;selectCounter<allSelectObjs.length;selectCounter++)
  {
   var currentSelectObj = allSelectObjs.item(selectCounter);
   currentSelectObj.style.visibility=visibility;
  }
 }
}


var targetX = 10;     // Final position (x)
var targetY = 10;     // Final position (y)

function slideIn() 
{
	//alert('Slidin');
	var floater = document.getElementById('HelpResourceDiv');
	var floatLeft = parseFloat(floater.style.left.replace('px', ''));
	var floatTop = parseFloat(floater.style.top.replace('px', ''));
	var newX = (floatLeft + ((targetX - floatLeft) / 12) + 3);
	var newY = (floatTop + ((targetY - floatTop) / 12) + 3);
	floater.style.left = newX + 'px';
	floater.style.top = newY + 'px';
	if ( newX < targetX || newY < targetY){
	  setTimeout('slideIn()', 10);
	}
}

function doUpdate() {
	alert('Error: The FastUpdate_v2 update code waS not loaded. Cannot save.');
	/*start = new Date();
	readform();
	end = new Date();
	alert('done:' + (end.getTime()-start.getTime())/1000);
	return false;*/
}
function queue_for_update() {
}
function versait_back() {
	alert('here');
	var back = -1;
	if (document.frmSelections.iframe_hits.value) back = back - eval(document.frmSelections.iframe_hits.value);
	setTimeout("history.go(" + back + ");", 1);
}
//document.onback = versait_back;
function doOnloadActions() {
	while (onload_actions.length > 0) {
		act = onload_actions.shift();
		//act = act.replace("'", "'");		
		//alert('onload_action: '+act);
		eval(act);
	}
}

function subMatch(regName, matchName) {
	var localArray = eval('val' + regName);
	for (var looper = 0; looper < localArray.length; looper++) {
		if (localArray[looper] == matchName) return looper;
	}
	return null;
}

function FlagChange(ElementID)
{
	try {
	  document.frmSelections.Saved.value=0;
	  eval("document.frmSelections.Changed" + ElementID +".value=0");
	  
	}
	
	catch (error) {
		return;
	}
	
	var possibleSS = document.getElementById('calc' + ElementID);
	if (possibleSS != null) {
		calcAll();
	}
	return true;
}
function FlagChangeV2(InputElement)
{
	//try {
	//alert(InputElement.tagName);
	document.frmSelections.Saved.value=0;
	InputElement.setAttribute("Changed",1);
	
	if (queue_for_update) {
		queue_for_update(InputElement, true);
	}
	if (InputElement.getAttribute("flagrow")) {
		//alert('flagrow');
		//find parent TR
		var oParent = InputElement.parentNode;
		
		//alert(oParent.nodeName);
		while ( (oParent.nodeName !='BODY' && oParent.nodeName != 'TR') ) {
			oParent = oParent.parentNode;
			//alert(oParent.nodeName);
		}
		
		if (oParent.nodeName=='TR') {
			//alert('TR');
			oParent.setAttribute("Changed",1);
			Elements = oParent.getElementsByTagName("input");
			for (var i=0; i<Elements.length; i++) {
				if(Elements.item(i).getAttribute("Changed")) {			
				//alert(Elements.item(i).tagName);
					Elements.item(i).setAttribute("Changed",1);
				}
			}
			
			Elements = oParent.getElementsByTagName("select");
			for (var i=0; i<Elements.length; i++) {
				if(Elements.item(i).getAttribute("Changed")) {			
						Elements.item(i).setAttribute("Changed",1);
				}
			}
			
			Elements = oParent.getElementsByTagName("textarea");
			for (var i=0; i<Elements.length; i++) {
				if(Elements.item(i).getAttribute("Changed")) {			
						Elements.item(i).setAttribute("Changed",1);
				}
			}
		}
	
	}
//else
//if (queue_for_update) {
//		queue_for_update(InputElement, true);

		
	//} catch (error) {
	//	return;
	//}
	
	return true;
}
function getURLParm(str, default_) {
	if (!(window.location.href.indexOf(str) > 0)) return default_;
	var temp = window.location.href.substr( window.location.href.indexOf(str)+str.length+1);
	var str = temp;
	if (temp.indexOf('&') > 0) str = temp.substr (0, temp.indexOf('&') );
	if (str.charAt(str.length-1) == '#') return str.substr(0,  str.length-1);
	return str;
}
function calcAll() {
	subMatch ('ColsRows', 'column');
	if (ssError) return;
	if (calcItems == null)
		calcItems = document.getElementsByName("calc");
		
	for (var i=0; i < calcItems.length; i++) {
		if (calcItems[i].formula.charAt(0) == '=') {
			calcCell(calcItems[i]);
		}
	}	
}

function calcCell(calcItem) {
	var oldval;
	var resolvedFormula = resolveRefs(calcItem);
	if (resolvedFormula != null) {
		var valItem = document.getElementsByName("Val" + calcItem.value);
		try {
			oldval = valItem[0].value;
			if (valItem[0] != null) valItem[0].value = eval(resolvedFormula);
			valItem[0].value = Math.round(valItem[0].value*100)/100  
			if (oldval != valItem[0].value) eval("document.frmSelections.Changed" + calcItem.value +".value=0");
		}
		catch (e) {
			ssError = true;
			alert('Error calculating spread sheet');
		}
	}
}

function resolveRefs(calcItem) {
	var looper, tRow, colNum, rowNum, replacementVal, strTemp;
	var re = new RegExp(regColsRows);
	var formula = calcItem.formula.substr(1);
	var references = formula.match(re);
	var currRow = getParentElem(calcItem, 'TR');
	var tBody = getParentElem(currRow, 'TBODY');
	var regReplace;
	
	
	
	while (references != null) {
		var operation = references[subMatch('ColsRows', 'operation')];
		
		if (references[subMatch('ColsRows', 'numberSign')] == '#') {
			tRow = currRow;
			rowNum = null;
		} else if (references[subMatch('ColsRows', 'row')] != '') {
			rowNum = references[subMatch('ColsRows', 'row')];
			tRow = null;
			//go get specified row
		} else { // no row or '#' specified, must need whole column
			rowNum = null;
			tRow = null;
		}
		
		
		if (references[subMatch('ColsRows', 'column')] != null) {
			colNum = references[subMatch('ColsRows', 'column')].charCodeAt(0) - 64;			
		}
		
		if (colNum != null && tRow != null) 
			replacementVal = getCellValue(tRow, colNum);
		else if (colNum != null && rowNum != null) {
			if (references[subMatch('ColsRows', 'tableName')] == 'this') {					
					replacementVal = getCellValueFromTable(tBody, rowNum, colNum);
				}			
			else 
				replacementVal = getCellValueFromTableName(references[subMatch('ColsRows', 'tableName')], rowNum, colNum);
		}
		else if (tRow == null) { // working on all rows in a single column
			replacementVal = propagateOnColumn(currRow, colNum, operation);
		}
		
		if (replacementVal == null || replacementVal == '') replacementVal = 0;
		
		strTemp = references[0]
		strTemp = strTemp.replace(/\[/, "\\\[");
		strTemp = strTemp.replace(/\]/, "\\\]");
		strTemp = strTemp.replace(/\)/, "\\\)");
		strTemp = strTemp.replace(/\(/, "\\\(");
		regReplace = new RegExp(strTemp,"gi")
		
		formula = formula.replace(regReplace, replacementVal);
		
		// find the next 'tablename[]' set
		references = RegExp.rightContext.match(re);
	}
	return(formula);
	
}
function propagateOnColumn(tRow, colNum, operation) {
	var tBody = getParentElem(tRow, 'TBODY');
	var op;
	var cVal, sReturn;
	switch (operation.toLowerCase()) {
		case 'sum(':
			op = ' + ';
			break;
		case 'prod(':
			op = ' * ';
			break;
		case 'sub(':
			op = ' - ';
			break;
	}

	sReturn = null;
	for (var looper = 1; looper < tBody.childNodes.length; looper ++) {
		if (tBody.childNodes[looper] != tRow) //make sure we don't include current row
			if ((cVal = getCellValue(tBody.childNodes[looper], colNum)) != null) {
				if (looper == 1)
					sReturn = cVal;
				else
					sReturn = sReturn + op + cVal;
			}
	}

	return sReturn
	
}


function getCellValueFromTableName(tableName, rowNum, colNum) {
	//alert(tableName);
	var tBody = document.getElementById('tb' + tableName);
	if (tBody == null) return null;
	
	tBody = tBody.childNodes[0];
	return getCellValueFromTable(tBody, rowNum, colNum);
}

function getCellValueFromTable(tBody, rowNum, colNum) {
	if (rowNum == '!')
		var tRow = tBody.childNodes[tBody.childNodes.length - 1];
	else
		var tRow = tBody.childNodes[rowNum];
	return (getCellValue(tRow, colNum));
}

function getCellValue(tRow, colNum) {
	var looper = 0;
	var column = tRow.childNodes[colNum];
	var targetCell = column.childNodes[looper++];
		
	while ( (targetCell !=null && targetCell.name != null && targetCell.name.substr(0,3) != 'Val') || (targetCell != null && targetCell.name == null) ) {
		
		targetCell = column.childNodes[looper++];
	}
	if (targetCell != null && targetCell.name != null && targetCell.name.substr(0,3) == 'Val')
		return targetCell.value;
	return null;
}

function getParentElem(item, elem) {
	var tElem;
	tElem = item.parentNode;
	while (tElem.nodeName != elem && tElem.nodeName != 'BODY') {
		tElem = tElem.parentNode;
	}
	if (tElem.nodeName == elem) {
		return tElem;
	}
	return null;
}


function getTable(tableName, calcItem) {
	// probably should add caching here for tables
	var tBody;
	if (tableName == 'this')
		tBody = calcItem.parentNode;
	while (tBody.nodeName != 'TBODY') {
		tBody = tBody.parentNode;
	}
	if (tBody.nodeName == 'TBODY') {
		alert('got it');
	}
}

function ValidateMask(item, mask)
{
	var required = item.mask;
	if (mask != "") {
		var re = new RegExp(mask);
		var matches = item.value.match(re);
		
		if (matches == null) {
			alert("Item: " + item.name + " must be of the form: " + required + ". Please correct this and resubmit.");
			return false;
		}
	}
	return true;
}

function HandleSpecial(item, e)
{
	item.selection=document.selection.createRange();
	var currMask = item.mask;
	
	if (isMaskValid(item.value, currMask)) {
		var dup = item.selection.duplicate();
		var pos = 0-dup.move("character",-255);
		
		var dup = item.selection.duplicate();
		dup.move("character",1);
		
		var modPos = 0;
		
		if (pos < currMask.length) {
			switch (e.keyCode) {
			case 8: 
				// backspace key
				if (item.selection.text.length > 0) { // clear out any selected text 
					// if dealing with an actual selection
					var data = stripOutData(item.value, currMask, pos+item.selection.text.length);
					var newText = applyMask(data, currMask, pos);
					document.selection.clear();
					while (dup.expand("character"));
					dup.text = nonDataSuffix + newText;// + nonDataSuffix;
					
					return false;
					break;
				}
				
				if (currMask.charAt(pos-1) != '#' && currMask.charAt(pos-1) != '&') {
					// if trying to delete a non data character, skip over it
					dup.text = item.value.charAt(pos-1) + item.value.charAt(pos)
					item.selection.expand("character");
					item.selection.text = "";
					
					return true;
				}
				
				while (dup.expand("character"));
				var data = stripOutData(item.value, currMask, pos);
				var newText = applyMask(data, currMask, pos-1);
				dup.text = newText;// + nonDataSuffix;
				
				item.selection.expand("character");
				
				item.selection.text = "";
				return true;
				break;
				
			case 46:
				// delete key
				if (item.selection.text.length > 0) { // clear out any selected text 
					var data = stripOutData(item.value, currMask, pos+item.selection.text.length);
					var newText = applyMask(data, currMask, pos + modPos);
					document.selection.clear();
					while (dup.expand("character"));
					dup.text = nonDataSuffix + newText;// + nonDataSuffix;
					
					return true;
					break;
				}
				
				while (currMask.charAt(pos) != '#' && currMask.charAt(pos) != '&') {
					if (pos == item.value.length) return false; // jump out if no data left to delete
					pos++;
					modPos = -1;
				}
				while (dup.expand("character"));
				
				//alert(item.value);
				var data = stripOutData(item.value, currMask, pos+1);
				//alert(data);
				var newText = applyMask(data, currMask, pos + modPos);
				//alert(newText);
				dup.text = nonDataSuffix + newText;// + nonDataSuffix;
					
				return true;
				break;
			}
		}
	}
	return true;
}

function CheckMask(item, e)
{
	var passThrough = false;
	var currMask = item.mask;
	var newChar = String.fromCharCode(e.keyCode)
	var modPos = 1;
	
	item.selection=document.selection.createRange();
	if (item.selection.text.length > 0) {
		document.selection.clear(); // clear out any selected text
	}
	//item.selection.text = "" // clear out any selected text
		
	if (isMaskValid(item.value, currMask)) {
		var dup = item.selection.duplicate();
		var pos = 0 - dup.move("character",-255);
		var dup = item.selection.duplicate();
		dup.move("character", 1);
		while (dup.expand("character"));
		if (pos < currMask.length) { // if we're within the confines of the mask
			var data = stripOutData(item.value, currMask, pos);
			var tempString = "";
			var looper = pos;
			if (currMask.charAt(looper) != '#' && currMask.charAt(looper) != '&' && item.value.charAt(looper) != '' && currMask.charAt(looper) != newChar) {
				while (looper < currMask.length && looper < item.value.length && currMask.charAt(looper) != '#' && currMask.charAt(looper) != '&' && item.value.charAt(looper) != '' && currMask.charAt(looper) != newChar) {
					tempString = currMask.charAt(looper);
					looper++;
				}
				passThrough = true;
				modPos = tempString.length + 1;
				newChar = tempString + newChar;
			}
			if ((currMask.charAt(pos) == '#' && (newChar >= '0' && newChar <= '9')) || (currMask.charAt(pos) == newChar) || passThrough) { // at somepoint, when we do letter only mask, we will need some of this stuff //&& (currMask.charAt(pos) = '&' || (newChar > '0' || newChar < '9'))) {
				passThrough = false;
				// mask wants number and we got a number
				if (isMaskFilled(item.value, currMask)) {
					// if mask is filled up, we throw a
					data = data.substr(1);
				}
				var newText = applyMask(data, currMask, pos+modPos); // modPos will usually be 1, but will be 0 when entering prior to a non-data char
				
				if (pos < item.value.length) {
					// adding numbers in middle of text
					dup.text = newText				
					item.selection.expand("character");
				} else {
					// if appending numbers on end of text
					dup.text = newText				
				}
				
				item.selection.text = newChar + nonDataSuffix;
			}
			return false;
		} else {
			// we're outside mask, they can do whatever they want
		}
	}
	else {
		// mask isn't valid, they can do whatever they want

	}
	return true;
}

function applyMask(data, mask, startPos)
{
	var output="";
	var dataCount=0;
	nonDataSuffix="";
	// consume all data
	for (var looper=startPos; dataCount < data.length; looper++) {
		//alert('maskchar' + mask.charAt(looper));
		if (looper > mask.length || mask.charAt(looper) == '#' || mask.charAt(looper) == '&') {
			output = output + data.charAt(dataCount);
			dataCount++;
		} else {
			if (dataCount > 0) {
				// never want lead character to be a dash (non data)
				output = output + mask.charAt(looper);
			} else {
				nonDataSuffix = nonDataSuffix + mask.charAt(looper);
			}
			//if (looper == mask.length) return output;
		}
		
	}
	// append any non-data mask stuff
	for (var looper = looper; looper < mask.length; looper++) {
		if (mask.charAt(looper) != '#' && mask.charAt(looper) != '&') {
			output = output + mask.charAt(looper)
		} else {
			return output;
		}
	}
	return output;
}

function stripOutData(input, mask, startPos)
{
	var output="";
	for (var looper=startPos; looper < input.length; looper++) {
		if (looper >= mask.length || mask.charAt(looper) == '#' || mask.charAt(looper) == '&') {
			output = output + input.charAt(looper);
		}
	}
	return output;
}

function isMaskValid(input, mask)
{
	for (var looper=0; looper < mask.length; looper++) {
		if (looper >= input.length) {
			return true;
		}
		else {
			if (mask.charAt(looper) == '#' && (input.charAt(looper) < '0' || input.charAt(looper) > '9')) {
				//if (mask.charAt(looper) == ' ')	return true;
				// if there is a space at end of current valid text, then ignore remainder of text.
				return false;
			} else {	
				//if (mask.charAt(looper) != '&') {	// need checking here later
				//	return false;
				//} else {
					if (mask.charAt(looper) != '#' && mask.charAt(looper) != input.charAt(looper)) {
						//if (mask.charAt(looper) == ' ')	return true;
						return false;
					}
				//}
			}
		}
	}
	return true;
}

function isMaskFilled(input, mask)
{
	if (mask.length > input.length) return false;
	return true;
}

function VerifySave(dont_wait, target_obj)	//JS2FIREFOX [changed] - added target_obj param
{
	if(typeof worksheetCustomExit!="undefined")
	{	
		if(!worksheetCustomExit())
			return false;
	}

	if (newStyleUpdate && outstandingUpdates()) {
		
		if (confirm("Changes have been made to this page. Press OK if you wish to save these changes and continue")) {
			//if (confirm("Changes have been made to this page. Press OK if you wish to discard these changes and continue"))
			doUpdate(dont_wait);
			return true;
		} else
		return (confirm("Do you wish to continue with requested action without saving?"));
	}
	
	//following specifically for Testgate, question page.
	try {
		SaveHTML(selectedEditObj);
	} catch (e) {}
	
	
	if (document.frmSelections.Saved.value==-1)
	{               
		document.frmSelections.Saved.value=0;
		return true;
	}               
	if (document.frmSelections.Saved.value==0)
	{	
		//For FastUpdate, cookie requested action, call "Save" onclick, then check for "nextaction" cookie afterwards.
		//Assume there is a "Save" button with an "onclick"
		if(document.getElementById('Save')) {
			var savecmd = document.getElementById('Save').getAttribute('onclick');
			//alert('Save: '+document.getElementById('Save').nodeName+':'+savecmd);
			
			var srcEl = (window.event && window.event.srcElement) ? window.event.srcElement : target_obj;			//JS2FIREFOX [changed]

			if(srcEl) {
				var cmd=srcEl.getAttribute('cmd');
				//alert('1' + cmd);
				if(srcEl.tagName=='DIV')
					if(srcEl.getAttribute('cmd')) {
						cmd = srcEl.getAttribute('cmd');
						//alert('2' + cmd);
				
					}
					if(cmd==null && srcEl.tagName!='A' && srcEl.parentNode.tagName=='A') { 
					cmd = srcEl.parentNode.getAttribute('onclick');
					//alert('3' + cmd);
				
					} 
					else {
					cmd = srcEl.getAttribute('onclick');
					//alert('4' + cmd);
				
					}

				if(cmd==null) cmd='';
				cmd = cmd.toString().replace(/function anonymous\(\)/,"")
				cmd = cmd.toString().replace(/return false/,"")
				cmd = cmd.toString().replace(/parent\.parent\.VerifySave\(([^\)]*)\)/,"true")
				cmd = cmd.toString().replace(/parent\.VerifySave\(([^\)]*)\)/,"true")
				cmd = cmd.toString().replace(/VerifySave\(([^\)]*)\)/,"true")
				//alert('cmd: '+cmd); 

				//document.frmUpdate['nextaction'].value = cmd;
				//alert('nextaction: '+document.frmUpdate['nextaction'].value); 
			}
		}
		else savecmd=''

		if (showModalDialog)	// if we're in IE, use the new dialog
			var retVal = msgbox("Changes have been made to this page. Please select an action to take.", 'vbCancelCont_DontSaveCont_SaveDefaultButton1Question', 'Save Changes?');
		else
			retVal = confirm("Changes have been made to this page. Do you wish to save and continue?") ? 8 : -2;
		if (retVal==8) {
			//if (confirm("Changes have been made to this page. Do you wish to save and continue?"))
			
			//alert(savecmd.toString().indexOf('readform'));
			if(savecmd.toString().indexOf('readform')>0) {	//Does the Save button have "readform" in it?
				//set frmUpdate.nextaction
				if(cmd) {
					//alert('test:' + cmd);
					setCookie('checknextaction', '1');		
					setCookie('nextaction', escape(cmd) );
				}
				else	setCookie('checknextaction', '0');
				try {
					document.getElementById('Save').onclick();	//execute Save
				}
				catch (error) { return;}
				return false;
			} else {
				document.frmSelections.Saved.value=-1;
				return true;
			}
		} else if (retVal==-2) {
			return (confirm("Do you wish to continue with requested action without saving?"));
		} else if (retVal==9) {
			return true;
		} else {
			return false;
		}
		
	}
	else
		return true;
}

function VSaveButton(url)
{

	document.frmSelections.action = url;

	if (document.frmSelections.Saved.value==-1)
	{	
		document.frmSelections.Saved.value=0;
		return true;
	}	
	if (document.frmSelections.Saved.value==0)
	{	


		var pattern = /Save(\w+)/g;
		var saveFound;
		var buttons = document.getElementsByTagName('a');
		var num = buttons.length;
		var currItem; 
		var SaveButton = 'no';
		var j = 1;
		while (j < num) {
			currItem = buttons[j];
			if (currItem.innerText.substr(0, 4) == 'Save') {
				SaveButton = 'yes';
				j = num;
			}
		j++;
		}

		if (SaveButton == 'yes')
		{
			//alert('SaveButton onclick=' + currItem.onclick);

			if (confirm("Changes have been made to this page. Do you wish to save and continue?"))
			{
				document.frmSelections.Saved.value=-1;
				//merge urls
				var DisplayURLParts = url.split('&');
				var SaveURL = "" + currItem.onclick;
				var SaveURLParts = SaveURL.split("'");
				var NewURL = SaveURLParts[1].split("&")[0];
				NewURL = NewURL + '&' + SaveURLParts[1].split("&")[3];
				NewURL = NewURL + '&' + DisplayURLParts[0].split("?")[1];
				NewURL = NewURL + '&mergedurl=y';
				var num2 = DisplayURLParts.length;
				var k = 1;
				while (k < num2) {
					NewURL = NewURL + '&' + DisplayURLParts[k];

				k++;
				}
				
				//alert('NewURL=' + NewURL);
				document.frmSelections.action = NewURL;



				return true;
			}
			else
			{
				if (confirm("Do you wish to continue with requested action without saving?"))
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		else
		{
			return true;
		
		}	
	}
	else
		return true;
}
function determineEndAction() {
		//alert('test' + getURLParm("dontbackrefresh", "f"));
		//return 0;
		if (getURLParm("dontbackrefresh", "f") == "t")
			return 0;
		return 2;
}
function PotentialRefresh()
{
 	/*
	This is code created on 7/11/02. It looked in the URL for a modifier, found the first file in
	the html (hidden control) and redirected to it. We decided to do this a different way to avoid
	the flash of the intermediate page showing up.

	var intNumFiles
	var filePath
 	var urlString = document.frmSelections.CurrURL.value;
	var pattern = /skipToFile=(\w+)/;
	var skipToFile = urlString.match(pattern);
	if (skipToFile[1] == "true") {
		document.frmSelections.CurrURL.value = urlString.replace(pattern, "");
		intNumFiles = eval("document.frmSelections.fileLink.length");
		if (typeof(intNumFiles) != "undefined")
		{
			filePath = document.frmSelections.fileLink[0].value;
		} else {
			filePath = document.frmSelections.fileLink.value;
		}
		if (filePath != null) {
			window.location = filePath;
			return true;
		}
	}*/
	

	// original stuff, pre June 2002
	              var endstr = document.cookie.indexOf ("checknextaction=1");
								 if (endstr > -1 && document.frmSelections.EndAction)
                {
						 //	alert('a');
								                 var nextaction = getCookie('nextaction');
                                nextaction = unescape(nextaction);
                                //alert('Cookie nextaction='+nextaction);
                                setCookie('checknextaction', '0');
                                setCookie('nextaction', '');
                                document.frmSelections.Saved.value=-1;
																	eval(nextaction);
																	//setTimeout('alert("ok");' + nextaction, 5000);
                }
                
                endstr = document.cookie.indexOf ("backreload");
                if (endstr > -1)
                {
						 	//alert('here');
                                document.cookie = "EndAction=none";
                                //window.location.reload(true);
                                setTimeout("window.location.reload(true);", 1);
																	//window.location.replace(window.location.href);
																	//alert('here');
                }
                document.frmSelections.Saved.value=1;
                return true;
}

function PotentialBackNavigation()
{
	if (document.frmSelections.EndAction.value ==1)
	{
		document.frmSelections.EndAction.value = 0;
		setTimeout("history.go(-2);", 1);
	}
	if (document.frmSelections.EndAction.value == 2)
	{
		document.frmSelections.EndAction.value = 0;
		document.cookie = "EndAction=backreload";
		setTimeout("history.go(-2);", 1);
	}
	
	return true;
}


function FlagChangeMulti(isChecked,ElementID)
{
	// this is used for both Reverse PV selection changes, as well as attendance page changes for the Tech Connect 2 application.
	// Note, ElementID cannot contain a colon.
	var intNumBoxes;
	document.frmSelections.Saved.value=0;
	
	intNumBoxes = eval("document.frmSelections." + ElementID +".length");
	
	if (typeof(intNumBoxes) != "undefined")
	{
		ElementID = ElementID + "[0]"
	}
	if (isChecked) {
		eval("document.frmSelections." + ElementID +".value=1");
	}
	else {
		eval("document.frmSelections." + ElementID +".value=0");
	}
		
	return true;
}
/*
function RevPVChange(isChecked,ElementID)
{
	var intNumBoxes;
	document.frmSelections.Saved.value=0;
	
	intNumBoxes = eval("document.frmSelections." + ElementID +".length");
	
	if (typeof(intNumBoxes) != "undefined")
	{
		ElementID = ElementID + "[0]"
	}
	if (isChecked) {
		eval("document.frmSelections." + ElementID +".value=1");
	}
	else {
		eval("document.frmSelections." + ElementID +".value=0");
	}
	return true;
}*/

function EntryIsChecked()
{
	var Checked; //as Boolean
	var intNumBoxes, x; // as integer
	
	Checked=false;
	
	intNumBoxes = document.frmSelections.chkPage.length;
	if (typeof(intNumBoxes) == "undefined")
	{
		// if only entry checked, true otherwise false
		Checked = document.frmSelections.chkPage.checked;
	}
	else
	{
		x=0;
		while (x<intNumBoxes)
		{
			if (document.frmSelections.chkPage[x].checked)
			{
				Checked = true;
			}
			x++;
		}
	}
	if (!Checked) alert("You must select at least 1 entry for this function.");
	return Checked;
}

function ItemIsChecked()
{
	var Checked; //as Boolean
	var intNumBoxes, x; // as integer
	
	Checked=false;
	
	intNumBoxes = document.frmSelections.chkItem.length;
	if (typeof(intNumBoxes) == "undefined")
	{
		// if only entry checked, true otherwise false
		Checked = document.frmSelections.chkItem.checked;
	}
	else
	{
		x=0;
		while (x<intNumBoxes)
		{
			if (document.frmSelections.chkItem[x].checked)
				Checked = true;
			x++;
		}
	}
	if (!Checked) alert("You must select at least 1 item for this function.");
	return Checked;
}


function PopUp(ID, popupPage, IDmodifier, initValue) {
	var openURL = 'display.asp?formatoption=popup&retrievemode=page&pagetype=POPUP+PAGE&key=' + popupPage + '&' + initValue;
	//var w = 330, h=270;
	var w = 640, h=480;
	//var openParms = 'location=no,scrollbars=yes,resizable=yes,width='+w+',height='=h;
	var openParms = 'location=no,scrollbars=yes,resizable=yes,width='+w+',height='+h;
	popupID = ID;

//alert(openParms);
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	openParms = openParms+',top='+TopPosition+',left='+LeftPosition
//alert(openParms);

	if (IDmodifier == null) {
		popupModifier = '';
	} else {
		popupModifier = IDmodifier;
	}
		
	try {
		if (popupModifier.substr(0,2) == '??') 
			popupTarget = document.frmSelections[popupModifier];
		else {
			popupTarget = eval("document.frmSelections.Val" + popupModifier + ID);
			if (!popupTarget) popupTarget = eval("document.frmSelections.TargetLink" + popupModifier + ID);
			if (!popupTarget) popupTarget = document.getElementById(ID);
		}
		
	}
	catch (error) {
		return;
	}
	
	if (popupPage.indexOf('.') > -1) {
		openURL = popupPage;
	}

	if (popupPage.indexOf('lookup.asp') > -1 || popupPage.indexOf('lookupv2.asp') > -1) {
		//alert(popupPage);
	    if (document.location.href.indexOf('xID=') > -1) {
		pos = document.location.href.indexOf("xID=")
		if (pos > -1)	{
		    xID = document.location.href.substring(pos + 3, document.location.href.length)
		    if (xID.indexOf("&") >= 0)
			xID = unescape(xID.substring(1, xID.indexOf("&")))	
		    openURL = openURL+'&xID='+xID;
		}
	    }
	}

	if (lastPopup != popupPage || typeof(PWindow) == 'undefined') {
		// if window has never been opened, or this is a different popup, open it
		PWindow=open(openURL,'PWindow',openParms);
		if (PWindow.opener == null) PWindow.opener = self;
		PWindow.focus();
		lastPopup = popupPage;
	}
	else {
		// if this popup is already open, or already opened and closed.
		try {
			// reapply focus
			PWindow.focus();
		} catch (error) {
			// if the popup had been closed, reopen it
			PWindow=open(openURL,'PWindow',openParms);
			if (PWindow.opener == null) PWindow.opener = self;
			lastPopup = popupPage;
		}
	}
}

function DatePopUp(ID,IDmodifier) {
	var openURL = 'datepopup.htm';
	var openParms = 'location=no,scrollbars=no,resizable=no,width=250,height=230';
	popupID = ID;
	if (IDmodifier == null) {
		popupModifier = '';
	} else {
		popupModifier = IDmodifier;
		//alert(popupModifier.charAt(0));
		//if (popupModifier.charAt(0)=='?') alert('Parm');
		//alert(document.frmSelections.elements[IDmodifier].value);
	}
	try {
		if (popupModifier.charAt(0)=='?' && document.frmSelections.elements[IDmodifier]) {
			popupTarget = document.frmSelections.elements[IDmodifier];
			}
		else {
			popupTarget = eval("document.frmSelections.Val" + popupModifier + ID);
			if (!popupTarget) popupTarget = eval("document.frmSelections.TargetLink" + popupModifier + ID);
		}
	}
	
	catch (error) {
		return;
	}
	
	
	if (typeof(PWindow) == 'undefined') {
		// if window has never been opened, or this is a different popup, open it
		PWindow=open(openURL,'PWindow',openParms);
		if (PWindow.opener == null) PWindow.opener = self;
		PWindow.focus();
	}
	else {
		// if this popup is already open, or already opened and closed.
		try {
			// reapply focus
			PWindow.focus();
		} catch (error) {
			// if the popup had been closed, reopen it
			PWindow=open(openURL,'PWindow',openParms);
			if (PWindow.opener == null) PWindow.opener = self;
		}
	}
}



var changedLinkText = "alert('test2');";
function changedLink() {
	var temp = new Function(changedLinkText);
	temp();
	return false;
}

function RPV(Value) {
	return returnPopupValue(Value);
}
function returnPopupValue(Value) {
	//alert(Value);
		var sets;
		
		var loop;
		if (Value.indexOf("=") == -1) {
			// simple assignment (no ='s)
			
			try {
				opener.popupTarget.value = Value;
				//alert(opener.popupID);				
				opener.FlagChange(opener.popupID);
			} catch (error) {
				popupTarget.value = Value;
			}
		}
		else {
			if (Value.indexOf("&&") == -1) {
				handleReturn(Value)			
			} else {
				sets = Value.split("&&");
				for(loop = 0; loop < sets.length; loop++) {
					handleReturn(sets[loop])
				}
			}
		}
		try {
			opener.FlagChangeV2(opener.document.getElementById(opener.popupID))
			//alert('id: ' + opener.popupID);
			//alert('el: ' + opener.document.getElementById(opener.popupID));
		} catch (error) {}
		try {
			opener.FlagChange(opener.popupID);
		} catch (error) {
		}
	
	window.close();
}

function handleReturn(text) {
	var pairs;
	var target;
	var j=1;
	var finders;
	
	pairs = text.split("=");
	if (pairs[0].substr(0,14) == 'AttributeVal!!') {
		var temp = 'AttributeLabel' + opener.popupID;
		finders = pairs[0].split("!!");
		var num = opener.document.getElementsByTagName('input').length;
		var currItem; 
		while (j < num) {
			currItem = opener.document.getElementsByTagName('input')[j];	
			if (currItem.value == finders[1] && currItem.name.substr(0,temp.length) == temp) {
				target = eval("opener.document.frmSelections.AttributeVal" + opener.popupID + currItem.name.substring(temp.length));
				j = num;
			}
		j++;
		}
		target.value = pairs[1];
		return false;
	}
	if (pairs[0].substr(0,10) == '@@linkpage' || pairs[0].substr(0,4) == '@@lp') {
		var pattern = /key=[\d]*/i;
		
		var temp = opener.document.getElementById('link' + opener.popupID).onclick.toString();
		temp = temp.substring(temp.indexOf('{') + 2, temp.length - 3) + ';'; // rip out function text
		// this line of code removes the return false found at start of onclick when there is no selected value already ('None')
		if (temp.substring(0, 13) == 'return false;') temp = temp.substring (14);
		temp = temp.replace(pattern, "key=" + pairs[1]); // change key value
		// set function text into hidden javascript variable in calling page
		opener.changedLinkText = temp;
		// change onclick to point to a function in the calling page, which invokes the text set above
		opener.document.getElementById('link' + opener.popupID).onclick = opener.changedLink;
		
		try {
			opener.document.getElementById('link' + opener.popupID).parentNode.getElementsByTagName('INPUT')[3].value = pairs[1]; //WSH 6/8/06 put in to support lookup.asp changes on links in new Sunglass system. Relies on input being 4th one in TD
		}catch (error) {

		}

		opener.popupTarget.value = pairs[1]; // set new link value\
		opener.FlagChange(opener.popupID);
		return false;
	}
	if (pairs[0].substr(0,10) == '@@linktext' || pairs[0].substr(0,4) == '@@lt') {
		opener.document.getElementById('link' + opener.popupID).innerText = pairs[1]; // change link text
		return false;
	}
	
	try {
		target = eval("opener.document.frmSelections." + pairs[0] + opener.popupID);
		target.value = pairs[1];
	} catch (error) {
		alert('Error finding target.');
		return false;
	}
	
	
}

// *************************************************************
// This area deals with cursor positioning and pressing enter
firstElement = 0;
netscape = "";
ver = navigator.appVersion; len = ver.length;
for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
netscape = (ver.charAt(iln+1).toUpperCase() != "C");

var default_actions_return = true;

function keyDown(DnEvents) { // handles keypress
	// determines whether Netscape or Internet Explorer
	var event = (DnEvents) ? DnEvents : window.event					// JS2FIREFOX [changed]
	var k = event.keyCode;																			// JS2FIREFOX [changed]
	//window.status = k + '!';
	var action = kb_actions[k + '_'];
	if (k == 13) { // enter key pressed
		var src = (event.target) ? event.target : event.srcElement;		// JS2FIREFOX [changed]
		if (src.name.substr(0,3)=='Val') {
			eval('FlagChange('+src.name.substr(3,9)+')');
		}
		//alert(document.getElementById('QuickSearch').value);
		if(document.frmDefaultAction.DefaultAction && (document.frmDefaultAction.DefaultAction)){
			//following line is to ensure that onchange event occurs for textbox
			try {
				document.frmSelections.elements[firstElement].focus();
				document.frmSelections.elements[firstElement].blur();
			} catch (e) {}
				intEnterActions = document.frmDefaultAction.DefaultAction.length;
				if (typeof(intEnterActions) == "undefined")
				// if only 1
					eval(document.frmDefaultAction.DefaultAction.value);
				else
				// if more than 1
					eval(document.frmDefaultAction.DefaultAction[0].value);
		}
		for (var j=0; j < default_actions.length; j++) {
			eval(default_actions[j]);

			
		}
		
	} else if (k == 46) { // del key pressed
		for (var j=0; j < delete_actions.length; j++) {
			eval(delete_actions[j]);
			
		}
	} else if (action) {
		if (eval(action['ctrl']) == event.ctrlKey && eval(action['shift']) == event.shiftKey && eval(action['alt']) == event.altKey)   {
			eval(action['action']);
		}
	}
	if(!default_actions_return){
		default_actions_return = true;
		return false;
	}

}

document.onkeydown = keyDown; // work together to analyze keystrokes
if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);
//if (document.addEventListener)
 // document.addEventListener('keydown', keyDown, true);
//document.attachEvent('onkeydown', function(){keyDown();});

function attachKeyPress(action, code, ctrlkey, altkey, shiftkey) {
	var temp = new Object;
	temp['ctrl'] = (ctrlkey ? 'true' : 'false');
	temp['alt'] = (altkey ? 'true' : 'false');
	temp['shift'] = (shiftkey ? 'true' : 'false');
	temp['action'] = action;
	
	kb_actions[code + '_'] = temp;
	
}


// *************************************************************

function keypress_number(decimal) {
	var keypressed = window.event.keyCode;
	var ElementText  = window.event.srcElement.value ;
	if (keypressed == 45){
		if (ElementText.length!=0) {
			window.event.keyCode = 0;
		}
	
	}
	else {
		if (decimal) {
			var Reg = /\./g;
			if (Reg.test(ElementText)) {
				if( (keypressed >= 48 && keypressed <= 57) == false) {
					window.event.keyCode = 0;
				}
			}
			else {
				if ((keypressed >= 48 && keypressed <= 57 || keypressed == 46) == false) {
					window.event.keyCode = 0;
				}
			}
		}

		else {
			if ((keypressed >= 48 && keypressed <= 57) == false) {
				window.event.keyCode = 0;
			}
		}
	}
}

function keypress_date() {
	var keypressed = window.event.keyCode;
	var ElementText  = window.event.srcElement.value ;
	if (keypressed == 45){
		if (ElementText.length!=0) {
			window.event.keyCode = 0;
		}
	}
	else {
		if ((keypressed >= 48 && keypressed <= 57 || keypressed == 45 || keypressed == 47) == false) {
			window.event.keyCode = 0;
			}
	}
}

function setCursor() {
	
//alert(document.frmDefaultAction.newLoad.value);
//document.frmDefaultAction.newLoad.value = 0;
//alert(document.frmDefaultAction.newLoad.value);

	var dontrefresh = getCookie('dontrefresh');
	setCookie('dontrefresh', 'false');
	if (dontrefresh == 'true') return;
	for (x = 0; x < document.frmSelections.length; x++) {
		if (document.frmSelections.elements[x].type == "text" || document.frmSelections.elements[x].type=="password") {
			try {
				document.frmSelections.elements[x].focus();
				firstElement = x;
			} catch (error) {}
			return;
		}
	}
}


// *************************************************************

function openwin(url,wintype)
{

 if (wintype=="screen1") window.open(url, wintype,'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=250,height=500');
 if (wintype=="screen2") window.open(url, wintype,'');
 if (wintype=="screen3") window.open(url, wintype,'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=350,height=150');
}


// Cookie Functions
function setStrData(instr, name, value) {
	var pattern = new RegExp(name + "=([^;])*","gi");
	var str;
	instr = unescape(instr);
	if (!instr || instr=='null' || instr=='' || instr=='undefined') {
		str = name + "=" + escape(value) + '; ';
		return escape(str);
	}
	/*alert(instr);
	alert(pattern.test(instr));*/
	if (pattern.test(instr)) {
		instr = instr.replace(pattern, name + "=" + escape(value));
	} else {
		instr = instr + name + '=' + value + '; ';
	}
	return escape(instr);
	//alert(inst.replace(pattern, "key=" + pairs[1]); // change key value
}
function getStrData(instr, name) {
	var pattern = new RegExp(name + "=([^;])*","gi");
	if (!instr || instr=='null' || instr=='' || instr=='undefined') {
		return instr;
	}
	var results = pattern.exec(instr);
	if (results && results.length > 0) {
		return (unescape(unescape(results[0]))).substr(name.length+1);
	}
	return instr;
}
// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure, subname) {
	if (subname) {
			var value_str = getCookie(name);
			//value_str = value_str.replace(/\?/gi, '\\\?');*/
			//alert('before :' + value_str);
			value = setStrData(value_str, subname, value);
			//alert('after: ' + value);
	}
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name, subname) {
	var dc = document.cookie;
	if (subname) {
			//alert('before g: ' + dc);
			dc = getStrData(dc, name);
			name = subname;
			//alert('after g, subname=' + subname  + ': ' + dc);
	}
  var prefix = name + "=";
  var begin;
  if (dc.substring(0,prefix.length)==prefix) {
    //alert(dc.substring(0,prefix.length));
    begin = 0;
  }
  else {
     begin = dc.indexOf("; " + prefix);
     if (begin == -1) {
       begin = dc.indexOf(prefix);
       if (begin != 0) return null;
     } else
       begin += 2;
  }
  var end = dc.indexOf(";", begin);
  if (end == -1)
    end = dc.length;

  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

var expdate = new Date(); 
expdate.setTime(expdate.getTime() + 20*24*60*60*1000); 

function setVersaCookie(page, name, value) {
	var newStr;
	name = name.replace(/\?/gi, '\\\?');
	var re = new RegExp(name + "=([^&]*)","gi");
	
	newStr = getCookie('page' + page);
	if (newStr == null)			 // if no cookies for this page, set this one as only one
		newStr = name + '=' + value;
		
	else if (newStr.match(re))	// if this name value, already set, update
		newStr.replace(re, name + '=' + value);
	else						// if this name value not present in cookie, add it to end
		newStr = newStr + '&' + name + '=' + value;
	
	var expdate = new Date(); 
	expdate.setTime(expdate.getTime() + 20*24*60*60*1000); 

	setCookie('page' + page, newStr, expdate);
}

function deleteVersaCookie(page, name) {
	var newStr;
	var re = new RegExp(name + "=[^&]*","gi")

	newStr = getCookie('page' + page);
	if (newStr.match(re)) {	// if this name value, already set, delete it
		newStr = newStr.replace(re, '');
		newStr = newStr.replace(/&&/gi, '&');
	}
	setCookie('page' + page, newStr, expdate);
	
}
function openFullScreen() {
					var width, height;
					if (screen.availHeight) { 
						width = screen.availWidth-5;
						height = screen.availHeight-60;
					} else if (window.outerWidth) {
						width = window.outerWidth;
						height = window.outerHeight;
					}
					//alert(height);
			
			var win = window.open(window.location, 'FullScreen', 'top=0, left=0, location=no, titlebar=yes, menubar=no, width=' + width + ', height=' + height + ', resizable=yes, scrollbars=yes, status=yes, toolbar=no');
			win.resizeTo( screen.availWidth, screen.availHeight );

}

function goto_page(page, xid, target, fo) {
	var usefo
	if(fo)
		usefo = fo
	else
		usefo = 'basic display'
	//setCookie('tab', '0', null, null, null, null, page + '_' + xid);
	if (target == 'parent')
		parent.location.href='display.asp?key=' + page + '&fo=' + usefo + '&rm=page&xID=' + xid
	else
		window.location.href='display.asp?key=' + page + '&fo=' + usefo + '&rm=page&xID=' + xid
	
}

function ajaxRefresh(url,target,SQLID)
{	
	//alert(url);
	//$(target).innerHTML = '<span>Loading...Please Wait</span>';
	//$(target).innerHTML = url;
	
	url =  url + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;
	
	if ( $('spin_'+SQLID) ) $('spin_'+SQLID).style.visibility = 'visible';
	
	var myAjax = new Ajax.Updater(target, url, { method: 'get', parameters: "", 
	                              onComplete: function (r) 
								  {													  
									if ( $('XMLRequestJava_'+SQLID) )
									{
										//alert($('XMLRequestJava').value );
									    eval( $('XMLRequestJava_'+SQLID).value );
									}
									
									if ( $('spin_'+SQLID) ) $('spin_'+SQLID).style.visibility = 'hidden';
									
								  } });
}

function ajaxPageActions(url,tablenames)
{

	
	//var extraPars = 'FormatOption=' + escape(getElementByName('FormatOption').value) + '&CurrURL=' + escape(getElementByName('CurrURL').value) + '&Saved=' + escape(getElementByName('Saved').value) + '&EndAction=' + escape(getElementByName('EndAction').value) + '&iframe_hits=' + escape(getElementByName('iframe_hits').value) + '&newLoad=' + escape(getElementByName('newLoad').value) + '&pkg2=' + escape(getElementByName('pkg2').value) + '&Page=' + escape(getElementByName('Page').value) + '&PageID=' + escape(getElementByName('PageID').value) + '&LastUpdated=' + escape(getElementByName('LastUpdated').value) + '&AddEntryOnLinkPaste=' + escape(getElementByName('AddEntryOnLinkPaste').value);
	var extraPars = 'FormatOption=' + escape(getElementByName('FormatOption').value) + '&CurrURL=' + escape(getElementByName('CurrURL').value) + '&Saved=' + escape(getElementByName('Saved').value) + '&EndAction=' + escape(getElementByName('EndAction').value) + '&iframe_hits=' + escape(getElementByName('iframe_hits').value) + '&newLoad=' + escape(getElementByName('newLoad').value) + '&Page=' + escape(getElementByName('Page').value) + '&PageID=' + escape(getElementByName('PageID').value) + '&LastUpdated=' + escape(getElementByName('LastUpdated').value) + '&AddEntryOnLinkPaste=' + escape(getElementByName('AddEntryOnLinkPaste').value);
//	alert(extraPars);
//	extraPars = escape(extraPars);
	//alert(extraPars);
//	document.frmUpdate.pkg2.value = extraPars;
	url = url + "&" + extraPars + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;
	
	//alert(url);
		
	var target = 'divMessage'	
	
	var myAjax = new Ajax.Updater(target, url, { method: 'post', parameters: "", 
	                              onComplete: function (d) 
								  {
									//alert(d.responseText);
									if ( tablenames )
									{
										var tables = tablenames.split(",");
										
										for( var k=0; k< tables.length; k++ )
										{
											//alert(tables[k]);
											RefreshTable(tables[k]);
										}
									}								
								  } });
}

function RefreshTable(tablename)
{
	var tableObj;
	var tbls = document.getElementsByTagName("TABLE");
	
	for( var i=0; i < tbls.length; i++ )
	{
		if (tbls[i].getAttribute("TableName"))
		{
			if (tbls[i].getAttribute("TableName") == tablename)
			{
				tableObj = tbls[i];
				break;
			}
		}
	}
	
	//Now we have the table-- lets find the Refresh Link in previousSibling (center)
	if (tableObj) 
	{
		var aTags = (tableObj.previousSibling).getElementsByTagName("A");
		
		for( var j=0; j < aTags.length; j++ )
		{		
			if (aTags[j].getAttribute("title"))
			{
				if (aTags[j].getAttribute("title") == "Refresh Results")
				{
					aTags[j].click();
					break;
				}
			}
		}
	}
}


function GenLetterLink(Source,xID,LetterPageNum,AltID,SendVia)
{
if (AltID == '') AltID = 0;
//if ((Source > 0) && ( LetterPageNum > 0)){
if (Source > 0){
	//document.frmSelections.action = 'pageactions.asp?action=generateletter&amp;source='+ Source +'&amp;letter=' + LetterPageNum + '&amp;sendvia='+ SendVia +'&amp;altid='+ AltID +'&amp;formatoption=basic display&amp;retrievemode=page&amp;key=8568&amp;ppwp=yes'; 
	//readform(); 
	//document.frmUpdate.CurrURL.value = 'pageactions.asp?action=generateletter&amp;source='+ Source +'&amp;letter=' + LetterPageNum + '&amp;sendvia='+ SendVia +'&amp;altid='+ AltID +'&amp;formatoption=basic display&amp;retrievemode=page&amp;key=8568&amp;ppwp=yes'; 
	//alert(document.frmUpdate.CurrURL.value);
	//document.frmUpdate.submit();
	window.location.href = 'pageactions.asp?action=generateletter&amp;source='+ Source +'&amp;letter=' + LetterPageNum + '&amp;sendvia='+ SendVia +'&amp;altid='+ AltID +'&amp;formatoption=basic display&amp;retrievemode=page&amp;key=8568&amp;xSourseID='+ xID +'&amp;ppwp=yes'; 
}

}

function GenLetterEmailLink(Source,xID,LetterPageNum,AltID,SendVia,Letter,xState)
{
if (AltID == '') AltID = 0;
if (Source > 0){
	if(Letter.indexOf('ADL') > 0) {
		document.frmSelections.action = 'pageactions.asp?action=route&amp;formatoption=refresh&amp;retrievemode=page&amp;buttonid=7106/ADL Letter&amp;passthroughparms=yes&amp;??STATE='+ xState +'&amp;??xID='+ xID; 
		document.frmSelections.submit(); 
	}
	else
	{
		window.location.href = 'pageactions.asp?action=generateletter&amp;source='+ Source +'&amp;letter=' + LetterPageNum + '&amp;sendvia='+ SendVia +'&amp;altid='+ AltID +'&amp;formatoption=basic display&amp;retrievemode=page&amp;key=8568&amp;xSourseID='+ xID +'&amp;ppwp=yes'; 
	}
}

}

function toggleLeftNav()
{
}

function GetURLQvals(url) 
	{
		var keypattern = /key=[\d]*/i;
		var formatoptionpattern = /formatoption=[^&]*/gi;
		var retrievemodepattern = /retrievemode=[^&]*/gi;
		var fopattern = /fo=[^&]*/gi;
		var rmpattern = /rm=[^&]*/gi;
		var amppattern = /&[^?]*/gi;
		//temp = temp.replace(pattern, "key=" + pairs[1]); // change key value
		
		var modurl=url;
		modurl = modurl.substr(modurl.indexOf('asp?')+4);
		modurl = modurl.replace(/&p_id=(\d)*/,'');
		modurl = modurl.replace(keypattern,'');
		modurl = modurl.replace(formatoptionpattern,'');
		modurl = modurl.replace(retrievemodepattern,'');
		modurl = modurl.replace(fopattern,'');
		modurl = modurl.replace(rmpattern,'');
		modurl = modurl.replace(amppattern,'');
		return modurl;
	}

function AdvanceProcessingDate()
{
	var answer = confirm("You are about to advance the processing date.  Are you sure you want to continue?");
	if (answer)
	{
		var url = 'AjaxActions.asp?action=AdvanceProcessingDate'; 
		url = url + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;
		var target = 'divProcessingDate';	
		var myAjax = new Ajax.Updater(target, url, { method: 'post', parameters: "", 
		                              onComplete: function (d) 
									  {
										//alert(d.responseText);
									  } });
	}
	return false;
}


function JumpToCMDebtor(Debtor)
{
		var sessID = getCookie('Open');
		//alert(sessID);
		//return false;
		
		var url = 'AjaxActions.asp?action=JumpToCMDebtor'; 
		url = url + '&Debtor='+ Debtor ;
		url = url + '&sessID='+ sessID ;
		
		url = url + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;
		var target = '';	
		var myAjax = new Ajax.Updater(target, url, { method: 'post', parameters: "", 
		                              onComplete: function (d) 
									  {
										if (d.responseText.indexOf('@@') > 0) {
											var start = d.responseText.indexOf('@@DebtorURL=');
											var end = d.responseText.indexOf('@@#@@');
											var jumpUrl = d.responseText.substring(start+12, end);
											if (jumpUrl.length > 0) {
												window.location.href = jumpUrl;
											}
										}
									  } });

	return false;
}


function GetGenLetters(State,User,Req,SourcePage,Source,Alt,Arena,xID)
{
	//display.asp?formatoption=search%20results&key=7106&retrievemode=searchpage&KSource=8524&id=99999&??STATE=FL%&??USER=7007%&??REQR=EXEC%&??SOURCEPAGE=111163&Source=8587&??ALTID=8524%&??ARENA=Sales%&xID=15114
	// If we have already ajaxed it once, no need to do it again!
	if ($('GenLetterResultsClose')) {
		$('GenLetterResults').style.display ='';
		return false;
	}
	
		var url = 'linkedsearch_direct.asp?id=7104/FastSQL'; 
		url = url + '&??STATE=' + State;
		url = url + '&??USER=' + User;
		url = url + '&??REQR=' + Req;
		url = url + '&??SOURCEPAGE=' + SourcePage;
		url = url + '&??GENSOURCE=' + Source;
		url = url + '&??ARENA=' + Arena;
		url = url + '&??ALTID=' + Alt;
		url = url + '&??xID=' + xID;
		url = url + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;

		var target = 'GenLetterResults';
		var myAjax = new Ajax.Updater(target, url, { method: 'post', parameters: "", 
		                              onComplete: function (d) 
									  {
										$('GenLetterResults').innerHTML = '<div id="GenLetterResultsClose" style="position:absolute;top:1;left:1;background:white;width:99%;text-align:right;"><img src="images/close.gif" onclick="$(\'GenLetterResults\').style.display =\'none\';"/></div><br/>' + d.responseText;
										$('GenLetterResults').style.display ='';
									  } });

	return false;
}



function MenuClick (PDClient,URL)
{
	var ClientID = 0;
	if (PDClient == '')
	{
		var IsXID = getURLParm('xID', '');
		if (IsXID == '') 
		{
			alert('No Client found, please run this report from a company page.');
		}
		else
		{
			if(VerifySave(null, this))  
			{
				//document.frmSelections.action = 'display.asp?formatoption=search%20results&amp;key=7105&amp;retrievemode=searchpage&amp;Source=7003&amp;id=127198&amp;??ARENA=Collections'; 
				document.frmSelections.action = URL.replace('??CLIENT=','??CLIENT=' + ClientID + '&'); 
				document.frmSelections.submit();
			}
		}
	}

}

var promptWin;

function refreshTables(tablenames) {
	//alert(tablenames);
	var tbls = tablenames.split(',');
	for (var j=0; j < tbls.length; j++) {
		var url = $(tbls[j]).getAttribute('src');
		var custom_refresh = $(tbls[j]).getAttribute('custom_refresh');
		if (custom_refresh) {
			eval(custom_refresh);
		} else if (url) {
			if (tbls[j].nodeName == 'TABLE') {
				new Ajax.Updater(tbls[j].parentNode, url + '&xid=' + getURLParm('xID=') + '&rnd='+ (Math.random() * Date.parse(new Date()) ) , {});
			} else {
				new Ajax.Updater(tbls[j], url + '&xid=' + getURLParm('xID=') + '&rnd='+ (Math.random() * Date.parse(new Date()) ) , {});
			}
		} else
			alert('No URL specified for ' + tbls[j]);
	}

}
/*** matchRecursiveRegExp
	Accepts a string to search, a left and right  format  delimiter
	as regex patterns, and optional regex flags. Returns  an  array
	of matches, allowing nested instances of left/right delimiters.
	Use the "g" flag to return  all  matches,  otherwise  only  the
	first is returned. Be careful  to  ensure  that  the  left  and
	right format delimiters  produce  mutually  exclusive  matches.
	Backreferences are not supported  within  the  right  delimiter
	due to how it is internally combined with the  left  delimiter.
	When matching strings whose format  delimiters  are  unbalanced
	to the  left  or  right,  the  output  is  intentionally  as  a
	conventional  regex  library  with  recursion   support   would
	produce, e.g. "<<x>" and "<x>>" both produce ["x"]  when  using
	"<" and ">" as the delimiters (both strings contain  a  single,
	balanced instance of "<x>").

	examples:
		matchRecursiveRegExp("test", "\\(", "\\)")
			returns: []
		matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
			returns: ["t<<e>><s>", ""]
		matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
			returns: ["test"]

*/
function matchRecursiveRegExp (str, left, right, flags) {
	var	f = flags || "",
		g = f.indexOf("g") > -1,
		x = new RegExp(left + "|" + right, "g" + f),
		l = new RegExp(left, f.replace(/g/g, "")),
		a = [],
		t, s, m;

	do {
		t = 0;
		while (m = x.exec(str)) {
			if (l.test(m[0])) {
				if (!t++) s = x.lastIndex;
			} else if (t) {
				if (!--t) {
					a.push(str.slice(s, m.index));
					if (!g) return a;
				}
			}
		}
	} while (t && (x.lastIndex = s));

	return a;
}

function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i > 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}



function GenPAButtons(tablenames, ajax_options) {
	return buttonStr = "<CENTER>" + new st_button("checkAddRemove(); ajaxPromptActions('pageactions.asp?action=applyprompts&amp;formatoption=refresh&amp;retrievemode=page', '" + tablenames + "');  return false;", "", "UIButtonred", "Generate PA", "cmd_GenPA", "Generate PA", null).create()
		+ new st_button("promptWin.close(); return false;", "", "UIButtonred", "Cancel and return to PA", "cmd_Cancel", "Cancel and return to PA", null).create() + "</CENTER>";
}

function promptButtons(tablenames, ajax_options) {
	if (ajax_options['noDefaultButtons'] ) return '';
	if (ajax_options['customButtonJS']) return eval(ajax_options['customButtonJS']); 
	return buttonStr = "<CENTER>" + new st_button("ajaxPromptActions('pageactions.asp?action=applyprompts&amp;formatoption=refresh&amp;retrievemode=page', '" + tablenames + "');  return false;", "", "UIButtonred", "Submit", "cmd_Submit", "Submit", null).create()
		+ new st_button("promptWin.close(); return false;", "", "UIButtonred", "Cancel", "cmd_Cancel", "Cancel", null).create() + "</CENTER>";
}

var postPromptActions = new Array();
function ajaxPromptActions(url, tablenames) {
	document.frmPrompt.action = url;
	$('frmPrompt').request( {
		onComplete: function (d) {
			//promptWin.setHTMLContent(d.responseText);
			//alert(d.responseText);

			var start, end, formStr2, formStr3, messageFlag, MessageIs
			//----Check to see if we have a message
			start = d.responseText.indexOf('<div id="divMessage"')
			if (start >= 0){			
				start = d.responseText.indexOf('<div id="divMessage"')
				formStr2 = d.responseText.substring(start, d.responseText.length - 1);
				end = formStr2.indexOf('</div>')
				formStr2 = formStr2.substring(0, end + 6);
				formStr3 = matchRecursiveRegExp(formStr2, "<div\\b[^>]*>", "</div>", "gi");	//will pull contents of a div or any tags
				messageFlag = true;
				MessageIs = formStr3;
			}
			
			start = 0;
			end = 0;
			formStr2 = '';
			formStr3 = '';
			//----Check to see if we need to open a file
			//----divPopUpFile was added to display.asp and contains the filename and path to open
			start = d.responseText.indexOf('<div id="divPopUpFile"')
			if (start >= 0){
				formStr2 = d.responseText.substring(start, d.responseText.length - 1);
				end = formStr2.indexOf('</div>')
				formStr2 = formStr2.substring(0, end + 6);
				formStr3 = matchRecursiveRegExp(formStr2, "<div\\b[^>]*>", "</div>", "gi");	//will pull contents of a div or any tags
				window.open(formStr3);
			}					
			try{
				document.body.removeChild(ajaxed.prototype.indicator);	// this shouldn't be required... but when moving from one dialog to another... it appears to be.
			}
			catch(e){};

			while (postPromptActions.length > 0) {
				var temp = postPromptActions.shift();
				eval(temp);
			}			
			promptWin.setHTMLContent('');
			promptWin.close();
			//----If Message was found, put it in divMessage
			if (messageFlag == true){
				$('divMessage').innerHTML = MessageIs;
			}

			refreshTables(tablenames);

		}
	});
}

var dialogAborted;
function abortDialog() {
	dialogAborted = true;
}

var sc_list ;
function ajaxRouter(url, tablenames, options) {
	//alert(url);
	document.frmSelections.action = url;
	$('frmSelections').request( { 
		onComplete: function (d) { 
			//$('divMessage').innerHTML = d.responseText;
			var overrideHeight=0; var overrideWidth=0;
			if (d.responseText.indexOf('<div id="divPromptBody"') == -1 && url.substr(0, ('fastsql_v2_direct.asp').length) != 'fastsql_v2_direct.asp') {
				
				var start, end, formStr2, formStr3
				start = d.responseText.indexOf('<div id="divMessage"')
				if (start >= 0){
					formStr2 = d.responseText.substring(start, d.responseText.length - 1);
					end = formStr2.indexOf('</div>')
					formStr2 = formStr2.substring(0, end + 6);
					formStr3 = matchRecursiveRegExp(formStr2, "<div\\b[^>]*>", "</div>", "gi");	//will pull contents of a div or any tags
					$('divMessage').innerHTML = formStr3;
				}
				start = 0;
				end = 0;
				formStr2 = '';
				formStr3 = '';
				start = d.responseText.indexOf('<div id="divPopUpFile"')
				if (start >= 0){
					formStr2 = d.responseText.substring(start, d.responseText.length - 1);
					end = formStr2.indexOf('</div>')
					formStr2 = formStr2.substring(0, end + 6);
					formStr3 = matchRecursiveRegExp(formStr2, "<div\\b[^>]*>", "</div>", "gi");	//will pull contents of a div or any tags
					window.open(formStr3);
				}				
				if (tablenames!='')
					{
						refreshTables(tablenames);
					}
				return true;
			}
			var formStr;
			if (d.responseText.indexOf('<div id="divPromptBody"') > 0) {
				
				var start = d.responseText.indexOf("<Form")
				var end = d.responseText.indexOf("</Form>")
				//var formStr =  new RegExp('<FORM\b[^>]*>(.*?)</FORM>', 'i');
				formStr = d.responseText.substring(start, end + 7).replace(/frmSelections/gi, 'frmPrompt');
			} else if (url.substr(0, ('fastsql_v2_direct.asp').length) == 'fastsql_v2_direct.asp') {
				formStr = '<Form name="frmPrompt" method="Post">'
					+ '<input type="hidden" name="CurrURL" value="' + url + '&formatoption=prompt' + '"/>'
					+ d.responseText + '</Form>';
					//+ '<input type="hidden" name="CurrURL" value="http://stsrv2/pc/display.asp?formatoption=prompt&key=299891&retrievemode=itemid&??xid=109&sourcepage=9417"/>'
					//+ '<input type="hidden" name="CurrURL" value="' + url + '"/>'
			}
			var ajax_options = new Hash({className: "alphacube", width:650, height:500, zIndex: 100, resizable: false, title: "Prompt", hideEffect:Element.hide, showEffect:Element.show, draggable:true, wiredDrag: true, destroyOnClose: true });
			ajax_options = ajax_options.merge(options);
			promptWin = new Window(ajax_options);
			//promptWin.getContent().innerHTML= formStr + promptButtons(tablenames);
			promptWin.setHTMLContent(formStr + promptButtons(tablenames, ajax_options));
			dialogAborted = false;
			/*sc_list = promptWin.getContent().getElementsByTagName('i');
			alert(sc_list.length);
			alert($(sc_list[0]).innerHTML);
			for (var x=0; x < sc_list.length; x++)
				if (sc_list[x].innerHTML) eval(sc_list[" + x + "].innerHTML);*/
			/*
			sc_list = promptWin.getContent().getElementsByTagName('SCRIPT')
			for (var x=0; x < sc_list.length; x++)
				if (sc_list[x].innerHTML)
					if (sc_list[x].getAttribute('immediate')  == 'true') {
						eval(sc_list[x].innerHTML);
						if (!dialogAborted) break;
					} else {
						setTimeout("eval(sc_list[" + x + "].innerHTML);", 10)
					}
			*/
			if (!dialogAborted) promptWin.showCenter(true);
			else promptWin.setHTMLContent('');
		}
	});
}

	
// *************************************************************
// TABLE SORT FUNCTIONS
// *************************************************************
function sc(obj) { // show cal
	//showCalendar(obj.parentNode.getElementsByTagName('INPUT')[0],'x','y','yearFrom','m/d/y')
	//showCalendar(obj.parentNode.getElementsByTagName('INPUT')[0],'x','y','yearFrom','m/d/y')
	var prevItems = $(obj).previousSiblings();
	for (var j=0; j < prevItems.length; j++)
		if (prevItems[j].nodeName == 'INPUT') {
			showCalendar(prevItems[j],'x','y','yearFrom','m/d/y')
			return;
		}
	alert('Did not find input for date selection.');
}

function ExecuteEmailLink(obj) { // show cal
	//showCalendar(obj.parentNode.getElementsByTagName('INPUT')[0],'x','y','yearFrom','m/d/y')
	//showCalendar(obj.parentNode.getElementsByTagName('INPUT')[0],'x','y','yearFrom','m/d/y')
	var prevItems = $(obj).previousSiblings();
	for (var j=0; j < prevItems.length; j++)
		if (prevItems[j].nodeName == 'INPUT') {
				window.location.href = 'mailto:' + prevItems[j].value;
			return;
		}
	alert('Did not find input for email selection.');
}
//Decimal to Hex
function d2h(d) {return d.toString(16);}
//Hex to Decimal
function h2d(h) {return parseInt(h,16);} 

function getCID(){
var clid = getCookie('CID');
//alert(clid);
if (clid=='')
	alert('No client found!');
else
	return h2d(clid);
}

function getCXID(){
var CXID = getCookie('CXID');
//alert(clid);
if (CXID=='')
	alert('No client found!');
else
	return h2d(CXID);
}


function LoadCCPNotes(id)
{
	//alert('ID: x'+id+'x');
	if (!id || id=='null' || id=='' || id=='undefined' || id=='NaN') 
		{
			alert('No Company found.'); return false;
		}
	var posturl = 'CompanyNotes.asp';
    var pars = 'id=' + id + '&rnd=' + Math.random() * 9999;
	if (pars!='') posturl = posturl+'?'+pars;
	var win = new Window({url: posturl, options: {method: 'get'}, className: "alphacube",  width:610, height:450, zIndex: 100, resizable: true, title: "Daily Transactions", hideEffect:Element.hide, showEffect:Element.show, draggable:true, wiredDrag: true})
		win.showCenter();
    return false;
}
function ClearCompNotes(id)
{
	if (confirm("Are you sure you would like to clear the notes?")) {
		var url = 'CompanyNotes.asp?cid=' + id; 
		url = url + '&action=Clear'
		url = url + '&ajaxrnd='+ (Math.random() * Date.parse(new Date())) ;

		var target = 'divNothing';
		var myAjax = new Ajax.Updater(target, url, { method: 'post', parameters: "", 
		                              onComplete: function (d) 
									  {
										//
									  } });
	}
	return false;

}

var ua = navigator.userAgent.toLowerCase()
var isIE = ( (ua.indexOf('msie') != -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) ); 
var css_offset_ff = isIE ? 0 : 1;
var css_offset_ie = isIE ? 1 : 0;

onload_actions.push('attachKeyPress("if (document.getElementById(\'Save and Return\')) {document.getElementById(\'Save and Return\').onclick();}", 83, true);');
// -->
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/date.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/msgbox.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/button_gen.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/prototype/prototype.js"></SCRIPT>');
document.write('<script type="text/javascript" src="javascripts/effects.js"> </script>');
document.write('<script type="text/javascript" src="javascripts/window.js"> </script>');
document.write('<script type="text/javascript" src="javascripts/debug.js"> </script>');
document.write('<link href="themes/default.css" rel="stylesheet" type="text/css"></link>');
document.write('<link href="themes/alphacube.css" rel="stylesheet" type="text/css"></link>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/prototype/ajaxed.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/simple_server_comm.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="ajaxactions.js"></SCRIPT>');
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="js/CM_MenuLinks.js"></SCRIPT>');
			
