//Begin MiscFunctions.fun

var PS_FLAG_ITEMDATA=1
var PS_FLAG_VALUE=2
var PS_FLAG_TEXT=3

var wDebugWindow;	//shortcut to debug window
var bDebug;			//allows debug statements to appear in debug window

var glPageLoadedAt // Used to check if session has timedout
var gbSessionTimedOut = false
var gbSessionTimedOutAlertShown = false 

var BBWEBCLIENT = "/BBWebClient";
var BBWEBCLIENT_SCRIPTS = BBWEBCLIENT + "/scripts";
var BBWEBCLIENT_HELPERS = BBWEBCLIENT_SCRIPTS + "/helpers";
var BBWEBCLIENT_SPELLCHECK_FORM = BBWEBCLIENT_SCRIPTS + "/SpellCheck/SpellCheckForm.htm";
var BBWEBCLIENT_INPUTBOX_FORM = BBWEBCLIENT_HELPERS + "/InputBox.htm";
var BBWEBCLIENT_INPUTBOX_FORM_MAC = BBWEBCLIENT_HELPERS + "/InputBoxMac.htm";

function getRadioListValue(oListItems){

	for(var i=0;i < oListItems.length;i++){
		if(oListItems.item(i).checked){
			return oListItems.item(i).value
		}
	}
	return -1
}

function getCheckListValue(oListItems){
	var sRetVal = ''
	for(var i=0;i < oListItems.length;i++){
		if(oListItems.item(i).checked){
			if(sRetVal.length > 0 ){
				sRetVal += ', '
			}
			sRetVal += oListItems.item(i).value
		}
	}
	return sRetVal
}


function OneOf(value){

	for(var i = 1; i < OneOf.arguments.length; i++){
		if(value == OneOf.arguments[i]) return true
	}

	return false
}

function SetChildrenProp(oChild, sProp, vValue, bDoContainer){

	if((oChild.children==null) || (oChild.children.length == 0)){

		oChild[sProp] = vValue;
		return true;

	}else{

		for(var i = 0; i < oChild.children.length; i ++){
			SetChildrenProp(oChild.children(i),sProp, vValue, true);
		}
		if(bDoContainer == true){
			oChild[sProp] = vValue;
		}
	}
}

function SetChildrenStyle(oChild, sStyle, vValue, bDoContainer){

	if((oChild.children==null) || (oChild.children.length == 0)){

		oChild.style[sStyle] = vValue;
		return true;

	}else{

		if(bDoContainer == true){
			oChild.style[sStyle] = vValue;
		}

		for(var i = 0; i < oChild.children.length; i ++){
			SetChildrenStyle(oChild.children(i),sStyle, vValue, true);
		}
	}
}

function PositionSelect(oList, vValue, byFlag){

	var vField;

	switch (byFlag){
		case PS_FLAG_ITEMDATA:
			vField = 'itemData'
			break
		case PS_FLAG_VALUE:
			vField = 'value'
			break
		case PS_FLAG_TEXT:
			vField = 'text'
			break
	}

	if(oList.options.length == 'undefined'){
	//}else if(oList.options.length == 1){
	//	if(oList.options(0)[vField] == vValue){
	//		oList.options(0).selected = true
	//	}
	}else{
		for(var i=0; i < oList.options.length; i++){
			if(oList.options[i][vField] == vValue){
				try {
					oList.options[i].selected = true
				} catch(e){} //a bug(?) in IE 5.5 will throw an error when setting the selected property
				if(!oList.multiple){
					oList.selectedIndex = i
				}
				return true
			}
		}
	}
	return false
}


function PositionOnItemData(olist, itemData){

	if(!PositionSelect(olist, itemData, PS_FLAG_ITEMDATA)){
		olist.selectedIndex = 0
	}
}

function AddListOption(oList, sText, vValue, sItemData){
	var oOption=oList.ownerDocument.createElement('OPTION')
	var sValue
	if(bIsFiveFive){
		oOption.innerText = sText
		if(vValue != null){ oOption.value = vValue }

		oList.appendChild(oOption)
	}else if(bIsMacIE){
		oOption.text = sText
		if(vValue != null){ oOption.value = vValue }
		oList.options[oList.options.length]=oOption
	}else{
		oOption.text = sText
		if(vValue != null){ oOption.value = vValue }
		oList.add(oOption,null)
	}
	return oOption
}

function AddToList(oList,vValue,sText,nItemData){
	var Opt = oList.document.createElement('OPTION');
	Opt.value = vValue
	Opt.text = sText
	//oList.add(Opt);
	//oList.options[oList.options.length-1].itemData = nItemData
	Opt.itemData = nItemData
	oList.appendChild(Opt)

	oList.selectedIndex = oList.options.length-1
}

function ClearList(oList)
{
	if(oList.options.length != 'undefined')
	{
	
		var total
	
		total = (oList.options.length -1)
	
		for(var cnt=total; cnt>=0; cnt--)
			oList.removeChild(oList.options[cnt])
	}
}

function RemoveFromList(oList, vValue, byFlag){

	var vField;

	switch (byFlag){
		case PS_FLAG_ITEMDATA:
			vField = 'itemData'
			break
		case PS_FLAG_VALUE:
			vField = 'value'
			break
		case PS_FLAG_TEXT:
			vField = 'text'
			break
	}

	if(oList.options.length != 'undefined'){
		for(var i=0; i < oList.options.length; i++){
			// used to use options(i) but FF didn't like it. [0] works on both browsers
			if(oList.options[i][vField] == vValue){
				if(oList.selectedIndex == i){oList.selectedIndex == -1}
				
				// this works in IE but is not recognized in FF:
				// oList.options.remove (i)
				
				// this works in both browsers
				oList.removeChild(oList.options[i])
				
				return true
			}
		}
	}
	return false
}

function DisAbleAllControls(bEnable, sPropTag, arr, oContainer){
//This function will toggle the disabled attribute
//of all form controls contained in the oParent
//Not sure what sPropTag is used for...legacy...
//Might remove arr and sPropTag in the future...
//arr is used to keep a list of controls to re-enable, though we could just
//use the container again...

	if(bEnable){
		for(var i=0; i < arr.length; i++){
			setFieldEnabled(arr[i],true)
		}
	}else{
		var a;
		a = oContainer.getElementsByTagName('SELECT');
		for(var x=0;x<a.length;x++){
			setFieldEnabled(a[x],false)
			a[x].setAttribute(sPropTag,true)
			arr[arr.length] = a[x]
		}
		a = oContainer.getElementsByTagName('TEXTAREA');
		for(var x=0;x<a.length;x++){
			setFieldEnabled(a[x],false)
			a[x].setAttribute(sPropTag,true)
			arr[arr.length] = a[x]
		}
		a = oContainer.getElementsByTagName('IMG');
		for(var x=0;x<a.length;x++){
			setFieldEnabled(a[x],false)
			a[x].setAttribute(sPropTag,true)
			arr[arr.length] = a[x]
		}
		a = oContainer.getElementsByTagName('INPUT');
		for(var x=0;x<a.length;x++){
			if(a[x].type!='hidden'){
			setFieldEnabled(a[x],false)
				a[x].setAttribute(sPropTag,true)
				arr[arr.length] = a[x]
			}
		}
	}
}

function LoadComboFromTabText(oSelect,sText,bUseItemData){
	/*
		Loads a Select list from a tab delimited string of format:
			value<tab>text<tab>

		IMPORTANT:the last entry must have a <tab> char

		bUseItemData flag, if true, will put value in the itemData property
			and set value & text to text



	*/

	if(bUseItemData == null){bUseItemData = false}

	var a = new Array()
	a = sText.split('\t')

	for(var i = 0; i < a.length -1; i++){
		Opt = oSelect.document.createElement('OPTION');
		if(bUseItemData){
			Opt.itemData = a[i++]
			Opt.value = a[i]
		}else{
			Opt.value = a[i++]
		}

		if(oLibPage.bIsFiveFive){
			Opt.innerText = a[i]
			oSelect.appendChild(Opt);
		}else{
			Opt.text = a[i]
			oSelect.add(Opt);
		}
	}

	if(a.length != 0){
		oSelect.selectedIndex = 0
	}
}

function LoadComboFromTabTextEx(oSelect,sText,nValueIndex,nTextIndex,nItemDataIndex){
	/*
		Loads a Select list from a tab delimited string of format:
			x<tab>x<tab>x<tab>...

		IMPORTANT:the last entry must have a <tab> char

		nValueIndex,nTextIndex,nItemDataIndex [0,1,2] indicate the orders of each item
			in sText. Set = -1 to disable

	*/

	try {
		oSelect.options.length = 0
	} catch (e){
		while (oSelect.options.length > 0){
			oSelect.options.remove(0)
		}
	}

	var nNumItems = 0
	if(nValueIndex != -1){nNumItems++}
	if((nTextIndex != -1) && (nTextIndex != nValueIndex) ){nNumItems++}
	if(nItemDataIndex != -1 && !oLibPage.OneOf(nItemDataIndex,nTextIndex,nValueIndex)){nNumItems++}

	var a = new Array()
	a = sText.split('\t')

	for(var i = 0; i < a.length -1; ){
		Opt = oSelect.document.createElement('OPTION');

		if(nValueIndex != -1){Opt.value = a[i + nValueIndex]}
		if(nItemDataIndex != -1){Opt.itemData = a[i + nItemDataIndex]}
		if(oLibPage.bIsFiveFive){
			if(nTextIndex != -1){Opt.innerText = a[i + nTextIndex]}
			oSelect.appendChild(Opt);
		}else{
			if(nTextIndex != -1){Opt.text = a[i + nTextIndex]}
			oSelect.add(Opt);
		}

		i += nNumItems
	}

	if(a.length != 0){
		oSelect.selectedIndex = 0
	}
}

function ClearField(el){
	switch (el.tagName){

		case 'INPUT' :
			el.value = ''
			break;

		case 'SELECT' :
			el.selectedIndex = -1
			break;

	}
}

function _ShowModalDialog(sModalURL, oWindow, sFeatures){
	// if(oWindow.showModalDialog){	// could also do this instead
	if(bSimulateModal){
		return bbShowModalDialog(sModalURL, oWindow, sFeatures)
	}else{
		var obj = oWindow.showModalDialog(sModalURL, oWindow, sFeatures)
		if(obj && obj.bRevertingToLogin){
			oWindow.bRevertingToLogin = true
			oWindow.document.location.replace(obj.href)
		}
			
		return obj
	}
}	

function _CloseModalDialog(oTopWindow, iDialogType, bIgnoreParent) {
	if (bSimulateModal) {
		bbCloseModalDialog(iDialogType, bIgnoreParent)
	} else {
		//window.top.close()	// need to pass in the top window instead.
		oTopWindow.close()
	}
}

function _CloseAllModals() {
	if (oLibPage.moModals) {
		if (oLibPage.moModals.length > 0) {
			var iLen = oLibPage.moModals.length 
			for (i=iLen-1; i >= 0; i--){
				var iDialogID = oLibPage.moModals[i].id
				//Don't let anything stop us from closing these modals.  This is getting messy.  Might soon need an overhaul of the modal simulation.
				try{ //gregorymc 20080717 [CR301289-052108]:  really, don't let *anything*, even "access is denied" errors, "stop us from closing these modals".
				    oLibPage.moModals[i].oModal.document.body.onunload = null
				    oLibPage.moModals[i].oModal.document.body.onbeforeunload = null
				}catch(e){} 
				oLibPage._CloseModalDialog(null, iDialogID, true)
			}
		}
	}	
}

function _ShowModelessDialog(sModalURL, oWindow, sFeatures, sTitle){
	// if(oWindow.showModalDialog){	// could also do this instead
	if(bSimulateModal){
		return bbShowModalDialog(sModalURL, oWindow, sFeatures, sTitle, true)
	}else{
		var obj=oWindow.showModelessDialog(sModalURL, oWindow, sFeatures)
		return obj
	}
}	



function openStandardModal(owindow, sURL, nHeight, nWidth, sPageTitle, bNoDelay, bCalcForLargeFonts){
//owindow generally is 'self'

	if(bNoDelay == null){
		bNoDelay = true
	}

	if(bCalcForLargeFonts == null){
		bCalcForLargeFonts = true
	}

	var sDelayQS

	if(bNoDelay){
		sDelayQS='?NoDelay=1'
	}else{
		sDelayQS =''
	}

	if(bCalcForLargeFonts){
		nWidth = DialogWidth(nWidth)
		nHeight = DialogHeight(nHeight)
	}
	return oModal=owindow.showModalDialog(sURL,owindow,BuildModalFeaturesString(owindow, nHeight, nWidth));
}

function openStandardModeless(owindow, sURL, nHeight, nWidth, sPageTitle, bNoDelay, bCalcForLargeFonts){
//owindow generally is 'self'

	if(bNoDelay == null){
		bNoDelay = true
	}

	if(bCalcForLargeFonts == null){
		bCalcForLargeFonts = true
	}

	var sDelayQS

	if(bNoDelay){
		sDelayQS='?NoDelay=1'
	}else{
		sDelayQS =''
	}

	if(bCalcForLargeFonts){
		nWidth = DialogWidth(nWidth)
		nHeight = DialogHeight(nHeight)
	}

	return oModal=owindow.showModelessDialog(sURL,owindow,BuildModalFeaturesString(owindow, nHeight, nWidth));
}

function BuildModalFeaturesString(owindow, nHeight, nWidth){

	var nTop = ((owindow.screen.availHeight - nHeight) / 2)
	var nLeft = ((owindow.screen.availWidth - nWidth) / 2)

	return 'dialogwidth='+nWidth+'px;dialogHeight='+nHeight+'px;status=no;'
}



function RecordSearch(owindow,sSearchTypes,sWindowName,bAddNew,bOpenAsList,sCustomProps,bSearchOnLoad,bReadOnly){

	/*
		owindow generally is 'self'
		sCustomProps = Optional; QueryString of Custom Properties to set, in the form of:
						CS_propertyname=value
	*/

	/*
	optional 9th arg is custom callback name - otherwise FinishedSearch will be called
	*/

	var sCallbackName = 'FinishedSearch'

	if(RecordSearch.arguments.length > 8){
		sCallbackName = RecordSearch.arguments[8]
	}


	if((sSearchTypes==null) || (sSearchTypes.length == 0)){
		alert('Assert:You must pass in a SearchType to RecordSearch')
		return false
	}

	if(sCustomProps != null){
		if((sCustomProps.length != 0) && (sCustomProps.substr(0,1) != '&')){
			sCustomProps = '&' + sCustomProps
		}
	}else{
		sCustomProps = ''
	}

	if(!sWindowName){sWindowName='Open'}

	var sUrl = oLibPage.BuildURL('sys/scripts/search/Search.asp','SearchTypes=' + sSearchTypes+ '&bAddNew=' + bAddNew +
									'&bOpenAsList='+ bOpenAsList + sCustomProps + '&bSearchOnLoad=' + bSearchOnLoad +
									'&bReadOnly=' + bReadOnly +
									'&sCallback=' + sCallbackName)

	openStandardModal(owindow, sUrl, 540, 750, sWindowName) //h,w
	return true
}

function ShowPleaseWait(oWindow, sMsg){

	if(!oLibPage.bIsMac){
		return ShowPleaseWaitModeLess(self, sMsg)
	}else{
		var w = oLibPage.DialogWidth(275)
		var h = oLibPage.DialogHeight(150)
		if(oLibPage.bIsMac){
			var l = 1 * ((document.body.clientWidth/2) - (w/2))
			var t = 1 * ((document.body.clientHeight/2) - (h/2))
		}else{
			var l = 1 * ((window.screen.width/2) - (w/2))
			var t = 1 * ((window.screen.height/2) - (h/2))
		}

		var sUrl = oLibPage.BuildURL('sys/scripts/miscPages/PleaseWait.asp','msg=' + sMsg)
		return oWindow.open(sUrl,'PleaseWait','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height=' + h + ',top= ' + t + ',left = ' + l + ',fullscreen=0,channelmode=0')
	}
}

function ShowPleaseWaitModal(oWindow, sMsg, sCallback){

	var w = oLibPage.DialogWidth(325)
	var h = oLibPage.DialogHeight(150)
	if(oLibPage.bIsMacIE){
		var l = 1 * ((document.body.clientWidth/2) - (w/2))
		var t = 1 * ((document.body.clientHeight/2) - (h/2))
	}else{
		var l = 1 * ((window.screen.width/2) - (w/2))
		var t = 1 * ((window.screen.height/2) - (h/2))
	}

	var sUrl = oLibPage.BuildURL('sys/scripts/miscpages/PleaseWait.asp?msg=' + escape(sMsg) + '&Callback=' + sCallback)
	//oLibPage.openStandardModal(oWindow, sUrl, h, w, '', true)
	oLibPage.openStandardModeless(oWindow, sUrl, h, w, '', true)

}


function ShowPleaseWaitModeLess(oWindow, sMsg){
	if(oLibPage.bIsMac){
		return ShowPleaseWait(oWindow, sMsg)
	}else{
		var w = oLibPage.DialogWidth(275)
		var h = oLibPage.DialogHeight(150)
		var sUrl = oLibPage.BuildURL('sys/scripts/miscPages/PleaseWait.asp','msg=' + sMsg)
		var sFeatures = BuildModalFeaturesString(window, h, w) + ';help:no;status:no'
		return oWindow.showModelessDialog(sUrl,oWindow,sFeatures)
	}
}

function ShowModalRS(oWindow, sMsg, sURL, sMethod, sParams){

	var w = oLibPage.DialogWidth(325)
	var h = oLibPage.DialogHeight(150)
	if(oLibPage.bIsMacIE){
		var l = 1 * ((document.body.clientWidth/2) - (w/2))
		var t = 1 * ((document.body.clientHeight/2) - (h/2))
	}else{
		var l = 1 * ((window.screen.width/2) - (w/2))
		var t = 1 * ((window.screen.height/2) - (h/2))
	}

	var sUrl = oLibPage.BuildURL('sys/scripts/remoteScripting/ModalRS.asp?msg=' + escape(sMsg) + '&url=' + escape(sURL) + '&method=' + escape(sMethod) + sParams)
	return oLibPage.openStandardModal(oWindow, sUrl, h, w, '', true)

}

function HandleTabBoundary(e, PrevCtl, NextCtl){
	//e should be event; PrevCtl - Control to move to on ShiftTab; NextCtl - Control to move to on Tab
	//KeyDown event handler to cycle to first control or last control
	if(e.keyCode==9){
		e.returnValue=false;
		if(e.shiftKey){
			PrevCtl.focus()
		}else{
			NextCtl.focus()
		}
	}
}

function ExportPrompt(owindow, sContext, DefaultFileName, DefaultFormat, bIncludeRepWrite, bIsMailExport){

	if(sContext == ''){
		alert("bbAssert: You must pass in a Context to ExportPrompt")
		return null
	}
	var sParams = 'Context=' + sContext

	if(DefaultFileName != null){sParams = sParams + '&Filename=' + escape(DefaultFileName)}
	if(DefaultFormat != null){sParams = sParams + '&Format=' + DefaultFormat}
	if(bIncludeRepWrite != null){sParams = sParams + '&IncludeRepWrite=' + bIncludeRepWrite}
	if(bIsMailExport != null){sParams = sParams + '&bIsMailExport=-1'}

	var sUrl = oLibPage.BuildURL('sys/scripts/export/ExportPrompt.asp',sParams)
	if(bIsMailExport != null){
		return oLibPage.openStandardModal(owindow, sUrl, 235, 475, 'Export')
	}else{
		return oLibPage.openStandardModal(owindow, sUrl, 225, 475, 'Export')
	}

}

function toFileName(sText, nLen){
	if(nLen == null){nLen = 8}

	var oRE = /[\\\/:\*?"<>\ |]|^con$|^aux$|^prn$|^lpt1$|^lpt2$|^lpt3$|^lpt4$|^com1$|^com2$/g
	return (sText.replace(oRE, '_')).substr(0,nLen)

}

function OpenExportWindow(oWindow)	{

	var w = oLibPage.DialogWidth(475)
	var h = oLibPage.DialogHeight(200)
	if(oLibPage.bIsMacIE){
		var l = 1 * ((document.body.clientWidth/2) - (w/2))
		var t = 1 * ((document.body.clientHeight/2) - (h/2))
	}else{
		var l = 1 * ((window.screen.width/2) - (w/2))
		var t = 1 * ((window.screen.height/2) - (h/2))
	}

	var oDate = new Date()
	var sWindowName = "ExportWindow" + oDate.getTime()

	var o = window.open("", sWindowName ,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + w + ',height=' + h + ',top= ' + t + ',left = ' + l + ',fullscreen=0,channelmode=0')
	if(oWindow){
		o.opener = oWindow
	}
	return sWindowName
}

function BuildFormValuesString(oDoc){

	var nNumForms = oDoc.forms.length
	var oForm
	var nLen = 0
	var sQString = ''
	var elem

	for(l=0; l < nNumForms; l++){
		oForm = oDoc.forms(l)
		nLen = oForm.length
		for(var j=0; j < nLen; j++){
			elem = oForm.elements(j)
			if(elem.name != ''){
				if(sQString != ''){
					sQString += '&'
				}
				sQString += elem.name+'='+escape(elem.value)
			}
		}
	}

	return sQString
}

function ReplaceSpecialChars(sText){
	sText = sText.replace(/</g,'&lt;')
	sText = sText.replace(/>/g,'&gt;')
	return sText
}

function OutputQueryPrompt(oWindow, lQType, sQProcess, lQId, sPageHandle, sQName, sQDesc){
	var sParams = ''
	/*
		lQType : type of query to create; ie QTYPE_CONSTITUENT
		sQProcess : Name of process ; ie Reports - From New Alumni Class list
		lQId : (this is optional) Id of an existing query
		sPageHandle : (this is optional) Handle of a page that implements IBBWebQueryCreatorUI
		sQName : (this is optional) Default query name
		sQDesc : (this is optional) Default query description
	*/

	if(OutputQueryPrompt.arguments.length > 5){
		try{sQName = unescape(sQName)}
		catch(e){}
	}

	if(OutputQueryPrompt.arguments.length > 7){
		try{sParams = unescape(OutputQueryPrompt.arguments[7])}
		catch(e){}
	}

	if(lQId == null){lQId = 0}
	if(sPageHandle == null){sPageHandle = ''}
	if(sQName == null){sQName = ''}
	if(sQDesc == null){sQDesc = ''}
	if(sParams == null){sParams == ''}

	var sUrl = oLibPage.BuildURL('Query/SaveQueryAs.asp','QId=' + lQId + '&QType=' + lQType + '&QProcess=' + sQProcess + '&QName=' + escape(sQName) + '&QDesc=' + escape(sQDesc) + '&PageHandle=' + sPageHandle + '&' + sParams)
	return oLibPage.openStandardModal(oWindow, sUrl, 375, 575)
}


function CardinalToOrdinal(nNumber){

	if(isNaN(nNumber)){return ''}
	if((nNumber > 3) && (nNumber <= 20)){return nNumber + 'th'}

	sTxt = nNumber.toString()
	nLastDigit = 1 * sTxt.substring(sTxt.length-1)
	if(nLastDigit == 1){return nNumber + 'st'}
	if(nLastDigit == 2){return nNumber + 'nd'}
	if(nLastDigit == 3){return nNumber + 'rd'}
	return nNumber + 'th'

}

function SelectedItemData(oCtl){
	if(oCtl.selectedIndex != -1){
		with (oCtl){
			nItemData = 1 * options[selectedIndex].itemData
			if(isNaN(nItemData)){
				return options[selectedIndex].itemData
			}else{
				return nItemData
			}
		}
	}else{
		return -1
	}
}

function StripColon(oCaption){
	with (oCaption.firstChild){
		data = data.replace(/:$/,'')
	}
}

function setText(o,sText){
	var bCreateTextNode = true
	var oTextNode

	if(o.childNodes.length > 0){
		while (o.firstChild != o.lastChild){
			o.removeChild(o.lastChild)
		}
		if(o.firstChild.nodeType != 3){
			o.removeChild(o.lastChild)
		}else{
			bCreateTextNode = false
		}
	}

	if(bCreateTextNode){
		oTextNode=o.ownerDocument.createTextNode(sText)
		o.appendChild(oTextNode)
	}else{
		o.firstChild.data = sText
	}
}

function getText(o){
	if(o.childNodes.length>0 && o.firstChild.nodeType == 3){
			return o.firstChild.data
	}else{
		return ''
	}
}

function EventHandlerToString(fnEventHandler){
	var sEventHandler = fnEventHandler.toString()
	var lsPtr = sEventHandler.indexOf('{')
	var lePtr = sEventHandler.lastIndexOf('}')
	if((lsPtr != -1) && (lePtr !=-1)){
		sEventHandler = sEventHandler.substring(lsPtr+2,lePtr-1)
	}
	return sEventHandler
}

function setFieldEnabled(o,bEnabled){
	if(o==null){return}	// CR232276-011906 - ChY - 1/19/06: leave if the parent document window is disabled
	var sID
	var oDocument=o.ownerDocument

	o.disabled=!bEnabled

	sID=o.id
	if(sID.substring(0,8)=='display_'){
		sID=sID.substring(8)
	}
	var oHelper=oDocument.getElementById('helper_'+sID)
	if(oHelper!=null){
		SetImage(-1, oHelper, bEnabled)
	}

	if(sID.substring(sID.length-4,sID.length)=='_CBX'){
		sID = sID.substring(0, sID.length-4)
	}
	var oLabel=oDocument.getElementById('label_'+sID)

	if(oLabel!=null){
		if(bEnabled){
			removeClass(oLabel,'captionGray')
		}else{
			addClass(oLabel,'captionGray')
		}
	}

	if(o.tagName=='FIELDSET'){
		var oControls=o.getElementsByTagName('input')
		for(var i=0;i<oControls.length;i++){
			oLibPage.setFieldEnabled(oControls.item(i),bEnabled)
		}
	}
}

function setFieldRequired(o,bRequired){
	var sID
	var oDocument=o.document

	if(bRequired){
		addClass(o,'cellRequired')
	}else{
		removeClass(o,'cellRequired')
	}

	sID=o.id
	if(sID.substring(0,8)=='display_'){
		sID=sID.substring(8)
	}
	var oHelper=oDocument.getElementById('helper_'+sID)
	if(oHelper!=null){
		if(bRequired){
			addClass(oHelper,'cellRequired')
		}else{
			removeClass(oHelper,'cellRequired')
		}
	}
}

function getTop(o){
	var nTop=o.offsetTop
	o=o.offsetParent
	while (o!=null){
		nTop+=o.offsetTop
		o=o.offsetParent
	}
	return nTop
}

function getLeft(o){
	var nLeft=o.offsetLeft
	o=o.offsetParent
	while (o!=null){
		nLeft+=o.offsetLeft
		o=o.offsetParent
	}
	return nLeft
}

function removeClass(o,sClassName){
    if(o == null){return}
    var re = new RegExp('\\b'+sClassName+'\\b');
    var re2 = new RegExp('^ ')
    var re3 = new RegExp(' $')
    var re4 = new RegExp('  ')
    var s=o.className.replace(re,'').replace(re2,'').replace(re3,'').replace(re4,' ')
    o.className=s
}

function addClass(o,sClassName){
    if(o == null || !sClassName){return}
    var re = new RegExp('\\b'+sClassName+'\\b');
    var sCurrentClassName=o.className

    if(sCurrentClassName.search(re)==-1){
        var s=(sCurrentClassName)?o.className+' '+sClassName:sClassName
        o.className=s
    }
}

function addClassToElement(o,sClassName){
    if(o == null || !sClassName){return}
    var re = new RegExp('\\b'+sClassName+'\\b');
    var sCurrentClassName=o.getAttribute('class')
    if(sCurrentClassName==null){sCurrentClassName=''}

    if(sCurrentClassName.search(re)==-1){
        var s=(sCurrentClassName)?o.getAttribute('class')+' '+sClassName:sClassName
        o.setAttribute('class',s)
    }
}

function removeClassFromElement(o,sClassName){
    if(o == null){return}
    if(o.getAttribute('class')==null){return}
    var re = new RegExp('\\b'+sClassName+'\\b');
    var re2 = new RegExp('^ ')
    var re3 = new RegExp(' $')
    var re4 = new RegExp('  ')
    var s=o.getAttribute('class').replace(re,'').replace(re2,'').replace(re3,'').replace(re4,' ')
    o.setAttribute('class',s)
}

function isGridDirty(oGrid){
	return oGrid && oGrid.isDirty && oGrid.isDirty()
}

function validateGrid(oGrid){
	var bValid=true
	// CR194141-111704 Need to call validate to check min number of lines.
	//if(isGridDirty(oGrid) && oGrid.validate){
	if(oGrid && (isGridDirty(oGrid) || oGrid.nRows<=1) && oGrid.validate){
		var bValid=oGrid.validate()
		if(!bValid){
			oGrid.setFocusToErrorCell()
			oGrid.alert(oGrid.sErrorMessage)			
		}
	}
	return bValid
}

function saveGrid(oGrid, bValidateFirst){
    var bContinue = true
    if(bValidateFirst){
        bContinue = validateGrid(oGrid) && oGrid && oGrid.bInit
    }else{
        bContinue = (oGrid && oGrid.isDirty && oGrid.bInit)
    }
    if(bContinue){
        var oGridHost=oGrid.oHost
        if(oGridHost){
            SafeSaveGridData(oGridHost, oGrid, oGrid.sGridName, oGridHost.document.getElementsByTagName('form').item(0).id)
            return true
        }else{
            return false
        }
    }else{
        return false
    }   
}

function setFocus(oDocument,sID){
	var o=null
	o=oDocument.getElementById('display_'+sID)
	if(o==null){o=oDocument.getElementById(sID+'_CBX')}
	if(o==null){o=oDocument.getElementById(sID)}
	if(o!=null){try {o.focus()} catch(e){}}

}

function doTextAreaFocus(w){
	var o=w.event.srcElement
	var sId=o.id
	o.setAttribute('intervalId',w.setInterval('oLibPage.doTextAreaTimeoutRoutine(window,"'+sId+'")', 500))
}


function doTextAreaTimeoutRoutine(w,sId){
	var o=w.document.getElementById(sId)
	if(o.value.length>o.maxlength){
		o.value=o.value.substr(0,o.maxlength)
	}
}

function doTextAreaKeyPress(w){
	var e=w.event
	var o=e.srcElement
	if(e.keyCode == 127 || (e.keyCode < 32 && e.keyCode != 13 && e.keyCode != 3)){
		e.returnValue=e.keyCode;
	}else{
		if(o.value.length >= o.maxlength){
			e.returnValue=false;
		}else{
			e.returnValue=e.keyCode;}
		}
}

function doNothing(){
	return false
}

function encodeGridData(sText){
    sText = sText.replace(/</g,'&BBlt;')
    sText = sText.replace(/>/g,'&BBgt;')
    sText = sText.replace(/onclick/g,'BBonclick')
    sText = sText.replace(/onmouse/g,'BBonmouse')
    return sText
}

function SafeSaveGridData(oGridHost, oGridWindow, sGridName, sFormId){
/* splits grid data up into 100K (approx.) chunks so it can safely be posted.
    oGridHost - the window hosting the grid (typically you can pass self
    oGridWindow - the grid
    sGridName - name of the grid, so that the hidden posted controls can be created correctly
    sFormId - id of the form (typically 'Form1ID')
*/
    var FORMLIMIT = 102300
    var SEGMENT_SIZE = (bIsMac)?32000:102300 
    var nNumSegments = 0
    var sGridData = oGridWindow.getGridData()
    sGridData = encodeGridData(sGridData)
    if(sGridData.length <= FORMLIMIT){
        oGridHost.document.getElementById(sGridName + 'DataID').value = sGridData
    }else{
        do {
            nNumSegments++
            nLen = Math.min(SEGMENT_SIZE, sGridData.length)

            var obj = oGridHost.document.createElement('INPUT')
            if(bIsMac){
                obj.style.display='none'
            }else{
                obj.type = 'hidden'
            }
            obj.name = sGridName + 'Data' + nNumSegments.toString()
            obj.value = sGridData.substr(0, nLen)
            obj.id = obj.name + 'id'

            if(oGridHost.document.getElementById(obj.id) != null){
                //if an object w/this id already exists, then remove it (can happen in batch)
                var oTestObj = oGridHost.document.getElementById(obj.id)
                oTestObj.parentNode.removeChild(oTestObj)
            }

            oGridHost.document.getElementById(sFormId).appendChild(obj)

            sGridData = sGridData.substr(nLen)

        } while (sGridData.length > 0)
        oGridHost.document.getElementById(sGridName + 'DataID').value = encodeGridData('<SPLIT>' + nNumSegments.toString())
    }
}

function SafeSaveControlData(oWindow, sData, sControlID, sFormId){

/* splits posted data up into 100K (approx.) chunks so it can safely be posted.
    oWindow - the window hosting the control (typically you can pass self
    sData - the data stream to post
    sControlID - id of the control, so that the hidden posted controls can be created correctly
    sFormId - id of the form (typically 'Form1ID')
*/
    var FORMLIMIT = 102300
    var SEGMENT_SIZE = (bIsMac)?32000:102300 
    var nNumSegments = 0
    sData = encodeGridData(sData)
    if(sData.length <= FORMLIMIT){
        oWindow.document.getElementById(sControlID).value = sData
    }else{
        var oCtl = oWindow.document.getElementById(sControlID)
        do {
            nNumSegments++
            nLen = Math.min(SEGMENT_SIZE, sData.length)

            var obj = oWindow.document.createElement('INPUT')
            if(bIsMac){
                obj.style.display='none'
            }else{
                obj.type = 'hidden'
            }
            obj.name = oCtl.name + nNumSegments.toString()
            obj.value = sData.substr(0, nLen)
            obj.id = obj.name + 'id'

            if(oWindow.document.getElementById(obj.id) != null){
                //if an object w/this id already exists, then remove it
                var oTestObj = oWindow.document.getElementById(obj.id)
                oTestObj.parentNode.removeChild(oTestObj)
            }

            oWindow.document.getElementById(sFormId).appendChild(obj)

            sData = sData.substr(nLen)

        } while (sData.length > 0)
        oWindow.document.getElementById(sControlID).value = encodeGridData('<SPLIT>' + nNumSegments.toString())
    }
}

function StripAccelKey(sTxt){
	sTxt = sTxt.replace(/&&/g,'\t')
	sTxt=sTxt.replace(/&/g,'')
	return sTxt.replace(/\t/g,'&')
}

function getXMLDocument(odocument, sId){
	//implemented currently as IE XMLDataIsland - could be changed to use IFRAMEs - a la grids...if we run into Mac compatibility problems
	return odocument.getElementById(sId)
}

function OpenModelessForm(oWindow, sFormKey, dialogHeight, dialogWidth){
	var obj 
	var sMoreTags = ''

	if(OpenModelessForm.arguments.length > 4){
		sMoreTags = ArgsToTags(OpenModelessForm.arguments[4])
		oWindow.myModalArguments = OpenModelessForm.arguments[4]
	}

	var sRequest = oLibPage.BuildModelessFormRequest(oWindow.document, sFormKey, sMoreTags)

	var sURL = oLibPage.applicationBase + 'sys/scripts/shell/page.asp?request=' + sRequest
	
	var sFeatures = oLibPage.BuildModalFeaturesString(oWindow, dialogHeight, dialogWidth)

	if(oLibPage.bIsMac){
	}
	else{
		obj = oWindow.showModelessDialog(sURL, oWindow, sFeatures)
	}
	
	if(obj != null){ 
        return obj
    } 

}
function OpenModalForm(oWindow, sFormKey, dialogHeight, dialogWidth){

	var obj 
	var sMoreTags = ''

	if(OpenModalForm.arguments.length > 4){
		sMoreTags = ArgsToTags(OpenModalForm.arguments[4])
		oWindow.myModalArguments = OpenModalForm.arguments[4]
	}

	var sRequest = oLibPage.BuildModelessFormRequest(oWindow.document, sFormKey, sMoreTags)

	var sURL = oLibPage.applicationBase + 'sys/scripts/shell/page.asp?request=' + sRequest
	var sModalURL = oLibPage.applicationBase + 'sys/scripts/modal/ModalHost.asp?modaldestination=' + escape(sURL)
	
	var sFeatures = oLibPage.BuildModalFeaturesString(oWindow, dialogHeight, dialogWidth)


	obj = _ShowModalDialog(sModalURL, oWindow, sFeatures)

	if(obj != null){ 
        return obj
    } 

}

function OpenModalFormDirect(oWindow, sFormKey, dialogHeight, dialogWidth, oArgObj){

	var obj 

	var sRequest = oLibPage.BuildModelessFormRequest(oWindow.document, sFormKey)

	var sURL = oLibPage.applicationBase + 'sys/scripts/shell/page.asp?request=' + sRequest
	
	var sFeatures = oLibPage.BuildModalFeaturesString(oWindow, dialogHeight, dialogWidth)

	if(OpenModalForm.arguments.length > 4){
		oWindow.myModalArguments = oArgObj
	}

	obj = _ShowModalDialog(sURL,oWindow,sFeatures)
	if(obj != null){ 
        return obj
    } 

}

function ShowInputBox(oWindow, sMsg, sCaption, sValue, sTBStyle, sSize, sMaxLength, dialogHeight, dialogWidth, sFieldsetCaption, oArgObj, bInputRequired){
	var obj 
	var iNbrOfArgs = ShowInputBox.arguments.length
	var sFeatures = oLibPage.BuildModalFeaturesString(oWindow, dialogHeight, dialogWidth)
	var oArgs = new Object();
	oArgs.value = sValue;
	oArgs.libPage = oLibPage;
	//oArgs.legend = sFieldsetCaption;	
	oArgs.message = sMsg;
	oArgs.caption = sCaption;
	oArgs.inputRequired = bInputRequired;
	/**	
	if(iNbrOfArgs > 10){
		oWindow.myModalArguments = oArgObj
	}
	**/
	oWindow.myModalArguments = oArgs
	var sURL = BBWEBCLIENT_INPUTBOX_FORM;
	if(oLibPage.bIsMacIE){
		sURL = BBWEBCLIENT_INPUTBOX_FORM_MAC;
	}
	obj = _ShowModalDialog(sURL,oWindow,sFeatures)
	if(obj != null){ 
        return obj
    } 
}

function openCalculator(owindow,ocontrol){

	var bIgnoreState = false
	var bDisabled = ocontrol.disabled

	if(openCalculator.arguments.length > 2){
		bIgnoreState = openCalculator.arguments[2]
	}

	if(!bDisabled || bIgnoreState){

		var sURL = oLibPage.serverURL + BBWEBCLIENT_HELPERS + "/calculator.htm"
		var nHeight = 200;
		var nWidth = 225;
		var sFeatures = oLibPage.BuildModalFeaturesString(owindow, nHeight, nWidth)

		var oArgs = new Object();
		oArgs.oLibPage = oLibPage;
		oArgs.calculatorReturnField = ocontrol;
		
		owindow.myModalArguments = oArgs;
		//owindow.calculatorReturnField = ocontrol;

		obj = _ShowModalDialog(sURL,owindow,sFeatures)
		if(obj != null){ 
		    return obj
		} 
	}
}

function openCalendar(owindow,ocontrol){
	var bIgnoreState = false
	var bDisabled = ocontrol.disabled

	if(openCalendar.arguments.length > 2){
		bIgnoreState = openCalendar.arguments[2]
	}

	if(!bDisabled || bIgnoreState){
	
		if(typeof("adjustControlWidth") == "function"){
			// used by BBWebSmartControl. Function defined in SmartControl.js
			adjustControlWidth(ocontrol, false)
		}
		
		var sURL = oLibPage.serverURL + BBWEBCLIENT_HELPERS
		var nHeight
		var nWidth
		if(bIsMacIE){
			sURL = sURL + "/calendarMac.htm"
			nHeight = 210;
			nWidth = 310;
		}else{
			sURL = sURL + "/calendar.htm"
			nHeight = 230;
			nWidth = 290;
		}

		var sFeatures = oLibPage.BuildModalFeaturesString(owindow, nHeight, nWidth)

		var oArgs = new Object();
        oArgs.calendarReturnField = ocontrol;
        oArgs.oLibPage = oLibPage
		owindow.myModalArguments = oArgs

		//owindow.calendarReturnField = ocontrol;

		obj = _ShowModalDialog(sURL,owindow,sFeatures)
		if(obj != null){ 
		    return obj
		} 
	}
}

function openSpellChecker(owindow, ocontrol, lMaxLength, HTMLMode, OnCloseFunc){
    if(ocontrol.value == ''){return}
    
    var bIgnoreState = false;
    var bDisabled = ocontrol.disabled;
    var sControlName = ocontrol.name;
    var oForm = owindow.document.getElementById('Form1Id');
    if(openSpellChecker.arguments.length > 2){
        bIgnoreState = openSpellChecker.arguments[2];
    }

    if(!bDisabled || bIgnoreState){

        var sURL = oLibPage.applicationBase + "/Forms/UserControlHost.aspx?dtid=" + SpellCheck;
        var nHeight = 370;
		var nWidth = 540;
        var sFeatures = oLibPage.BuildModalFeaturesString(owindow, nHeight, nWidth);

        if (HTMLMode)
			ocontrol.value = AlterLinks(ocontrol.value);
			
		var oArgs = new Object();
        oArgs.spellCheckReturnField = ocontrol;
        oArgs.controlId = ocontrol.id;
        oArgs.spellCheckURL = sURL;
        oArgs.oLibPage = oLibPage;
        oArgs.HTMLMode = HTMLMode;
        oArgs.lMaxLength = lMaxLength
        oArgs.OnCloseFunc = OnCloseFunc;
        oArgs.sText = ocontrol.value;
		owindow.myModalArguments = oArgs;

        /*
        owindow.spellCheckReturnField = ocontrol;
        owindow.controlId = ocontrol.id;
        owindow.spellCheckURL = sURL;
        owindow.oLibPage = oLibPage
        */
        
        sURL = BBWEBCLIENT_SPELLCHECK_FORM + "?dtid=" + SpellCheck;
        var obj = _ShowModalDialog(sURL, owindow, sFeatures)
        
       	if (!bSimulateModal) {
			if(obj != null){ 
				return obj
			} 
		}

    }
}

function openCodeTableSelect(owindow, lCodeTableID){
	/**********************
	var lHeight = 325
	var lWidth = 230
	if(openCodeTableSelect.arguments.length > 2){
		lHeight = openCodeTableSelect.arguments[2]
	}
	
	if(openCodeTableSelect.arguments.length > 3){
		lWidth = openCodeTableSelect.arguments[3]
	}
	
	var oArgs = new Object()
	oArgs.CODETABLEID = lCodeTableID
	oArgs.DIALOGHEIGHT = lHeight
	oArgs.DIALOGWIDTH = lWidth
	
	var sMoreTags = ArgsToTags(oArgs)

	var oReq = new BBWebRequest(owindow.document)
	oReq.bPreserveCache = true
	oReq.bLoad = true
	oReq.lRecID = lCodeTableID
	oReq.sProgID = SYSTEM_WEB_RECORD_PROGID
	oReq.sNextForm = 'CODETABLESELECT'
	oReq.sAdditionalTags = oReq.sAdditionalTags + sMoreTags

	var sRequest = oReq.GetReqString()
	var sURL = oLibPage.applicationBase + 'sys/scripts/shell/page.asp?request=' + sRequest

	var sFeatures = oLibPage.BuildModalFeaturesString(owindow, lHeight, lWidth)

	obj = _ShowModalDialog(sURL,owindow,sFeatures)
	if(obj != null){ 
	    return obj
	} 
	***************************/
}


function handleEmptyCheckList(oDocument, sName){
	var oChecklist=oDocument.getElementsByName(sName)
	for(var i=0;i<oChecklist.length;i++){
		if(oChecklist.item(i).checked){
			return true
		}
	}
	var o=oDocument.getElementById(sName+'HiddenId')
	if(!o){
		o=oDocument.createElement('input')
		o.name=sName
		oDocument.getElementById('Form1Id').appendChild(o)
	}
	o.value=''
	return true
}

function toggleCheckBox(o){
	var sId=o.getAttribute('id')
	sId=sId.substring(0,sId.length-4)
	o.document.getElementById(sId).value=(o.checked?'-1':'0')
}

function windowScrollTo(owindow,x,y){
	owindow.scrollTo(x, y)
}

function NotifyPageLoaded(sPageHandle, bPreserveCache){
	var sNotifyPage
	sNotifyPage = 'sys/scripts/shell/Notify.asp?NID=1&' + 'DATA=' + sPageHandle + ';' + bPreserveCache
	var oNotifyFrame = parent.window.document.getElementById('NotifyFrameid')
	if(oNotifyFrame){
		oNotifyFrame.src = sNotifyPage
	}
}

function resizeModalToFit(oWindow){
return
    if(oWindow.top.bIsModal && oWindow.top.bDoResize && oLibPage.bIsMac){
        oWindow.top.bDoResize=false
        var o=oWindow.document.getElementById('mainFormDivId')
        if(o){
            var nWidth=o.offsetWidth
            var nHeight=o.offsetHeight+15
            oWindow.resizeTo(nWidth,nHeight)
        }
    }
}

function windowSetTimeout(oWindow,sCode, nMillisecondDelay){
    if(oWindow.top.bIsModal && oLibPage.bIsMacIE){
        oWindow.eval(sCode)
    }else{
		oWindow.setTimeout(sCode,nMillisecondDelay)
    }
}

//ISK changed for export to excel functionality
//function openPrintGrid(oWindow,bPrintBlank,sHandlerUrl){
function openPrintGrid(oWindow,printType,sHandlerUrl){
	var sURL = oLibPage.applicationBase+sHandlerUrl
	//if(bPrintBlank){sURL=sURL+'3'}else{sURL=sURL+'2'}
	switch(printType){
		case 0:
			sURL=sURL+'2';
			break;
		case 1:
			sURL=sURL+'3';
			break;
		case 2:
			sURL=sURL+'4';
			break;
	}
    var oForm=oWindow.document.getElementById('printGridFormId')
    oForm.setAttribute('action',sURL)
  
    oForm.submit()
}
      
function RedirectEnterKey(event, btn){
	if(document.all){
		if(event.keyCode == 13){ 
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		} 
	}
}

function getTime(){
	var dtToday = new Date()
	return (dtToday.getTime()/1000) // Seconds since 1 JAN 1970 00:00:00
}

function setPageLoadTime(){
	glPageLoadedAt = getTime()
}

function getPageLoadTime(){
	return glPageLoadedAt
}

function hasSessionTimedOut(){
	var bRet
	
	if(gbSessionTimedOut){
		bRet = gbSessionTimedOut
	}else{
		bRet = ((getTime() - getPageLoadTime()) > (_wrfSessionTimeout * 60))
		if(bRet){gbSessionTimedOut = bRet}
	}
	
	return bRet
}

function alertSessionTimedOut(){
	alert('Your session has timed out. Unsaved data will be lost.')
	return
}

function getSessionTimedOutAlertShown(){
	return(gbSessionTimedOutAlertShown)
}

function setSessionTimedOutAlertShown(bShown){
	gbSessionTimedOutAlertShown = bShown
}

//object used to call showModalDialog to show a usercontrol modally
function ModalDialogBB(iDialogId, sWidth, sHeight, sQSdata){
	// iDialogId is the user control to load - the IDs are spit out by common code
	// sWidth/sHeight should be string and include units eg. '400px'
	// sQSdata is a string and is passed as-is on the query string and handed to your ctl's IBBDialog.data property
	// the clientArgs object will be passed to the client side JS code of the control and can be used for any arguments you like

	this.dialogId = iDialogId
	this.width = sWidth
	this.height = sHeight
	this.clientArgs = new Object()
	this.qsdata = sQSdata
	this.features = "scroll:no;status:no;"
	this.Show = Show
	this.getFeatureString = getFeatureString

	function getFeatureString(){
		return this.features + "dialogWidth:" + this.width + ";dialogHeight:" + this.height + ";"
	}

	function Show(){
		if(typeof(this.ctl) == 'undefined'){
			alert("showModalDialogBB assert: ctl parameter not set in arg object")
		}

		if(typeof(this.width) == 'undefined'){
			alert("showModalDialogBB assert: width parameter not set in arg object")
		}

		if(typeof(this.height) == 'undefined'){
			alert("showModalDialogBB assert: height parameter not set in arg object")
		}

		var sURL = oLibPage.applicationBase + "/Forms/UserControlHost.aspx?dtid=" + this.dialogId + "&data=" + this.qsdata
		return window.showModalDialog(sURL, this.clientArgs, this.getFeatureString());
	}
}

var iDbgWinCount=1
function write2DebugWindow(oWin, sMsg){
	var oDebugWin
	if(typeof(oWin.DebugWindow)=='undefined'){
		var sFeatures='scrollbars=yes height=400 width=300'
		oDebugWin=window.open('about:blank','BBDebugWindow'+iDbgWinCount,sFeatures)
		oWin.DebugWindow=oDebugWin
	}else{oDebugWin=oWin.DebugWindow}
	if(oDebugWin){
		oDebugWin.document.writeln(sMsg)
	}
}

function _getCallerArgs(oWindow) {
	var oCallerWindow
	var oArgs 
	if (oWindow.opener.oLibPage.bSimulateModal) {
		// probably from a simulated modal
		var iLen = oWindow.opener.oLibPage.moModals.length
		if ( iLen > 1) {	// we are also a simulated modal, so one previous.
			oCallerWindow =oWindow.opener.oLibPage.moModals[iLen - 1].oParent
		} else {
			oCallerWindow =oWindow.opener
		}
	} else if (oWindow.top.dialogArguments) {
		oCallerWindow = oWindow.top.dialogArguments
	} else if (oWindow.opener.myModalArguments) {
		oCallerWindow = window.opener
	}

	if (oCallerWindow) {
		oArgs = oCallerWindow.myModalArguments;
	} 
	return oArgs
}

function _getCallerWindow(oWindow) {
	var oCallerWindow
	if (oWindow.top.dialogArguments) {
		oCallerWindow = oWindow.top.dialogArguments
	} else if (oWindow.opener.oLibPage.bSimulateModal) {
		// probably from a simulated modal
		var iLen = oWindow.opener.oLibPage.moModals.length
		if ( iLen > 1) {	// we are also a simulated modal, so one previous.
			oCallerWindow =oWindow.opener.oLibPage.moModals[iLen - 2].oModal
		} else {
			oCallerWindow =oWindow.opener
		}
	} else if (oWindow.opener.myModalArguments) {
		oCallerWindow = window.opener
	}

	return oCallerWindow
}

function HandleResize() {
	// Feel free to override, but include the next line.
	Resize_SetAvailableHeightWidth()
}

function Resize_SetAvailableHeightWidth(){
	// I got these numbers by setting the resolution to 800x600, maximizing the browser and capturing the result of document.body.clientWidth and document.body.clientHeight, on windows.  They are not precise, just a lower bound on what we support.  They can be adjusted if needed.
	var RESIZE_MINHEIGHT = 447;
	var RESIZE_MINWIDTH = 780;

	var oElem

	var h = GetHeight(window)
	var w = GetWidth(window) - 17

	if (h<RESIZE_MINHEIGHT) h = RESIZE_MINHEIGHT
	if (w<RESIZE_MINWIDTH) w = RESIZE_MINWIDTH

	oElem = document.getElementById("availableHeight")
	if (oElem) oElem.value = String(h)
	
	oElem = document.getElementById("availableWidth")
	if (oElem) oElem.value = String(w)

	oElem = document.getElementById("bodyId")
	if (oElem) oElem.style.width = String(w-3) + 'px'
	
}

function CenteredFeatures(w, h)
{
	var l = Math.round((window.screen.availWidth -w-12)/2); if (l<0) l = 0
	var t = Math.round((window.screen.availHeight-h-76)/2); if (t<0) t = 0
	return 'width=' + w + ',height=' + h + ',top=' + t + ',left=' + l
}

function AlterLinks(html) {
	//Make the links not look like links (links will confuse the spell checker)
	return html.replace(/<[aA] /ig, "<BBLINK ").replace(/<\/[aA]>/ig, "</BBLINK>");
}

function RevertLinks(html) {
	//Revert the disguised links
	return html.replace(/<BBLINK /ig, "<A ").replace(/<\/BBLINK>/ig, "</A>");
}

function GetNodeText(oNode) {
	var bIsIE = false;
	if (window.ActiveXObject){
		bIsIE = true;
	}
	if (bIsIE) {
		return oNode.text
	}else{
		// Mozilla
		return oNode.textContent
	}
}

function GetHeight(win) {
  var h
  var doc = win.document
  if( typeof( win.innerWidth ) == 'number' ) {
    //Non-IE
    h = win.innerHeight;
  } else if( doc.documentElement &&
      ( doc.documentElement.clientWidth || doc.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    h = doc.documentElement.clientHeight;
  } else if( doc.body && ( doc.body.clientWidth || doc.body.clientHeight ) ) {
    //IE 4 compatible
    h = doc.body.clientHeight;
  }
  return h
}

function GetWidth(win) {
  var w
  var doc = win.document
  if( typeof( win.innerWidth ) == 'number' ) {
    //Non-IE
    w = win.innerWidth;
  } else if( doc.documentElement &&
      ( doc.documentElement.clientWidth || doc.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    w = doc.documentElement.clientWidth;
  } else if( doc.body && ( doc.body.clientWidth || doc.body.clientHeight ) ) {
    //IE 4 compatible
    w = doc.body.clientWidth;
  }
  return w
}

function GetActualWidthAvailable(win) {
  var w;
  var doc = win.document;
  var phDiv = doc.getElementById("phDiv");
  if (phDiv) {
    w = phDiv.clientWidth;
  } else {
    w = GetWidth(win);
  }
  return w
}

// START: Emulate the disabled attributte for the <option> in IE ------------------------------------------>
// ChY adopts this piece of code on 1/12/06:
/****************************************************************
* Author:	Alistair Lattimore
* Contact:	http://www.lattimore.id.au/
* Purpose:	Emulate the disabled attributte for the <option> 
*			element in Internet Explorer.
****************************************************************/

function disableDDOptionsForIE(ctrlName) {
	if (document.getElementsByName) {
		var s = document.getElementsByName(ctrlName);

		if (typeof(s) != 'undefined') {
			window.select_current = new Array();

			for (var i=0, select; select = s[i]; i++) {
				select.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
				select.onchange = function(){ disableDDOptionsForIE_restore(this); }
				disableDDOptionsForIE_emulate(select);
			}
		}
	}
}

function disableDDOptionsForIE_restore(e) {
	if (e.options[e.selectedIndex].disabled) {
		e.selectedIndex = window.select_current[e.id];
	}
}

function disableDDOptionsForIE_emulate(e) {
	for (var i=0, option; option = e.options[i]; i++) {
		if (option.disabled) {
			option.style.color = "graytext";
		}
		else {
			option.style.color = "menutext";
		}
	}
}
// END: Emulate the disabled attributte for the <option> in IE ------------------------------------------>

// START:  Put a max length counter to <textarea> ------------------------------------------>
/****************************************************************
* Author:	Peter-Paul Koch
* Reference:	http://www.quirksmode.org/dom/maxlength.html
* Edited by:	Cherrie Yuen [ChY] on 3/8/06
* Purpose:	[ChY] Count the characters the user has typed in a HTML <textarea> box. 
*				If max reached, display the counter as a warning, else, hide the counter.
*				Treat single quote as 2 characters because it will be replaced with 2 single quotes to put in SQL.
****************************************************************/
function HTMLTextArea_SetMaxLength()
{
	var x = document.getElementsByTagName('textarea');
	var textareaCounter = document.createElement('div');
	textareaCounter.className = 'textareaCounter';		// ChY - this is a CSS class. edit it if you want.
	for (var i=0;i<x.length;i++)
	{
		if (x[i].getAttribute('maxlength'))
		{
			var counterClone = textareaCounter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/' + x[i].getAttribute('maxlength') + ' characters max. Excess will be trimmed.';
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = HTMLTextArea_CheckMaxLength;
			x[i].onkeyup();
		}
	}
}

function HTMLTextArea_CheckMaxLength()
{
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (this.value.match(/'/g)){					// ChY - use regular expression to find the number of single quotes
		currentLength = currentLength + this.value.match(/'/g).length	
	}
	if (currentLength > maxLength){		// ChY - max reached, display the counter
		this.relatedElement.className = 'textareaTooLong';
		this.relatedElement.parentNode.style.display = 'inline';		
	}
	else{
		this.relatedElement.className = '';
		this.relatedElement.parentNode.style.display = 'none';		
	}
	this.relatedElement.firstChild.nodeValue = '  ' + currentLength;
	// not innerHTML
}

// END: Put a max length counter to <textarea> ------------------------------------------>


//end MiscFunctions.fun



