
var awfhPrevValues	//assoc. array - will be created by eval
var wrfbPromptToSave=false
var wrfbSaveFirst=false
var wrfbOKToNavigate=false
var iTimerId
var aspNet_doPostBack
var mbWRFSave=false
var mbLogout=true
var mbModalWindow=false
var displayingTimeout = false;
var forceTimeoutDisplay = false;
var browserAlert = window.alert;

function writeStatusMessage(sMsg){
	window.status=sMsg
}

function _WRFPageLoad(){

	writeStatusMessage('Page Load Step 1 of 6')

	// create assoc. array from previous values array
	awfhPrevValues=_WRFCreatePrevValuesArray()
	
	if(window.positionMenu){
		positionMenu()
	}
	
	// Get the ASP.NET postback function pointer
	if(typeof(__doPostBack) != "undefined"){
		aspNet_doPostBack=__doPostBack
		__doPostBack=_WRFPostBack
	}
	
	if(window.PageInit){
		writeStatusMessage('Page Load Step 2 of 6')
		PageInit()
	}
	
	if(window.PageLoad){
		writeStatusMessage('Page Load Step 3 of 6')
		PageLoad()
	}

	if(bPageHasGrids){

	} else {
		writeStatusMessage('Page Load Step 4 of 6')
		_WRFPageLoad2()
	}
	
	if(window.bIsModal){
	   if((window.opener)&&(typeof(window.opener.mbCallExternal) != 'undefined'))
	    {
			if(window.opener.mbCallExternal==true){
				if(window.opener.external){
					window.opener.external.HookModalDialog(window.document)
					}
			}
		}
	}
	if (typeof(HandleResize)=='function') HandleResize();
	
	window.alert = _WRFAlert;
}

function _WRFAlert(txt) {
    //Need to check to see if alert was called while we were in the process of 
    //saving before displaying the timeout message.
    //Otherwise alert will take over and timeout message will not display.
    if(displayingTimeout) {
        if (_wrfbWarnSessionTimeout) {
	        if(window.displaySessionTimeoutMsg) {
	            forceTimeoutDisplay = true;
		        displaySessionTimeoutMsg();
	        }
        }
        displayingTimeout = false;
    }
    
    browserAlert(txt);
}

function _WRFPageLoad2(){
	writeStatusMessage('Page Load Step 5 of 6')
	_WRFEndPageLoad()
}

function _WRFEndPageLoad(){
	writeStatusMessage('Page Load Step 6 of 6')
	setSessionTimeoutWarning(window);
	
	if(window.PageLoadEnd){
		PageLoadEnd()
	}
	if(window._bInError){
		_WRFHandleError()
	}
	writeStatusMessage('Done')
}

function setSessionTimeoutWarning(oWin){
	if(oWin.dialogArguments){
		oWin.dialogArguments.clearTimeout(oWin.dialogArguments.MyTimerId); //clear timer on parent if modal is opened using standard brower function
	}else if(oWin.oModal){
	    if(oWin.oModal.oParent) {
		    oWin.oModal.oParent.clearTimeout(oWin.oModal.oParent.MyTimerId); //clear timer on parent if modal is opened using bbShowModalDialog
		}
	}else{
		oWin.clearTimeout(oWin.MyTimerId);
	}
    
    //if we are not already displaying the timeout message set the timer
    if(!displayingTimeout) {
	    var iMilliSecs = getTimeoutValue();
	    var lTimerId=oWin.setTimeout("_WRFSessionTimeoutWarning()", iMilliSecs);
	    oWin.MyTimerId=lTimerId;
	}	
}

function _WRFSessionTimeoutWarning(){
    if (_wrfbWarnSessionTimeout) {
        if(window.displaySessionTimeoutMsg){
            displayingTimeout = true;
	        displaySessionTimeoutMsg();
        }
    }
    else {
        //the user has choosen not to have the timeout message displayed
        //we still want to try to auto-save for them before they timeout
        tryAutoSave();
    }
}

//Need to add this to anywhere were we would like to auto-save.
//If auto-saving before opening a modal then the modal parameters
//can be passed in and the modal will be opened after the postback occurs.
function tryAutoSave(sModalURL, sFeatures) {
    //Check to see if the page is able to autosave
    if (window.CheckForForceSave && window.btnAutoSavePostback && !forceTimeoutDisplay) {
        //This is needed for pages that have grids so that we can refocus on the current cell after the postback
        //If we don't get the focus befoe we check to see if the page is dirty we will just lose focus
        //Each page with a grid will need to implement GetGridFocus and SetGridFocus on its own.
        var currentCell;
        if(window.GetGridFocus) {  
            currentCell = GetGridFocus();
        }
        //Now we can try to autosave if the page is dirty
        if(_WRFIsPageDirty()){
            // we are going to display a modal after the postback
            // send the modal parameters in a JSON string back to the server so that the modal will open after the page is reloaded
            // if we just opened the modal before auto-saving the modal would be closed
            if(sModalURL != undefined) {
                var modal = new Object();
                modal.sModalURL = sModalURL;
                modal.sFeatures = sFeatures;
                modal.currentCell = currentCell;
                $('#' + hfPostbackArguments).val(Sys.Serialization.JavaScriptSerializer.serialize(modal));
            }
            
            $('#' + btnAutoSavePostback).click(); //postback to force an autosave then display the timeout message
            return true;
        }
        //This code might not be hit if the postback occurs but we need it because checking if the page is dirty causes
        //the grid to lose focus
        if(window.SetGridFocus) {
            if (currentCell) {
                SetGridFocus(currentCell);
            }
        }
    }
    
    return false;
}

function getTimeoutValue(){
	var lSessionTimeout
	switch(_wrfSessionTimeout){
		case 1:
			lSessionTimeout=(_wrfSessionTimeout/2)
			break
			
		default:
			lSessionTimeout=_wrfSessionTimeout - 1
			break
	}
	var iMilliSecs=(lSessionTimeout * 60000) // convert minutes to Milliseconds	
	return iMilliSecs
}

function _WRFPostBack(eventTarget, eventArgument){
	mbLogout=false
	var postBackInfo=new Object;
	
	postBackInfo.bCancel=false;
	postBackInfo.bSaveFirst=false; 

    // Give calling page a chance to cancel prompt to save (will get a chance to force a hidden save below).
    if(window.CheckForPromptToSave){
        CheckForPromptToSave();
    }
	
	var bCallPart2Now = true;
	if(wrfbPromptToSave && _WRFIsPageDirty()){
		_WRFConfirmSaveBeforePostback(postBackInfo);
		if (bSimulateModal && mbModalWindow) {
			if (typeof(oModalReturn) != 'undefined') {
				// cache our intent for when the modal comes back.
				oModalReturn.eventTarget = eventTarget
				oModalReturn.eventArgument = eventArgument
				bCallPart2Now = false;
			}
		}
	}

	if (bCallPart2Now) 
		_WRFPostBack_Part2(postBackInfo, eventTarget, eventArgument)

}


function _WRFPostBack_Part2(postBackInfo, eventTarget, eventArgument) {

	// this second part happens after modal is dismissed
	var bContinue=true
	
	if(!postBackInfo.bCancel){
		wrfbOKToNavigate=true;
		var oElems=document.getElementsByName(POSTBACK_HIDDEN_FLD_NAME)
		var oSave
		if((oElems)&&(oElems.length>0)){oSave=oElems[0]}
		if(!postBackInfo.bSaveFirst){
		    // Give calling page a chance to force a hidden save (i.e. not based on WRFConfirmSaveBeforePostback above).
		    if((window.CheckForForceSave) && (eventArgument != "save") && (eventArgument != "cancelback")){
		        CheckForForceSave();
		    }
			postBackInfo.bSaveFirst=wrfbSaveFirst
		}
		if(postBackInfo.bSaveFirst){
			bContinue=_WRFSave()
			if(oSave){oSave.value=POSTBACK_ACTION_SAVE}
		}else{
			if(oSave){oSave.value=POSTBACK_ACTION_DONT_SAVE}
		}
		if((bContinue) && (window.PagePostBack)){
			bContinue=PagePostBack(eventTarget, eventArgument,oSave.value)
		}
		if(bContinue){
			// Original Postback
			aspNet_doPostBack(eventTarget, eventArgument)
		}
		if((bContinue) && (window.PagePostPostBack)){
			PagePostPostBack()
		}
	}
	if((postBackInfo.bCancel) || (!bContinue)){
		if(window.PostBackCancelled){
			window.PostBackCancelled();
		}
	}
}

function getMainForm(){
	var theform
	if(window.navigator.appName.toLowerCase().indexOf("netscape") > -1){
		theform=document.forms["Form1"];
	}
	else {
		theform=document.Form1; 
		// MSDN "ASP.NET Run-Time Breaking Changes" (http://msdn2.microsoft.com/en-us/netframework/aa497240.aspx), "The form's name attribute is no longer rendered to the response for XHTML compliance", appears to be incorrect about this.  It's only a problem if compliance is set to Strict; it's Transitional by default, which this code will work under, it's not necessary to drop down to Legacy for this code to keep working.  And there is this switch available, just not as named in the article.
		// So if this is used by an application with <xhtmlConformance mode="Strict" /> in its web.config, we could just gut this function and return document.forms["Form1"].  I don't know why that syntax isn't used for every browser, why the author of this function bothered to write it.  There would be other alternative syntax choices like "theform=document.getElementById('Form1');".  Or "theform=document.forms(0);"--if more than one form is defined per page (even possible in ASP.NET?) the form of interest just has to be the first for this to work.
	}
	return theform
}

function _WRFConfirmSaveBeforePostback(postBackInfo){
	//changed to allow customization - specifically for Netclassroom.
	var style = oLibPage.mb_YesNoCancel + oLibPage.mb_Exclamation;
	if (window.msgBoxStyle) {
		style = window.msgBoxStyle();
	}
		
	var retVal=oLibPage.ShowMsgBox(self, SAVE_PROMPT_MESSAGE, style, "", "", "Save Changes");
	if (oLibPage.getStyleNoImage(style) == oLibPage.mb_YesNoCancel) {
		mbModalWindow = true;
		switch (retVal){
			case oLibPage.mb_Yes:
				postBackInfo.bSaveFirst=true;
				break;
				
			case oLibPage.mb_Cancel:
				postBackInfo.bCancel=true;
				break;
				
			case oLibPage.mb_No:
				postBackInfo.bCancel=false;
				postBackInfo.bSaveFirst=false;
				break;
		}
	}
	else if (oLibPage.getStyleNoImage(style) == oLibPage.mb_OKCancel) {
		mbModalWindow = false;
		switch (retVal){
			case oLibPage.mb_OK:
				postBackInfo.bCancel=false;
				postBackInfo.bSaveFirst=false;
				break;
				
			case oLibPage.mb_Cancel:
				postBackInfo.bCancel=true;
				break;
		}
	}
}

function _WRFIsPageDirty(){
	var bDirty=_wrfbPageDirty //created/set/maintained by vb code - handles web rec dirty from any form
	if(!bDirty){
		bDirty=_WRFHavePrevValuesChanged()
	}
	if(!bDirty){
		if(window.IsPageDirty){
			bDirty=IsPageDirty()
		}
	}
	return bDirty
}

function _WRFHandleError(){
	if(_bErrShowMsg){
		if(_sErrMsg.length > 0 ){
			alert(_sErrMsg)
			if(_bErrSetFocus){
				if(_sErrControlID.length>0){
					var _oErrCtl=document.getElementById(_sErrControlID)
					if(_oErrCtl){
					    try{
						    _oErrCtl.focus()
		                }catch(err){
			                //Ignore the error - only here because some controls don't want to accept focus sometimes
		                }
					}
				}
			}
		}
	}
}

function setFocusToErrorFld(){
	// This is an extension to the ASP.NET client-side Required field validation process
	
	if((typeof(Page_IsValid)=="undefined") || (typeof(Page_Validators)=="undefined")){
		return
	}
	
	if(!Page_IsValid){
		var i
	    for (i=0; i < Page_Validators.length; i++){
	        if(!Page_Validators[i].isvalid){
	        	var sCtrl=Page_Validators[i].controltovalidate
	        	var oCtrl=document.getElementById(sCtrl)
	        	if(typeof(oCtrl) != "undefined"){
	        		oCtrl.focus()
	        	}
	            return
	        }
	   }
	}
}

function _WRFPageUnload(){
	//alert('mbLogout='+mbLogout);
	//ISK need this only for main page
	
	if (typeof(oLibPage) != 'undefined'){
		var sApplicationBase;
		
		try{
			sApplicationBase = oLibPage.applicationBase;
		}catch(err){
			//Ignore the error
		}
	
		if (typeof(sApplicationBase) != 'undefined'){
			var FAWebShellURL=sApplicationBase + "/Forms/FAWebShell.aspx";
			var NCShellURL=sApplicationBase + "/Forms/NCShell.aspx";
			var NCCompatShellURL=sApplicationBase + "/Forms/NCShellCompat.aspx";
			var portnum;
			portnum=window.location.port;
			if (portnum=='') {
				portnum='80';
			}
			var currentURL = window.location.protocol + '//' + window.location.hostname + ':' + portnum + window.location.pathname;
			if (currentURL.toLowerCase()==FAWebShellURL.toLowerCase() || 
			    currentURL.toLowerCase()==NCShellURL.toLowerCase() ||
			    currentURL.toLowerCase()==NCCompatShellURL.toLowerCase()) {
				if (mbLogout) {
					doLogout()
				}
			}
			writeStatusMessage('Page Unload Step 3 of 4')
			if(window.PageUnload){
				PageUnload()
			}
			writeStatusMessage('Page Unload Step 4 of 4')
		}
	}
}

//ISK added to logout if user navigates to another website
function doLogout() {
	var c=new XmlHttpClient();
    var r=new GetRequest();
    var LOGOUT_URL=oLibPage.applicationBase + "/Forms/Logout.aspx";
    r.timeout=getTimeOut();
    r.setUrl(LOGOUT_URL);
    r.addParam('method','GET');
    c.asyncCall(r, null);
}

function _WRFQueryUnload(oEvent){
	// abw 5/25/05 added oEvent to help Firefox maintain reference to original event
	writeStatusMessage('Page Unload Step 1 of 4')
	var bShowWarning=false
	var bDirty=false

	if(window.PageQueryUnload){
		PageQueryUnload()
	}

	if(!wrfbOKToNavigate){
		if(_WRFIsPageDirty()){
			//event.returnValue="The data on this page has been modified and not saved."
			oEvent.returnValue="The data on this page has been modified and not saved."
		}
	}
	
	if (typeof(oLibPage) != 'undefined'){
	
		var bHasSessionTimedOutMethod;
		
		try{
			bHasSessionTimedOutMethod = (typeof(oLibPage.hasSessionTimedOut) != 'undefined');
		}catch(err){
			bHasSessionTimedOutMethod = false;
		}
	
		if (bHasSessionTimedOutMethod) {			// added for safe modal closedown when parent is closed 1st.
			if (typeof(window.dialogArguments) != 'undefined'){
				if(!oLibPage.hasSessionTimedOut() && window.dialogArguments){
					setSessionTimeoutWarning(window.dialogArguments)
				}
			}
		}
	}

	writeStatusMessage('Page Unload Step 2 of 4')
}

function _WRFCreatePrevValuesArray(){
	
	//jswfhPrevValues variable must be on page - VB code will spit this out
	
	var arrTemp=new Array()
	if(jswfhPrevValues!=null && jswfhPrevValues!=''){
		// ChY - jswfhPrevValues_skip flag added to bypass comparison of current and previous values 
		if (typeof(jswfhPrevValues_skip)!='undefined' && jswfhPrevValues_skip=='-1'){
			return (arrTemp)
		}
		arrTemp=eval(jswfhPrevValues)
	}
	return (arrTemp)
}

function _WRFHavePrevValuesChanged(){
	// Call this function from your page to see if your page is dirty from any
	// controls changing
	var sID=''
	for (var sID in awfhPrevValues){
		if(document.getElementById(sID)){
			if(_WRFIsFieldDirty(document.getElementById(sID))){
				return true
			}
		}
	}
	return false
}
	
function _WRFIsFieldDirty(obj, PrevValue){
	// This function will return whether or not a control has changed value.
	// The previous value is pulled from awfhPrevValues which is an assoc. array created
	// by the VB code when the page is created. You may optionally pass in the second parameter
	// to be used as the prev value.

	var PreviousValue
	var bContinue=true

	if(_WRFIsFieldDirty.arguments.length > 1){
		PreviousValue=PrevValue
	}else{
		bContinue=(typeof(awfhPrevValues[obj.id]) != 'undefined')
		if(bContinue){
			PreviousValue=awfhPrevValues[obj.id]
		}
	}
	if(bContinue){
		var sValue=obj.value
		switch (obj.tagName){
			case 'INPUT' :
				if((obj.type=='checkbox')||(obj.type=='radio')){
					if(obj.checked){
						sValue='-1'
					} else {
						// checkboxes may have prev value of '' or 0 check for both
						if(('0'==PreviousValue) || (''==PreviousValue)){
							return false
						}else{
							return true
						}
					}
				}
				if(obj.type=='hidden'){
					//checkboxes are actually hiddens - the above if stmt is now ignored under BBWEB...
					if(obj.getAttribute('bbHtmlType')){ //make sure it exists first
						if(obj.getAttribute('bbHtmlType')=='3'){ //we are a cb hidden
							if(obj.value==0){
								if(('0'==PreviousValue) || (''==PreviousValue)){
									return false //empty string is valid for unchecked cb
								}
							}
						}
					}				
				}
				
				break

			case 'SPAN' :
				sValue=oLibPage.getText(obj)
				break

			case 'DIV' :
				//handle checklists and radiolists
				if(obj.getAttribute('bbHtmlType')){ //make sure it exists first
					if(obj.getAttribute('bbHtmlType')=='21'){ //radiolist
						sValue=oLibPage.getRadioListValue(document.getElementsByName(obj.listname))
					}
					if(obj.getAttribute('bbHtmlType')=='22'){ //checklist
						sValue=oLibPage.getCheckListValue(document.getElementsByName(obj.listname))
					}
					if((sValue=='-1') && (PreviousValue=='')){
						//oLibPage.getRadioListValue will return -1 if none selected
						return false
					}
					
					//ert('ListControl:' + obj.id + ' value:' + sValue)

				}				
				break

			case 'SELECT' :
				if((obj.options.length > 0) && (obj.selectedIndex != -1)){
					sValue=obj.options[obj.selectedIndex].value
					if((sValue=='0') && (PreviousValue=='')){
						//some non-required select fields may have '' or 0
						return false
					}
					//for CodeTables Only: Now for the final comparison, we need the text since that is what is placed in the PrevValues array.
					if(obj.getAttribute('LookupMode')){ //if it exists
						if(obj.getAttribute('LookupMode')=='1'){ // compare descriptions - since ID is in value
							sValue=obj.options[obj.selectedIndex].text
						}
					}
				}
				break
		}

		if(sValue != PreviousValue){
			
			//alert('id: ' + obj.id + '   value:' + sValue + '    Prev:' + PreviousValue)
			
			return true
		}else{
			return false
		}
	}
	else{
		return false
	}
}

function _WRFSave(){
	var bValid=_WRFValidatePage()

	if(bValid){
		if(window.CheckForDeletion){
			var bValid=CheckForDeletion()
		}	
	}
		
	if(bValid){
		wrfbPromptToSave=false;
	}
	mbWRFSave=bValid
	return bValid
}

function _WRFValidatePage(){

	var bValid=true

	bValid=PrepGridForXfer()

    if(bValid){
		if(window.ValidatePage){
			bValid=window.ValidatePage()
		}
	}
               
	if(!bValid){
		if(window.OnValidationFailure){
			window.OnValidationFailure() //some pages want to know this...
		}
	}               
	return bValid
}

function PrepGridForXfer(bValidateFirst){
	var bValidate=true
	var bSuccess=true
	// prepareGridData is dynamically built by BBWebGrid server control
	// and injected onto the page hosting the grid
	if(window.prepareGridData){

		if(PrepGridForXfer.arguments.length > 0){
			bValidate=bValidateFirst
		}
		bSuccess=window.prepareGridData(bValidate)
	}
	return bSuccess;
}

//no longer used?
function _WRFModalOKXfer(sTargetForm, lFlag, bClose){
	var bContinue=true
	if(oLibPage.bIsMac && oLibPage.hasSessionTimedOut()){
		if(oLibPage.getSessionTimedOutAlertShown()){
			_WRFModalClose(oLibPage.mb_Cancel)
		}else{
			oLibPage.alertSessionTimedOut()
			oLibPage.setSessionTimedOutAlertShown(true)
			return
		}
	}

	//callback to page script-if there is one
	if(window.OnModalOK){
		bContinue=OnModalOK()
	}
	
	/******************
	if(bContinue){
	
		if(bClose){
			var sTags='<CLOSEWINDOW FLAG="' + lFlag + '"/>'
		}
		
		if(_WRFModalOKXfer.arguments.length > 3){
			var sAdditionalTags=_WRFModalOKXfer.arguments[3]
			if(sTags){
				sTags=sTags + sAdditionalTags
			} else {
				var sTags=sAdditionalTags
			}
		}

		_WRFFormSwitch(sTargetForm, true, sTags)

	}
	*******************/
}

//no longer used?
function _WRFModalClose(lRetVal){
	//create return object
	var oReturnObj=new Object
	window.top.returnValue=oReturnObj
	oReturnObj.returnValue=lRetVal //set in cWebRecordHelper
	
	//callback to page script-if there is one
	if(window.OnModalClose){
		OnModalClose(oReturnObj)
	}
	
	//User closed form with a command button, so they already decided what they wanted to do.
	//   Set this so that the 'do you wish to save' message (see QueryUnload) will not appear.
	wrfbOKToNavigate=true
		
	if(!oReturnObj.cancelClose){
		window.top.close()
	}
}

function setPromptToSave(bPromptToSave){
	wrfbPromptToSave=bPromptToSave
}

function setSaveFirst(bSaveFirst){
	wrfbSaveFirst=bSaveFirst
}

function promptToSave(saveInfo){
	saveInfo.bCancel=false;
	saveInfo.bSaveFirst=false; 
	if(_WRFIsPageDirty()){
		_WRFConfirmSaveBeforePostback(saveInfo);
	}
}

function onGridXMLLoadFailed(){
	window.location.reload(true)
}

