﻿var _action = '';

var IsInternalHBMUser;

var _divPromptRegistrationAction = 'divPromptRegistrationAction';
var _divThankYou = 'divThankYou';
var _divRegistrationError = 'divRegistrationError';
var _divRegistrationMessage = 'divRegistrationMessage';
var _divAcceptPremiumService = 'divAcceptPremiumService';
var _wireframe_blackout = 'wireframe_blackout';

var _currUserListing;
var _lenderName = '';
var _makeAnOfferName = '';
var _userRating;
var _listingID;
var _applicationFeatureDescription;
var _userHasAcceptedTermsOfService = 0;

var hashToUnlockTxt = new Object();

var _actionAddToNotebook = "AddToNotebook";
var _actionScheduleAShowing = "ScheduleAShowing";
var _actionRequestDirection = "RequestDirections";
var _actionSearchForeclosures = "SearchForeclosures";
var _actionMakeAnOffer = "MakeAnOffer";
var _actionAskAnAgent = "AskAnAgent";
var _actionFinancingQuestion = "FinancingQuestion";
var _actionGetPreApproved = "GetPreApproved";
var _actionAddANote = "AddANote";
var _actionListingDetailView = "ListingDetailView";
var _actionQuickAlerts = "QuickAlerts";
var _actionSaveSearch = "SaveSearch";
var _actionViewNotes = "ViewNotes";
var _actionRequestAddress = "RequestAddress";
var _actionListingCategory_OpenHouse = "ShowListingCategory_OpenHouse";
var _actionListingCategory_Foreclosure = "ShowListingCategory_Foreclosure";
var _actionListingCategory_PreListing = "ShowListingCategory_PreListing";

var _txtNewSavedSearch = "txtSearch_SaveNew";
var _txtSearch_SaveAs = "txtSearch_SaveAs";
var _txtExistingSavedSearchName = "txtSearch_Save";

hashToUnlockTxt[_actionAddToNotebook ] = "To unlock this feature please provide the following information.";
hashToUnlockTxt[_actionScheduleAShowing] = "A certified real estate agent will be happy to show you this property or any other property. Please provide the following information.";
hashToUnlockTxt[_actionRequestDirection] = "Please provide the following information to unlock this feature:";
hashToUnlockTxt[_actionSearchForeclosures] = "To unlock the 'Search Foreclosures' feature, please provide the following information.";
hashToUnlockTxt[_actionMakeAnOffer] = "A certified real estate agent will assist you in making an offer on this property. Please provide the following information.";
hashToUnlockTxt[_actionAskAnAgent] = "A certified real estate agent can anwser questions about this property or any other property. Please provide the following information.";
hashToUnlockTxt[_actionFinancingQuestion] = "If you have financing questions about this property or any other property, please provide the following information and we will have a lender contact you shortly.";
hashToUnlockTxt[_actionGetPreApproved] = "{0} can help you with all your financing needs including pre-approval. Please provide the following information and we will have a lender contact you.";
hashToUnlockTxt[_actionAddANote] = "To unlock this feature please provide the following information.";
hashToUnlockTxt[_actionListingDetailView] = "Thanks for choosing <a href='http://www.greatrealestate.com'>www.greatrealestate.com</a> for your home search.<br /><br />To continue your home search and unlock all the features of our FREE premium service, the <i>Home Buyers Scouting Report</i><sup>&reg;</sup>, please provide the following information:";
hashToUnlockTxt[_actionQuickAlerts] = "To unlock this feature please provide the following information.";
hashToUnlockTxt[_actionSaveSearch] = "To unlock this feature please provide the following information.";
hashToUnlockTxt[_actionViewNotes] = "To unlock this feature please provide the following information.";
hashToUnlockTxt[_actionRequestAddress] = "To unlock this feature please provide the following information.";

hashToUnlockTxt[_actionListingCategory_OpenHouse] = "To view open house listings please create an account:";
hashToUnlockTxt[_actionListingCategory_Foreclosure] = "<p style=\"font-size:14px;font-weight:bold;\">Sign up today to receive your FREE list of bank-owned/foreclosures properties, and you will receive email notifications when:</p><ul><li>New Foreclosure listings hit the market</li><li>One of your \"favorite\" foreclosure listings goes off the market or the price drops</li></ul><hr style=\"background-color:Black;height:3px;width:70%;border:0px;margin-right:auto;margin-left:auto;\" /><p style=\"font-size:24px;text-align:center;\">JOIN NOW</p><p style=\"text-align:center;\">Please provide the following information:</p>";
hashToUnlockTxt[_actionListingCategory_PreListing] = "To view pre-listings please create an account:";

var hashAltMessage = new Object();
hashAltMessage[_actionAddToNotebook] = "";
hashAltMessage[_actionScheduleAShowing] = "Please provide the following information:";
hashAltMessage[_actionRequestDirection] = "Please provide the following information:";
hashAltMessage[_actionSearchForeclosures] = "";
hashAltMessage[_actionMakeAnOffer] = "{0} will be glad to assist you in making an offer on this property. Please provide the following information:";
hashAltMessage[_actionAskAnAgent] = "If you have a question about his property, or any other property, we can have an agent contact you shortly. Please provide the following information.";
hashAltMessage[_actionFinancingQuestion] = "If you have financing questions about this property or any other property, please provide the following information and we will have {1} contact you shortly.";
hashAltMessage[_actionGetPreApproved] = "{0} can help you with all your financing needs including pre-approval. Please provide the following information and we will have {1} contact you.";
hashAltMessage[_actionAddANote] = "";
hashAltMessage[_actionListingDetailView] = "Thanks for using choosing <a href='http://www.greatrealestate.com'>www.greatrealestate.com</a> for your home search.<br /><br />To continue your home search and unlock all the features of our FREE premium service, the <i>Home Buyers Scouting Report</i><sup>&reg;</sup>, please provide the following information:";
hashAltMessage[_actionQuickAlerts] = "To unlock this feature please provide the following information.";
hashAltMessage[_actionSaveSearch] = "";
hashAltMessage[_actionViewNotes] = "";
hashAltMessage[_actionRequestAddress] = "Please provide the following information:";

hashAltMessage[_actionListingCategory_OpenHouse] = "Please provide the following information:";
hashAltMessage[_actionListingCategory_Foreclosure] = "Please provide the following information:";
hashAltMessage[_actionListingCategory_PreListing] = "Please provide the following information:";

var hashThankYouTxt = new Object();
hashThankYouTxt[_actionAddToNotebook] = "Thank you. The property is saved to your favorites.";
hashThankYouTxt[_actionScheduleAShowing] = "Thank you. A certified real estate agent will contact you shortly.";
hashThankYouTxt[_actionRequestDirection] = "Thank you.";
hashThankYouTxt[_actionSearchForeclosures] = "Thank you. You can now search for foreclosed properties on our premium service.";
hashThankYouTxt[_actionMakeAnOffer] = "Thank you. A certified real estate agent will contact you shortly.";
hashThankYouTxt[_actionAskAnAgent] = "Thank you. A certified real estate agent will contact you shortly.";
hashThankYouTxt[_actionFinancingQuestion] = "Thank you. Your request is important to us and we’ll have {1} contact you shortly.";
hashThankYouTxt[_actionGetPreApproved] = "Thank you. Your request is important to us and {1} will contact you shortly.";
hashThankYouTxt[_actionAddANote] = "Thank you. Your note has been added to this listing.";
hashThankYouTxt[_actionListingDetailView] = "Thank you.";
hashThankYouTxt[_actionQuickAlerts] = "Thank you.";
hashThankYouTxt[_actionSaveSearch] = "Thank you. Your search has been saved.";
hashThankYouTxt[_actionViewNotes] = "Thank you.";
hashThankYouTxt[_actionRequestAddress] = "Thank you. A certified real estate agent will contact you shortly.";
hashThankYouTxt[_actionListingCategory_OpenHouse] = "Thank you.";
hashThankYouTxt[_actionListingCategory_Foreclosure] = "Thank you.";
hashThankYouTxt[_actionListingCategory_PreListing] = "Thank you.";


var hashFooterTxt = new Object();
hashFooterTxt[_actionAddToNotebook] = "";
hashFooterTxt[_actionScheduleAShowing] = "";
hashFooterTxt[_actionRequestDirection] = "";
hashFooterTxt[_actionSearchForeclosures] = "";
hashFooterTxt[_actionMakeAnOffer] = "";
hashFooterTxt[_actionAskAnAgent] = "";
hashFooterTxt[_actionFinancingQuestion] = "";
hashFooterTxt[_actionGetPreApproved] = "";
hashFooterTxt[_actionAddANote] = "";
hashFooterTxt[_actionListingDetailView] = "";
hashFooterTxt[_actionQuickAlerts] = "";
hashFooterTxt[_actionSaveSearch] = "";
hashFooterTxt[_actionViewNotes] = "";
hashFooterTxt[_actionRequestAddress] = "";
hashFooterTxt[_actionListingCategory_OpenHouse] = "";
hashFooterTxt[_actionListingCategory_Foreclosure] = "<p style=\"font-size:10px;\">HBM II, a national real estate company, provides the FREE list of foreclosure-related properties directly to you. HBM II will not share your information with anyone other than the lender or real estate agent who provided you with information about HBM II's services. HBM II will not sell your information to anyone.</p>";
hashFooterTxt[_actionListingCategory_PreListing] = "";


var hashValidate = new Object();
hashValidate["txtFirstName"] = 0;
hashValidate["txtLastName"] = 0;
hashValidate["txtEmail"] = 0;
hashValidate["txtDayPhone"] = 0;
//hashValidate["txtEveningPhone"] = 0;
hashValidate["txtStreetAddress"] = 0;
hashValidate["txtCity"] = 0;
hashValidate["txtState"] = 0;
hashValidate["txtZip"] = 0;
hashValidate["radioAddressType"] = 0;
hashValidate["txtScheduleAShowingPreferredDate"] = 0;
hashValidate["optDayTime"] = 0;
hashValidate["txtAreaQuestion"] = 0;
hashValidate["divAddANote"] = 0;
hashValidate["txtAreaAddANote"] = 0;
hashValidate["divCommunicationPreference"] = 0;
hashValidate["txtSearch_SaveNew"] = 0;


function HideDivsOrCloseWindow() {

    if (IsShowListingCategoryAction(_action)) {
        window.close();
    }
    else {
        HideRegistrationDivs();
    }
}


function CancelPromptRegistrationAction() {
    HideDivsOrCloseWindow();
}

function HideRegistrationDivs() {
    HideRegistrationDiv(_divPromptRegistrationAction);
    HideRegistrationDiv(_divThankYou);
    HideRegistrationDiv(_divRegistrationError);
    HideRegistrationDiv(_divRegistrationMessage);

}

function HideRegistrationDiv(registrationDiv) {
    SetDisplay(registrationDiv, 'none');
    SetDisplay(_wireframe_blackout, 'none');
}

function ShowRegistrationDiv(registrationDiv) {
    HideWorkingImage();
    HideRegistrationDivs();
    SetDisplay(registrationDiv, 'block');
    SetDisplay(_wireframe_blackout, 'block');
}

function StartRegistration(action, lenderName, makeAnOfferName, listingId, rating) {

    if (lenderName == undefined) { lenderName = "undefined"; }
    if (makeAnOfferName == undefined) { makeAnOfferName = "undefined"; }
    if (listingId == undefined) { listingId = "undefined"; }
    if (rating == undefined) { rating = "undefined"; }


    var isInternalUser = $('txtIsInternalHBUser');
    IsInternalHBMUser = (isInternalUser == null ) ? "False" : isInternalUser.value;

    HidePromptRegistrationActionFields();
    HideRegistrationDivs();
    ShowRegistrationDiv(_divRegistrationMessage);
    ShowWorkingImage();

    var authService = new HBM2.BuyerPortal.WebServices.AuthService();
    var userContext = action + "|" + lenderName + "|" + makeAnOfferName + "|" + listingId + "|" + rating;

    var legacyId = GetCookie("LegacyID");
    var legacyIdIsSet = LegacyIdIsSet(legacyId);

    _applicationFeatureDescription = GetApplicationFeatureDescription(document, action);

    if (legacyIdIsSet) {
        // call WebService
        authService.GetLoginState(StartRegistrationAfterLoginCheckOnSuccess, StartRegistrationAfterLoginCheckOnFailure, userContext);
    }
    else {
        var result = new HBM2.BuyerPortal.WebServices.LoginState();
        StartRegistrationAfterLoginCheckOnSuccess(result, userContext)
    }
}

function StartRegistrationAfterLoginCheckOnSuccess(result, userContext) {
    _userHasAcceptedTermsOfService = result.HasAcceptedTermsOfService;
    var isLoggedIn = result.IsLoggedIn;

    var params = userContext.split("|");

    _action = params[0]; //action
    var lenderName = params[1]; //lenderName
    var makeAnOfferName = params[2];
    var listingId = params[3];
    var rating = params[4];

    if ( listingId != "undefined" && listingId != null )
        document.getElementById('txtListingId').value = listingId;

    if (rating != "undefined" && rating != null)
        document.getElementById('txtUserRating').value = rating;

    var legacyId = GetCookie("LegacyID");
    var legacyIdIsSet = LegacyIdIsSet(legacyId);

    if (legacyIdIsSet && _userHasAcceptedTermsOfService && !isLoggedIn) {
        DisplayRegistrationMessage("Please login to use premium service");
    }
    else {

        var display = ShowRegistrationFields(_action, lenderName, legacyIdIsSet);

        if (display == 1) {
            //            //popup
            ShowRegistrationDiv(_divPromptRegistrationAction);
        }
        else {
            SubmitRegistrationAction(lenderName, makeAnOfferName);
        }
    }
}

function StartRegistrationAfterLoginCheckOnFailure(error) {
    DisplayWebServiceError(error);
}

function SetDisplay(id, style)
{
    var theId = document.getElementById(id)
    if (theId != null) {
        theId.style.display = style;
    }
}

function AcceptPremiumService() {
    HideAcceptPremiumService();

    if (!_userHasAcceptedTermsOfService)
    {
        var ws = new HBM2.WebServices.PromptRegistrationWebService();
        ws.AcceptPremiumService(AcceptPremiumService_OnSuccess, AcceptPremiumService_OnFailure);
        ShowWorkingImage();
    }
}

function AcceptPremiumService_OnSuccess(result) {
    if (result != "")
    {
        //window.close();
        window.open(result);
    }
}

function AcceptPremiumService_OnFailure(error) {
    DisplayWebServiceError(error);
}

function CloseAcceptPremiumService() {
    HideAcceptPremiumService();

}

function CloseRegistrationError() {
    HideAcceptPremiumService();
}


function GetBuyerNoteUpdateId() {
    if (typeof ListingDetail_txtBuyerNoteUpdateId == 'undefined') return null;

    var bnuId = document.getElementById(ListingDetail_txtBuyerNoteUpdateId);
    return bnuId;
}

function NotifySubscribers( action ) {

    switch ( action ) {
        case 'AddANote':
            {
                var bnuId = GetBuyerNoteUpdateId();
                if (bnuId == null) return;
                var prefix = bnuId.value.length > 0 ? "\n\n" : "";
                bnuId.value += prefix + unescape( _currUserListing.NotebookNote );
            }
            break;
    case 'AddToNotebook': {
        if( _currUserListing.UserRating <= 0 )
            {

                    var bnuId = GetBuyerNoteUpdateId();
                    if (bnuId == null) return;
                    bnuId.value = "";
                }
            }
    }
    if (window.opener != undefined) {
        if (window.opener.GetListings != undefined) {
            window.opener.GetListings();
        }
    }
}


function HideAcceptPremiumService() {
    SetDisplay(_divAcceptPremiumService, 'none');
    SetDisplay(_divThankYou, 'none');
    SetDisplay(_divRegistrationError, 'none');
    SetDisplay(_wireframe_blackout, 'none');

}

function CloseThankYou() {
    SetDisplay(_divThankYou, 'none');
    SetDisplay(_wireframe_blackout, 'none');
}

function LegacyIdIsSet(legacyId) {
    return !( legacyId == null || legacyId == '' || legacyId == 'undefined' || legacyId == 0 );
}

function ReplacePreferredLender(message, lender) {
    if( message === undefined ) return message;

    if( lender === undefined ) return message;

    message = message.replace(/\{0\}/, lender);

    if (lender != null) {
        if (lender.substring(0, 3) == "Our") {
            lender = lender.substring(0, 1).toLowerCase() + lender.substring(1);
        }
        message = message.replace(/\{1\}/, lender);
    }
    return message;
}

function SubmitRegistrationAction(lenderName, makeAnOfferName) {

    _currUserListing = PopulateUserAndActionFromUI();

    if (_currUserListing == null) return;

    _currUserListing.ApplicationFeatureDescription = _applicationFeatureDescription;

    if (!ValidationPassed()) return;

    //disable submit button
    document.getElementById('btnOK').disabled = true;

    //We need these ones in the success call back function
    _lenderName = lenderName;
    _makeAnOfferName = makeAnOfferName;
    _userRating = _currUserListing.UserRating;
    _listingID = _currUserListing.ListingId;

    ShowWorkingImage();

    //-------- Display info for debugging -------------
    var queryString="";
    for(var i in _currUserListing){
        if(typeof(_currUserListing[i])!='function') {
            if(!(IsNullOrEmpty(_currUserListing[i]))) {
                queryString+='&'+i+'='+_currUserListing[i];
            }
        }
    }
   $("divResult").innerHTML=queryString;
    //----------------------------------------------------

    var _promptRegistrationWebService = new HBM2.WebServices.PromptRegistrationWebService();


    _promptRegistrationWebService.EnrollOrUpdateUser(_currUserListing, SubmitRegistrationAction_EnrollOrUpdate_Success, SubmitRegistrationAction_EnrollOrUpdate_Failure);
}

function ShowRegistrationError(errorMessage) {
    ShowRegistrationDiv(_divRegistrationError);
    $('divRegistrationErrorTxt').innerHTML = errorMessage;
    SetDisplay('divCloseRegistrationError', 'block');
}

function CloseErrorBox() {
    HideDivsOrCloseWindow();
}


function ForgotUserNameOrPassword() {
    ShowWorkingImage();
    var _promptRegistrationWebService = new HBM2.WebServices.PromptRegistrationWebService();
    _promptRegistrationWebService.ForgotUserNameAndPassword( _currUserListing.Email,  ForgotUserNameAndPassword_Success, ForgotUserNameAndPassword_Failure);

}

function ForgotUserNameAndPassword_Success() {
    DisplayRegistrationMessage("Your user name and password have been sent to " + _currUserListing.Email );    
}

function ForgotUserNameAndPassword_Failure(error) {
    DisplayWebServiceError(error);
}

function DisplayRegistrationMessage(message) {
    ShowRegistrationDiv(_divRegistrationMessage);
    $('divRegistrationMessageTxt').innerHTML = message;
    SetDisplay('divCloseRegistrationMessage', 'block');
}

function CloseRegistrationMessage() {
    HideDivsOrCloseWindow();
}


function ShowWorkingImage() {
    for (var i = 1; i < 5; i++) {
        var divWorkingImageId = 'divWorkingImage' + i;
        var divWorkingImage = document.getElementById(divWorkingImageId);
        if (divWorkingImage != undefined) {
            divWorkingImage.innerHTML = "<img src='../App_Themes/Default/Images/Map/Working.gif'> Please wait.";
        }
    }
}

function HideWorkingImage() {
    for (var i = 1; i < 5; i++) {
        if($('divWorkingImage'+i) != undefined){
            $('divWorkingImage'+i).innerHTML = "";
        }
    }
}

function SubmitRegistrationAction_EnrollOrUpdate_Success( result ) {
    if (result.Status == HBM2.Business.FMUserListing.Entities.EnrollmentStatus.DUPLICATE_USER) {
        ShowRegistrationError("“This email address already exists in our system. <br/><br/>Please login to use premium service.<br/><a href=\"javascript:ForgotUserNameOrPassword();\">Forgot</a> user name or password?");
        return;
    }

    _currUserListing.LegacyId = result.UserEntity.LegacyId;

    var _promptRegistrationWebService = new HBM2.WebServices.PromptRegistrationWebService();

    ShowWorkingImage();

    if (_action != 'SaveSearch')
    {
        _promptRegistrationWebService.ExecuteOtherRequests(_action, _currUserListing, SubmitRegistrationAction_ExecuteOtherRequests_Success, SubmitRegistrationAction_ExecuteOtherRequests_Failure);
    }
    else {
        if ( _search != undefined && _search.SearchID != null)
        {
            updateExistingSavedSearch();
        }
        else
        {
            newSavedSearch();
        }

    }
    NotifySubscribers( _action );

}

function SubmitRegistrationAction_ExecuteOtherRequests_Success() {
    if (_action == 'AddANote') {
        if (_userRating < 0) _userRating = 1;
        RefreshRatingsUI(_userRating, _listingID, "");
    }

    if (_action == 'MakeAnOffer') {
        ThankYou(_makeAnOfferName);
    }
    else {
        ThankYou(_lenderName);
    }

    document.getElementById('btnOK').disabled = false;
}

function SubmitRegistrationAction_EnrollOrUpdate_Failure(error) {
    DisplayWebServiceError(error);
}

function DisplayWebServiceError(error) {
    HideWorkingImage();

    var message = error.get_message();

    var userMessage = message;

    if (IsInternalHBMUser == 'True' ) {
        var stackTrace = error.get_stackTrace();
        var statusCode = error.get_statusCode();
        var exceptionType = error.get_exceptionType();
        var timedout = error.get_timedOut();

        userMessage += "<br/>" +
        "Stack Trace: " + stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout
    }

    ShowRegistrationError(userMessage);

}

function SubmitRegistrationAction_ExecuteOtherRequests_Failure(error) {
    DisplayWebServiceError(error);

    document.getElementById('btnOK').disabled = false;
}

function ThankYou(lenderName) {

    if (_action == "DoNotDisplay") return;

    ShowRegistrationDiv(_divThankYou);

    if (_userHasAcceptedTermsOfService) {
        SetDisplay(_divAcceptPremiumService, 'none');
        SetDisplay('divCloseAcceptedPremiumService', 'block');
    }
    else {
        SetDisplay(_divAcceptPremiumService, 'block');
        SetDisplay('divCloseAcceptedPremiumService', 'none');
    }

    var thankYouTxt = hashThankYouTxt[_action];

    thankYouTxt = ReplacePreferredLender(thankYouTxt, lenderName);

    document.getElementById('divThankYouTxt').innerHTML = '<br/>' + thankYouTxt + '<br/>';
    SetDisplay(_divThankYou, 'block');
    SetDisplay(_wireframe_blackout, 'block');
}

function ValidationPassed() {

    var valRes = true;
    if (hashValidate["txtFirstName"] == 1) {
        valRes &= TestRequiredInput("txtFirstName", "First Name is required.");
        valRes &= TestMaxLen("txtFirstName", 50, "First Name is too long.");
    }
    if (hashValidate["txtLastName"] == 1) {
        valRes &= TestRequiredInput("txtLastName", "Last Name is required.");
        valRes &= TestMaxLen("txtLastName", 50, "Last Name is too long.");
    }
    if (hashValidate["txtEmail"] == 1) {
        valRes &= TestRequiredInput("txtEmail", "Email is required.")
        valRes &= TestMaxLen("txtEmail", 100, "Email is too long.");
        valRes &= TestEmail("txtEmail", "Invalid email.");
    }
    if (hashValidate["txtDayPhone"] == 1) {
        valRes &= TestRequiredInput("txtDayPhone", "Phone is required.");
        valRes &= TestPhoneNumber("txtDayPhone", "Invalid phone number.");
    }
    //    if (hashValidate["txtEveningPhone"] == 1) {
    //        valRes &= TestRequiredInput("txtEveningPhone", "EveningPhone is required.");
    //        valRes &= TestPhoneNumber("txtEveningPhone", "Invalid phone number.");
    //
    //    }
    if (hashValidate["txtStreetAddress"] == 1) {
    }
    if (hashValidate["txtCity"] == 1) {
    }
    if (hashValidate["txtState"] == 1) {
    }
    if (hashValidate["txtZip"] == 1) {
    }
    if (hashValidate["radioAddressType"] == 1) {
    }
    if (hashValidate["txtScheduleAShowingPreferredDate"] == 1) {
        valRes &= TestRequiredInput("txtScheduleAShowingPreferredDate", "Preferred date is required.");
    }
    if (hashValidate["optDayTime"] == 1) {
    }
    if (hashValidate["txtAreaQuestion"] == 1) {
    }
    if (hashValidate["divAddANote"] == 1) {
    }
    if (hashValidate["txtAreaAddANote"] == 1) {
    }
    if (hashValidate["divCommunicationPreference"] == 1) {
    }
    if (hashValidate[_txtNewSavedSearch] == 1) {
        valRes &= TestRequiredInput(_txtNewSavedSearch, "Search Name is required.")
        valRes &= TestMaxLen(_txtNewSavedSearch, 100, "Search Name is too long.");
    }

    if (hashValidate[_txtSearch_SaveAs] == 1) {
        valRes &= TestMaxLen(_txtSearch_SaveAs, 100, "Search Name is too long.");
    }

    if (valRes == 0) {
        alert(errorSummary);
        errorSummary = '';
        return false;
    }
    return true;
}


function PopulateUserAndActionFromUI() {

    var userListing = new HBM2.Business.FMUserListing.Entities.UserListingEntity();

    userListing.FirstName = GetEscapedValue( 'txtFirstName' );
    userListing.LastName = GetEscapedValue( 'txtLastName' );
    userListing.Email = GetEscapedValue( 'txtEmail' );


    var legacyCookie = GetCookie("LegacyID");
    userListing.LegacyId = !LegacyIdIsSet(legacyCookie) ? 0 : GetCookie("LegacyID");

    if ( document.getElementById('txtListingId').value == "undefined" ) {
        alert("Please refresh your browser window");
        throw ("ListingId is not set!." + userListing.LegacyId);
    }

    userListing.ListingId =  GetEscapedValue( 'txtListingId' );

    userListing.UserRating = GetEscapedValue( 'txtUserRating' );
    userListing.MetroAreaId = GetEscapedValue( 'txtMetroAreaId' );
    
    if ( !IsNullOrEmpty( GetEscapedValue('txtDayPhone') ) )
    {
        userListing.DayPhone = GetEscapedValue( 'txtDayPhone' );
    }
    //userListing.EveningPhone = ""; //document.getElementById('txtEveningPhone').value;
    userListing.StreetAddress = GetEscapedValue( 'txtStreetAddress' );
    userListing.City = GetEscapedValue('txtCity');
    userListing.State = GetEscapedValue( 'txtState' );
    userListing.Zip = GetEscapedValue( 'txtZip' );

    var communicationPreferenceRadio = document.getElementsByName('radiocommunicationPreference');
    var communicationPreference = "Phone";

    for (i = 0; i < communicationPreferenceRadio.length; i++) {
        if (communicationPreferenceRadio[i].checked == true)
            communicationPreference = communicationPreferenceRadio[i].value;
    }
    userListing.CommunicationPreference = communicationPreference;


    var addressTypeRadio = document.getElementsByName('radioAddressType');
    var addressType = "Home";
    for (i = 0; i < addressTypeRadio.length; i++) {
        if (addressTypeRadio[i].checked == true)
            addressType = addressTypeRadio[i].value;
    }
    userListing.AddressType = addressType;

    var timeToCallOptions = document.getElementById('optTimeToCall');
    var timeToCall = "Morning";
    for (i = 0; i < timeToCallOptions.options.length; i++) {
        if (timeToCallOptions.options[i].selected == true)
            timeToCall = timeToCallOptions.options[i].value;
    }
    userListing.TimeToCall = timeToCall;

    var dayTimeOptions = document.getElementById('optDayTime');
    var dayTime = "Morning";
    for (i = 0; i < dayTimeOptions.options.length; i++) {
        if (dayTimeOptions.options[i].selected == true)
            dayTime = dayTimeOptions.options[i].value;
    }
    userListing.DayTime = dayTime;


    userListing.ScheduleAShowingPreferredDate = document.getElementById('txtScheduleAShowingPreferredDate').value;
    userListing.Question = GetEscapedValue( 'txtAreaQuestion' );
    userListing.NotebookNote = GetEscapedValue( 'txtAreaAddANote' );

    var scheduleAShowingPreferredDate = document.getElementById('txtScheduleAShowingPreferredDate').value;
    var question = GetEscapedValue( 'txtAreaQuestion' );
    var addANote = GetEscapedValue( 'txtAreaAddANote' );

    return userListing;
}

function GetEscapedValue(elementId) {
    return escape( document.getElementById(elementId).value );
}

function ShowRegistrationFields(action, lenderName, legacyIdIsSet) {
    var display = 0;

    if (legacyIdIsSet) {
        var altMessage = hashAltMessage[action];

        altMessage = ReplacePreferredLender(altMessage, lenderName);

        document.getElementById('divToUnlock').innerHTML = altMessage + '<br />';

    } else {
        //Show First Name, Last Name, email boxes
        SetDisplay('divName', 'block');

        display = 1;
        var toUnlock = hashToUnlockTxt[action];
        toUnlock = ReplacePreferredLender(toUnlock, lenderName);
        $('divToUnlock').innerHTML = toUnlock + '<br />';

        var footer = hashFooterTxt[action];
        $('divFooter').innerHTML = footer + '<br />';


        // Ensure the following are marked to be validated
        hashValidate["txtFirstName"] = 1;
        hashValidate["txtLastName"] = 1;
        hashValidate["txtEmail"] = 1;
    }

    switch (action) {
        case 'AddToNotebook':
        case 'QuickAlerts':
        case 'ViewNotes':
        case 'RequestAddress':
            {
                // do nothing
            }
            break;
        case 'ScheduleAShowing': {
                SetDisplay('divPhone', 'block');
                SetDisplay('divTimeToCall', 'block');
                SetDisplay('divDateTimes', 'block');
                //SetDisplay('divCommunicationPreference','block'); //NOT SUPPORTED!
                display = 1;

                hashValidate["txtScheduleAShowingPreferredDate"] = 1;
                hashValidate["txtDayPhone"] = 1;
                //hashValidate["txtEveningPhone"] = 1;
            }
            break;
        case 'RequestDirections': {
                SetDisplay('divAddress', 'block');
                display = 1;

                hashValidate["txtStreetAddress"] = 1;
                hashValidate["txtCity"] = 1;
                hashValidate["txtState"] = 1;
                hashValidate["txtZip"] = 1;
                hashValidate["radioAddressType"] = 1;
            }
            break;
        case 'SearchForeClosures': {
                // do nothing
            }
            break;
        case "MakeAnOffer": {
                SetDisplay('divPhone', 'block');
                SetDisplay('divTimeToCall', 'block');
                //        SetDisplay('divCommunicationPreference','block';//NOT SUPPORTED!
                display = 1;
                hashValidate["txtDayPhone"] = 1;
                //hashValidate["txtEveningPhone"] = 1;

            }
            break;
        case 'AskAnAgent': {
                SetDisplay('divPhone', 'block');
                SetDisplay('divTimeToCall', 'block');
                //        SetDisplay('divCommunicationPreference','block';//NOT SUPPORTED!
                SetDisplay('divQuestion', 'block');
                display = 1;

                hashValidate["txtDayPhone"] = 1;
                //hashValidate["txtEveningPhone"] = 1;
                hashValidate["divAddANote"] = 1;
            }
            break;
        case 'AddANote': {
                SetDisplay('divAddANote', 'block');
                display = 1;
                hashValidate["txtAreaAddANote"] = 1;
            }
            break;
        case 'FinancingQuestion': {
                SetDisplay('divPhone', 'block');
                SetDisplay('divTimeToCall', 'block');
                //        SetDisplay('divCommunicationPreference','block';//NOT SUPPORTED!
                SetDisplay('divQuestion', 'block');
                display = 1;

                hashValidate["txtDayPhone"] = 1;
                //hashValidate["txtEveningPhone"] = 1;
                hashValidate["txtAreaQuestion"] = 1;
            }
        case 'GetPreApproved': {
                SetDisplay('divPhone', 'block');
                SetDisplay('divTimeToCall', 'block');
                //        SetDisplay('divCommunicationPreference','block';//NOT SUPPORTED!
                display = 1;

                hashValidate["txtDayPhone"] = 1;
                //hashValidate["txtEveningPhone"] = 1;
            }
            break;

        case 'ListingDetailView':
            {
                SetDisplay('btnCancel', 'none');
                display = 1;

                hashValidate["txtFirstName"] = 1;
                hashValidate["txtLastName"] = 1;
                hashValidate["txtEmail"] = 1;
            }
            break;
        case 'SaveSearch': {
            SetDisplay('divPromptSaveSearch', 'block');
            if (_search != undefined && _search.SearchID != null)
            {
                    SetDisplay('divSaveExistingSearchCriteria', 'block');

                    $(_txtExistingSavedSearchName).value = unescape(_search.SearchName);
                    $(_txtSearch_SaveAs).value = "";
                    hashValidate[_txtExistingSavedSearchName] = 1;
                    hashValidate[_txtSearch_SaveAs] = 1;
                }
            else
            {
                    SetDisplay('divSaveNewSearch', 'block');
                    hashValidate[_txtNewSavedSearch] = 1;
                }
                display = 1;
            }
            break;
    }

    return display;
}

function HidePromptRegistrationActionFields() {

    SetDisplay(_divPromptRegistrationAction, 'none');
    SetDisplay(_wireframe_blackout, 'none');
    SetDisplay('divName', 'none');
    SetDisplay('divPhone', 'none');
    SetDisplay('divTimeToCall', 'none');
    SetDisplay('divAddress', 'none');
    SetDisplay('divDateTimes', 'none');
    SetDisplay('divCommunicationPreference', 'none');
    SetDisplay('divQuestion', 'none');
    SetDisplay('divAddANote', 'none');

    SetDisplay('divPromptSaveSearch', 'none');
    SetDisplay('divSaveExistingSearchCriteria', 'none');
    SetDisplay('divSaveNewSearch', 'none');

    //enable submit button & cancel button
    document.getElementById('btnOK').disabled = false;
    SetDisplay('btnCancel', 'block');

    hashValidate["txtFirstName"] = 0;
    hashValidate["txtLastName"] = 0;
    hashValidate["txtEmail"] = 0;
    hashValidate["txtDayPhone"] = 0;
    //    hashValidate["txtEveningPhone"] = 0;
    hashValidate["txtStreetAddress"] = 0;
    hashValidate["txtCity"] = 0;
    hashValidate["txtState"] = 0;
    hashValidate["txtZip"] = 0;
    hashValidate["radioAddressType"] = 0;
    hashValidate["txtScheduleAShowingPreferredDate"] = 0;
    hashValidate["optDayTime"] = 0;
    hashValidate["txtAreaQuestion"] = 0;
    hashValidate["divAddANote"] = 0;
    hashValidate["txtAreaAddANote"] = 0;
    hashValidate["divCommunicationPreference"] = 0;
    hashValidate["divNewSavedSearch"] = 0;

}

function IsShowListingCategoryAction( action )
{
    return !IsNullOrEmpty(action) && (action.toString().substring(0,"ShowListingCategory".length) == "ShowListingCategory");
}

function GetApplicationFeatureDescription(document, action) {
    var id_Trace = null;
    if (action == 'ListingDetailView' || IsShowListingCategoryAction(action) ) {
        id_Trace = this.location.pathname + '|' + action;
    }
    else {
        var currElement = document.activeElement;
        if ((typeof currElement.pathname !== 'undefined') && (currElement.pathname !== null)) {
            var jsFunctionName = currElement.pathname.split('(')[0];
            id_Trace = currElement.id;
            var isIMG = currElement.innerHTML.search(/IMG /i) > 0 ? 'IMG' : '';

            while (currElement.parentElement != null) {
                currElement = currElement.parentElement;
                var currElementId = currElement.id;

                currElementId = currElementId.replace(/\d+/, '');

                if (!IsNullOrEmpty(currElementId)) {
                    if ((id_Trace.length +
                        6 + // 6 extra characters 3 for IMG and 3 extra |
                        currElementId.length +
                        this.location.pathname.length +
                        jsFunctionName.length +
                        action.length) <= 100) {
                        id_Trace = currElementId + '|' + id_Trace;
                    }
                    else {
                        break;
                    }
                }
            }
            id_Trace = this.location.pathname.substring(1, this.location.pathname.length) + '|' + id_Trace + jsFunctionName + '|' + isIMG + '|' + action;
        }
    }

    //alert(id_Trace.length + id_Trace);
    return id_Trace;
}


//http://msdn.microsoft.com/en-us/library/bb310952.aspx
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

