// Javascript file for the SearchSummary control

//This is the global xml object
//Is this the 3.0 version updated with IE7?
var objCriteriaForSummary = new XMLWrapper("<empty></empty>")

//This is only used to store the xml which is sent in the callback. It is later
//used when the data from the callback is returned.
var tempCriteriaSentInCallback 

//Global object for this Search Control javascrsteven ipt. This is how all the functions
//in this .js file "talk" to other .js files in the page.
var  SearchSummaryControl = new SearchSummaryControlObject

//Load the xml document from the hidden doc
function InitializeSummaryScreen () {
    var xmlString = document.forms[0].hdnSearchCriteriaXmlDoc.value
    //NOTE: this is a global variable
    objCriteriaForSummary = new XMLWrapper(xmlString)
    
    //Throw an event indicating that initializon is now complete
    SearchSummaryControl = new SearchSummaryControlObject
    SearchSummaryControl.Xml = document.forms[0].hdnSearchCriteriaXmlDoc.value
    SearchSummaryControl.IsFinishedInitializationEvent = true
    
   //By making a dummy change to this hidden field, the  onpropertychange event will be thrown
   //document.getElementById("hdnSearchControlInitiatizationEventIndicator").value = "event thrown"   
   //    NOTE: text is needed in this hidden field becuase it's used to test if the initial page is loaded.
   document.getElementById("hdnSearchControlInitiatizationEventIndicator").value = "page is loaded"   
   fireEvent(document.getElementById("hdnSearchControlInitiatizationEventIndicator"), "change");
}

function LoadSearchSummaryTableWithHTML(summaryHTML) {
	var sumSpan = document.getElementById('SpanSearchSummary')
	if (sumSpan != null) {
		sumSpan.innerHTML = summaryHTML;
	}
}

function RemoveSummaryField (xmlNodeName) {
    //Hide the Summary table row
//    var tr = GetTrTagReference(xmlNodeName)
//    tr.style.display = "none"

    //Delete the node from the Xml Doc
//    DeleteXmlNode(objCriteriaForSummary, "//" + xmlNodeName)
    
    //Do any extra processing depending on the page
    if (typeof ItemIsRemovedFromSearchSummaryControl == "function") {
        ItemIsRemovedFromSearchSummaryControl(xmlNodeName)
    }
    //Rerun the callback to get the updated record count
//    UpdateCounts('SearchCount')
}

//sets a field to resetValue (alternative to RemoveSummaryField())
function ResetFieldValue(xmlNodeName, resetValue) {
	if (typeof resetValue !== 'string') {
		resetValue = '';
	}

	var control = GetFieldObject(xmlNodeName);	//SearchGlobalFunctions.js
	if (control.controlType == 'RadioButtons') {	//behavior only defined for RadioButtons
		RemoveDataFromRadioButtonsControl(control, resetValue);	//StandardSearch.js
		objCriteriaForEdit.DeleteNode('//' + xmlNodeName);	//in XmlHelperFunctions.js		
        var newElem = objCriteriaForEdit.CreateElement(xmlNodeName, '', ['Value'], [resetValue]);
        objCriteriaForEdit.AppendNodeToXmlDoc("//Search", newElem)		
		

		DisableViewResultsButton();
		NextButtonIsClicked();	//behave as though "Next" was just clicked; StandardSearch.js
	}
}//ResetFieldValue()

function GetTrTagReference(xmlNodeName) {
    var trTagReference = document.getElementById("trSmry" + xmlNodeName)
    if (trTagReference == null) {
        //alert("trSmry row not found. It should be called: trSmry" + xmlNodeName)
    }
    return trTagReference
}

function EditInPopup(xmlNodeName, extraInfo) {

    var title = ""
    //This element has information about the xml field.
    var trTag = GetTrTagReference(xmlNodeName)
    if (trTag != null) {
        //"hd" is the attribute for the header.
        title = trTag.getAttribute("hd")
    }
    

    var arrReturn = window.showModalDialog(GetResolveUrl() + "/Search/Popups/EditSingleCriteria.aspx?node="+xmlNodeName+"&extraInfo="+extraInfo+"&title="+title, "", "resizable: yes; dialogWidth:" + AdjustPopupWidth(745, "px") + "; dialogHeight: " + AdjustPopupHeight(300, "px") + "; edge: sunken; help: no; status: yes; scroll: no; center: yes;");
    //arrReturn will contain the new Xml Criteria. Only process it if it exists. If not, the the user probably clicked "Cancel"
    if (arrReturn != undefined) {
        var returnedXml = decodeURI(arrReturn)
                
        //This object can be used by any function which attaches to the event below.
        SearchSummaryControl = new SearchSummaryControlObject
        SearchSummaryControl.Xml = returnedXml
        
        //Load the new criteria into the current xml document.        
        objCriteriaForSummary = new XMLWrapper(returnedXml)
        
        
        //Refresh the screen table 
        HideAllTdElements()
        
        if (document.getElementById("hdnSearchControlPostAfterCriteriaUpdated").value == "true") {
            //Post the page if the "ThrowSearchCriteriaUpdatedEvent" was set on the server.
            PostPageThroughSubmitButton(returnedXml)
        } else {
            //Throw the event indicating that data was changed so other .js functions are notified
            fireEvent(document.getElementById("hdnSearchControlSearchCriteriaChangedEventIndicator"), "change");
        }
   }
}

function SetupTheXmlForThePageSubmit(xmlToSend) {
    document.getElementById("hdnReturnXmlToServer").value = xmlToSend	
}
//Post the page to the server through the invisible "btnRefreshPage" button.
function PostPageThroughSubmitButton(xmlToSend) {					    
    //Before posting to the page, write the xml search criteria to a hidden variable to the server can use it.
    SetupTheXmlForThePageSubmit(xmlToSend)
   
    //click the submit button
    var refreshButtonName =  document.getElementById("hdnSearchControlBaseName").value + "_btnRefreshPage"
    //document.getElementById(refreshButtonName).onclick()
    document.getElementById(refreshButtonName).click()
}

function UpdateSearchCriteriaTable(objCriteriaForEdit) {
    //Hide all the current table elements
    HideAllTdElements()
    
    //Save the xml for the next round
    //objCriteriaForSummary.loadXML(objCriteriaForEdit.xml)
    objCriteriaForSummary = new XMLWrapper(objCriteriaForEdit.String())
    
    //Display the current table elements
    //LoadSearchSummaryTable()
    LoadSearchSummaryTableWithHTML(SearchSummaryControl.SummaryHTML)
}

//This function is called by other functions when the idea is to clear the
//data displayed on the screen.
function ClearDataInSearchSummaryControl() {
    HideAllTdElements()
}

function HideAllTdElements() {

	var searchSummaryTable = document.getElementById("searchCrit");
		
	//This should never be true, but it's just in case...
	if (searchSummaryTable != null) {
		
		//Clear the SearchSUmmary table of all rows.
		while(searchSummaryTable.getElementsByTagName("TR").length>0)
		{
			searchSummaryTable.deleteRow(0);
		}
	}
}
//This is a special global flag used in the client javascript of
//custom validators to indicate that this the validation is 
//occuring before the page is submitted or before a client
//callback.  This is needed for extra validation
var specialValidationBeforeSubmit = false

// Run the callback to update the record counts on the screen. (The screen is updated in another function)
function UpdateCounts(typeOfUpdate) {
	var result = true;

    //Clear the data from the screen
    ClearDataInSearchSummaryControl()
    
    //This variable is defined by the .Net runtime and is created after we set a default button to "automatically" be clicked
    //after the user hits the enter key. It used to to determine if the form has already tried to be submitted.
    //It in the aspx.vb page like this:
    //Page.Form.DefaultButton = {Button Unique Id}.     In this case, we don't want the form submitted because we're using
    //a client callback instead.   Since the page is not submitted, we change the __defaultFired variable to say it wasn't.
    //I hope all this makes sense....
     __defaultFired = false;

    //Get lat/lon if radius and location is specified in the search criteria
     if (typeof GetSearchType == "function") {
     	var searchType = GetSearchType(objCriteriaForEdit)
     	if (searchType == "Standard" || searchType == 'BrokerTourOpenHouse' || searchType == 'Hotsheet') {
     		result = SelectCenterOfRadius_Main(typeOfUpdate);

     		//When everything is fine then UpdateCounts_Complete() function is called
     		//after the callback has returned from the server.
     		//Otherwise, call it here.
     		if (!result) {
     			UpdateCounts_Complete(typeOfUpdate);
     		}
     	}
     	else {
     		//Proform the rest of the steps for other search types
     		result = UpdateCounts_Complete(typeOfUpdate);
     	}
     }
     else {
     	//Proform the rest of the steps for all other search; Inventory, MlsNumber, Address.
     	result = UpdateCounts_Complete(typeOfUpdate);
     }

    return result;
}

var SelectCenterOfRadius_Main = function(typeOfUpdate) {
	//We want to default the return result to false so that UpdateCounts_Complete() will be called.
	//GetLocationLatLonFromServer function will set result to true when is made the server call.
	//When Radius is not specified in the search criteria this function will return false and
	//UpdateCounts_Complete is called.  Otherwise, UpdateCounts_Complete is called after the server
	//callback has returned.
	var result = false;

	//Declare the function to run after the server callback has returned.
	var SelectCenterOfRadiusComplete = function(selectedCenter) {
		if (selectedCenter != null) {
			//Update the lat/lon hidden inputs and the location textbox
			var latHiddenInput = GetRadiusLatitudeInputControl(control); // control variable is available through closure
			var lonHiddenInput = GetRadiusLongitudeInputControl(control);
			var locationInput = GetRadiusLocationInputControl(control);
			latHiddenInput.value = selectedCenter.latitude;
			lonHiddenInput.value = selectedCenter.longitude;
			locationInput.value = selectedCenter.locationText;

			//Update thevalues in the control
			control.centerLatitude = selectedCenter.latitude;
			control.centerLongitude = selectedCenter.longitude;
			control.centerLocationText = selectedCenter.locationText

			//Update the values in the search criteria
			objCriteriaForEdit.SetXmlNodeAttribute("/Search/" + control.xmlNodeName,
					"CenterLatitude",
					selectedCenter.latitude,
					false);
			objCriteriaForEdit.SetXmlNodeAttribute("/Search/" + control.xmlNodeName,
					"CenterLongitude",
					selectedCenter.longitude,
					false);
			objCriteriaForEdit.SetXmlNodeAttribute("/Search/" + control.xmlNodeName,
					"LocationText",
					selectedCenter.locationText,
					false);

			//Proform the rest of the steps after the server callback is complete.
			return UpdateCounts_Complete(typeOfUpdate);
		}
		else {
			//A lat lon was not found or the user didnot choose one.
			ResultsControl_SetResultsValue("");
			return false;
		}


	} // End of SelectCenterOfRadiusComplete() function

	//----- Main code begins -----

	//Find first radius search fields from objCriteriaForEdit
	var allNodes = objCriteriaForEdit.GetNodeNamesOfChildren('/Search');
	var tmpControl;
	for (var x = 0; x < allNodes.length; x++) {
		tmpControl = GetFieldObject(allNodes[x]);
		if (tmpControl != null && tmpControl.controlType == 'Radius') {

			var oNode = objCriteriaForEdit.SelectFirstNode("/Search/" + tmpControl.xmlNodeName)
			var control = GetFieldObjectAndLoadData(tmpControl.xmlNodeName, oNode)
			if (!control.IsEmpty()) {
				if (control.centerLatitude == '' || control.centerLongitude == '') {
					if (control.locationText == null || control.locationText == '') {
						return false;
					}
					//Call the server method in SelectCenterOfRadius.js to get the lat/lon.
					result = GetLocationLatLonFromServer(control.locationText, SelectCenterOfRadiusComplete);
				}
			}
			//else Radius is not speificed in the search criteria.  Result is default to false.
			break;
		}
	}
	return result;
}

function UpdateCounts_Complete(typeOfUpdate) {
	if (PerformAllPageValidation() == false) {
		return false
	}

	//Set the default, if not is provided.   
	if (typeOfUpdate == "") {
		typeOfUpdate = "SearchCount"
	}

	RunClientCallback(typeOfUpdate, "", objCriteriaForEdit)
	return true
}

//Performs all .Net and non .Net page validation
function PerformAllPageValidation() {
	
	var isErrors = false
	
    //Perform any Non-.Net Validation functions, if any exist.
    if (typeof PreValidationCheck == "function") {
        // If the pre-validation function fails, then do not continue and exit this function
        if (PreValidationCheck() == false) {
            return false
            
            isErrors = true
        }
    }
    
    // Validate the XML Criteria first, if the function exists (only for the Standard Search)
    if (typeof ValidateXmlCriteria == "function") {
            var errors = ValidateXmlCriteria(objCriteriaForEdit)
            if (errors != "") {
                //what to do??  Maybe highlight errors?
                //alert (errors) 
                //return false' 
	            isErrors = true
            }
     }

    //Validate the page
    if (typeof(Page_ClientValidate) == 'function') {
        
        //set the variable used by custom validators to indicate validation 
        //is now occurring on a page level before a client callback to get 
        //the record count. Extra validation occurs in some of the custom
        //validators.
        specialValidationBeforeSubmit = true
                
        var validatorGroup
    
    	//We only want to validate the controls from the StandardSearchVew control.        
        validatorGroup = document.getElementById("StandardSearchViewControl_ValidationGroup")
        if (validatorGroup == null) {
	        Page_ClientValidate();        	
        }
        else {
   	        Page_ClientValidate(validatorGroup.value);
        }
        
        specialValidationBeforeSubmit = false
        if (!Page_IsValid) {
	        isErrors = true
        	//Popup an alert telling the user there were errors.
        }                 
    }       
    
    if (isErrors == true) {
	        alert(GetErrorFromClientErrorMasterManager("GeneralErrors"))
	        return false    	
    }  else {
	    //The page must be valid!
	    return true
	}
}    

//function pointers for the BeginValidateSearchCriteriaOnServer function and CallbackHandlerForSearchSummaryControl functions.
var fnServerValidation_Valid, fnServerValidation_Invalid, fnServerValidation_Exception

//This function is used to validate the search critieria on BOTH the client and server.
//The parameters are the function pointers. Do not put quotes around the names.
//Returns a true if the client validation was valid.
function BeginValidateSearchCriteriaOnServer(validFunction, invalidFunction, exceptionFunction) {
	
	//First, perform all client side validation
	if (PerformAllPageValidation() == true) {

		//Globally, save the function pointers because they will be used in the CallbackHandlerForSearchSummaryControl function after the
		//callback is returned from the server.
		fnServerValidation_Valid = validFunction
		fnServerValidation_Invalid = invalidFunction
		fnServerValidation_Exception = exceptionFunction
		
		AddJsEvent(document.getElementById("hdnSearchControlValidate_IsValidEventIndicator"), "change", fnServerValidation_Valid)
		AddJsEvent(document.getElementById("hdnSearchControlValidate_ValidationErrorEventIndicator"), "change", fnServerValidation_Invalid)
		AddJsEvent(document.getElementById("hdnSearchControlValidate_ExceptionErrorEventIndicator"), "change", fnServerValidation_Exception)
				
		//Second, perform the server side validation
		RunClientCallback("Validate", "", "", true);
		
		//Return "true" which means that all client side validation is successful and the callback was called
		//successfully (but not returned yet)
		return true;
	} else {
		//Return false since client validation failed.
		return false;
	}
}

function TestServerValidation() {
	if (!BeginValidateSearchCriteriaOnServer(TestServerValidation_Valid, TestServerValidation_Invalid, TestServerValidation_Exception)) {
		//Client Side Error Occurred.  An alert popup message already appeared on the screen. 
	}
	
	var browserEvent = new cbEvent(event)
	browserEvent.preventDefault();
	browserEvent.stopPropagation();   
	return false;	
}
function TestServerValidation_Valid() {
   //Clear any error messages
    ClearGeneralMessages()
	alert ("Your Search Criteria is Valid!")	
}
function TestServerValidation_Invalid() {
		//The server determined the search criteria is invalid. 
        //Popup the general error message:  alert(GetErrorFromClientErrorMasterManager("GeneralErrors"))
		alert ("Server Validation Errors Occurred: "+ SearchSummaryControl.AdditionalMessages)
}
function TestServerValidation_Exception() {	
		//Popup error. The generic message will also appear on the screen.
		alert ("Program Exception occured on Server: "+ SearchSummaryControl.AdditionalMessages)	
}


function RunClientCallback(requestType, context, criteria, doNotRunPreCallbackEvents ) {

    //Store the xml that is sent to the server to be later used when it comes back. We don't want to
    //use the copy coming in because it *may* have changed if the server processing is slow.
    //This is a global variable
    tempCriteriaSentInCallback = objCriteriaForEdit.String()
    
    var xmlString = ""
    xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
     "<SearchCallback>" +
	            "<RequestType>" + requestType + "</RequestType>" + 
	            "<SearchCriteriaXml>" + tempCriteriaSentInCallback + "</SearchCriteriaXml>" + 
	            "</SearchCallback>"
    
    //Throw an "onpropertychangedevent" by adding dummy data to this hidden field.
    if (doNotRunPreCallbackEvents != true) {
    	if (document.fireEvent) {
    		fireEvent(document.getElementById("hdnSearchControlDirectlyBeforeClientCallbackEventIndicator"), "change");
    	}
    	else {
			var changeEvent = document.createEvent("Event");
            changeEvent.initEvent ("change", true, false);
            document.getElementById("hdnSearchControlDirectlyBeforeClientCallbackEventIndicator").dispatchEvent(changeEvent);
    	}
    }
	            
    //Make the callback.  The next item that will run will be the CallbackHandlerForSearchSummaryControl function.
    CallbackServerCallForSearchSummary(xmlString, context)
}

//Used to stop the client callback from firing while it's still running on the server. It's a hack to keep
//it synchrounous.
var disableNextButton = false

function CallbackHandlerForSearchSummaryControl(result, context) {
        
		//Reset the Mls V4 timer which appears on the bottom of the screen.
		if (typeof fn_ResetTimeOut == "function") {
			fn_ResetTimeOut();
		}
        
        //Throw an "onpropertychangedevent" by adding dummy data to this hidden field.
        fireEvent(document.getElementById("hdnSearchControlDirectlyAfterClientCallbackEventIndicator"), "change");
        
        var validMlsNumbers = document.getElementById("hdnValidMlsNumbers")
        
        //set the onclick event on the Next button so the user can click it again.
        disableNextButton = false

        //break apart the result:
        var arrResult =  result.split("|"+String.fromCharCode(30)+"|")
                
        var requestType = arrResult[0]
        var serverStatus = arrResult[1]
        var recordCount = arrResult[2]
        var additionalMessages = arrResult[3]
        var mlsIds = arrResult[4]
        var summaryHTML = arrResult[5]
        var extraJsToRun = arrResult[6]
       
        validMlsNumbers.value = mlsIds
        
        //Setup the SearchSummaryControl object as it will be used in conjunction with an event
        SearchSummaryControl = new SearchSummaryControlObject
        SearchSummaryControl.RequestType = requestType
        SearchSummaryControl.ServerStatus = serverStatus
        SearchSummaryControl.RecordCount = recordCount
        SearchSummaryControl.AdditionalMessages = additionalMessages
        SearchSummaryControl.MlsIds = mlsIds
        SearchSummaryControl.EditXmlChangedSinceReturnFromCallback = false;
        SearchSummaryControl.SummaryHTML = summaryHTML;
       
        switch (requestType) {
            case "SearchCount":
            case "SearchCount,UpdateSession,UpdateLastSearchTable":
            case "SearchCount,ReturnMlsIds":
            case "SearchCount,SetupInfoForMarketAnalysisPopup":
                switch (serverStatus) {
                    case "OK":
                        if (tempCriteriaSentInCallback == objCriteriaForEdit.String()) {
                            SearchSummaryControl.EditXmlChangedSinceReturnFromCallback = false;
                        } else {
                            SearchSummaryControl.EditXmlChangedSinceReturnFromCallback = true;
                        }
                        objCriteriaForSummary = new XMLWrapper(tempCriteriaSentInCallback)
                        fireEvent(document.getElementById("hdnSearchControlValidRecordCountEventIndicator"), "change");
                        UpdateSearchCriteriaTable(objCriteriaForSummary)
                        break;
                        
                    case "ValidationError":
                    	
                        //Throw an event indicating that there are validation errors on the server
                        fireEvent(document.getElementById("hdnSearchControlValidationErrorEventIndicator"), "change");
                        
                        //In a normal situation, the objCriteriaForEdit xml object should not be changed because the time
                        //lag between the start of the callback to the end should be very quick. However, if it takes a long
                        //time, we saved off a copy of the xml to be used.  We don't use the original xml from the edit screen
                        //because the user might have changed it.
                        objCriteriaForSummary = new XMLWrapper(tempCriteriaSentInCallback)
                        
                        //Update the SearchSummary control table (<td> elements)
                        //UpdateSearchCriteriaTable(objCriteriaForEdit)
                        UpdateSearchCriteriaTable(objCriteriaForSummary)                        
                        
                        break;
                    case "Exception":
                        //Throw an event indiciating that there was an exception on the server
                        fireEvent(document.getElementById("hdnSearchControlExceptionErrorEventIndicator"), "change");
                        
                        break;
                    default:
                        alert ("Invalid return server status in the callback: " + serverStatus + ".  The returned xml is : " + result)
                        break;
                }                
                break;
            
            case "SearchCount,SetupForTrendPEPopup":
                
                //serverStatus indicates if there were any problems processing the record count on the server
                switch (serverStatus) {
                    case "OK":
                        //Now that the return was successful, update the search criteria for the SearchSummary control
                        
                        if (tempCriteriaSentInCallback == objCriteriaForEdit.String()) {
                            SearchSummaryControl.EditXmlChangedSinceReturnFromCallback = false;
                        } else {
                            SearchSummaryControl.EditXmlChangedSinceReturnFromCallback = true;
                        }
                        
                        //In a normal situation, the objCriteriaForEdit xml object should not be changed because the time
                        //lag between the start of the callback to the end should be very quick. However, if it takes a long
                        //time, we saved off a copy of the xml to be used.  We don't use the original xml from the edit screen
                        //because the user might have changed it.
                        objCriteriaForSummary = new XMLWrapper(tempCriteriaSentInCallback)
                    
                        //Throw an event indicating that a successful count was retrieved
                        fireEvent(document.getElementById("hdnSearchControlValidRecordCountEventIndicator"), "change");
                        
                        //Update the SearchSummary control table (<td> elements)
                        //UpdateSearchCriteriaTable(objCriteriaForEdit)
                        UpdateSearchCriteriaTable(objCriteriaForSummary)
                        
                        break;
                    case "ValidationError":
                    	
                        //Throw an event indicating that there are validation errors on the server
                        fireEvent(document.getElementById("hdnSearchControlValidationErrorEventIndicator"), "change");
                        
                        //In a normal situation, the objCriteriaForEdit xml object should not be changed because the time
                        //lag between the start of the callback to the end should be very quick. However, if it takes a long
                        //time, we saved off a copy of the xml to be used.  We don't use the original xml from the edit screen
                        //because the user might have changed it.
                        objCriteriaForSummary = new XMLWrapper(tempCriteriaSentInCallback)
                        
                        //Update the SearchSummary control table (<td> elements)
                        //UpdateSearchCriteriaTable(objCriteriaForEdit)
                        UpdateSearchCriteriaTable(objCriteriaForSummary)                        
                        
                        break;
                    case "Exception":
                        //Throw an event indiciating that there was an exception on the server
                        fireEvent(document.getElementById("hdnSearchControlExceptionErrorEventIndicator"), "change");
                        
                        break;
                    default:
                        alert ("Invalid return server status in the callback: " + serverStatus + ".  The returned xml is : " + result)
                        break;
                }                
                break;
            case "Validate":
            	switch (serverStatus) {
            		case "OK":
                        //Throw an event indicating the validation was successful
                        fireEvent(document.getElementById("hdnSearchControlValidate_IsValidEventIndicator"), "change");
                        break;
                    case "ValidationError":
                        //Throw an event indicating that there are validation errors on the server. 
                        fireEvent(document.getElementById("hdnSearchControlValidate_ValidationErrorEventIndicator"), "change");
                        
                        //Throw an event indicating that there are validation errors on the server. This is the same
                        //event thrown above so the message is displayed on the screen.
                        fireEvent(document.getElementById("hdnSearchControlValidationErrorEventIndicator"), "change");
                        break;
                    case "Exception":
                        //Throw an event indiciating that there was an exception on the server
                        fireEvent(document.getElementById("hdnSearchControlValidate_ExceptionErrorEventIndicator"), "change");

                        //Throw an event indiciating that there was an exception on the server. This is the same
                        //event thrown above so the message is displayed on the screen.                        
                        fireEvent(document.getElementById("hdnSearchControlExceptionErrorEventIndicator"), "change");
                        break;
                    default:
                        alert ("Invalid return server status in the Validate callback: " + serverStatus + ".  The returned xml is : " + result)
                        break; 
            	}
            	            	
            	//Detach the events            	
				DetachJsEvent(document.getElementById("hdnSearchControlValidate_IsValidEventIndicator"), "change", fnServerValidation_Valid) 
				DetachJsEvent(document.getElementById("hdnSearchControlValidate_ValidationErrorEventIndicator"), "change", fnServerValidation_Invalid) 
				DetachJsEvent(document.getElementById("hdnSearchControlValidate_ExceptionErrorEventIndicator"), "change", fnServerValidation_Exception)             	
            	break;
            //Not in use at this time.
            case "InformationalLog":
                // do nothing
            //Not in use at this time.                
            case "JavascriptException":
                // do nothing
            default:
                alert("Invalid Request Type on callback: " + requestType)
                break;
        }
        
        //In some cases, the callback will return some javascript to run.
        //(right now, it's with the SetupForTrendPEPopup and possibly more)
        if (extraJsToRun.length > 0) {
        	eval(extraJsToRun)
        }

}

function HttpErrorInCallback(context) {

    //Throw an "onpropertychangedevent" by adding dummy data to this hidden field.
    fireEvent(document.getElementById("hdnSearchControlDirectlyAfterClientCallbackEventIndicator"), "change");

	//This should probably be part of the error system messages(?)
    var errorMessage = "The server could not be contacted. Please try again later or contact the Help Desk." + "<!--" + context + "-->"
    
    alert (errorMessage)
    
    //Setup the SearchSummaryControl object as it will be used in conjunction with an event
    SearchSummaryControl = new SearchSummaryControlObject
    SearchSummaryControl.AdditionalMessages = errorMessage
    fireEvent(document.getElementById("hdnSearchControlCallbackErrorIndicator"), "change");
        
}

////used for the popup
function RunReportClicked () {

   //Load the xml into a hidden field so the server application can use it
   var returnXml = document.getElementById("hdnReturnXmlToServer")
   returnXml.value = objCriteriaForSummary.String()
   //Submit the form
   return true
}

/****************************************

   Objects & Object Functions

****************************************/

// This objct represents general information about the MlsNumber mode
// and a wrapper for the xml file.
function MlsNumberControl(oNode) {

    //Inherits FromToControlInfo.. pass the nodename to the constructor
    this.base = MlsNumberControlInfo    
    this.base (oNode.nodeName)    
    
    this.Values = new Array()
    this.Values = populateArrayWithChildNodes(oNode)
}

//
function MlsNumberControlInfo(xmlNodeName) {

    var trTag = GetTrTagReference(xmlNodeName)
    this.header = trTag.getAttribute("hd")
    if (this.header == null) {this.header = ""}
    this.xmlNodeName = xmlNodeName
}


//This object is used to tell other .js functions that certain things occurred
//when processing a client callback.
function SearchSummaryControlObject () {
    //Set after callback returns any type of error
    this.ErrorDescription = ""
    //Xml
    this.Xml = ""
    //The request type sent to the server
    this.RequestType = ""
    //The status indicating if the server processing was successful
    this.ServerStatus = ""
    //The record count
    this.RecordCount = ""
    //Any additional messages
    this.AdditionalMessages = ""
    //Any returned Mls Ids returned for the Mls Number Search
    this.MlsIds = ""
    //Indicates if the user changed the xml since it was sent to the server
    this.EditXmlChangedSinceReturnFromCallback = false
    // HTML content for the Listing Search criteria
    this.SummaryHTML = ""
}   
