/*
place the following line in the header of the page that you want to include this file in
<script src="/jscript/shared.js" type="text/javascript"></script>
*/
var _mapSearchUrl = "/mapsearch/mapsearch/mapsearch.aspx";
var _mappingUrl = _mapSearchUrl;
var _searchResultUrl = _mapSearchUrl;
var _freeSearchResultUrl = _mapSearchUrl;


function showUpgradePop(e) {
    //Shows the Upgrade div
    //MUST be called using onClick and passing event eg: onClick="showUpgradePop(event)"
    //Must call the ASP sub writeUpgradePopupDiv() located in execlib.inc
    var objUpgradePop = document.getElementById("GuestMemberPop");
    if (objUpgradePop != null) {
        objUpgradePop.style.display = "block";
        var objMouseXY = new mouseGetCoords(e);
        var newX = objMouseXY.x - 100;
        var newY = objMouseXY.y - 100;
        if (newX < 0) newX = 0;
        if (newY < 0) newY = 0;
        objUpgradePop.style.top = newY + 'px';
        objUpgradePop.style.left = newX + 'px';
    }
}

function hideUpgradePop() {
    var objUpgradePop = document.getElementById("GuestMemberPop");
    if (objUpgradePop != null) {
        objUpgradePop.style.display = "none";
    }
}

function mouseGetCoords(event) {
    if (typeof event.pageX == "undefined") {
        //IE BS
        x = event.clientX + document.documentElement.scrollLeft;
        y = event.clientY + document.documentElement.scrollTop;
    } else {
        //compliant browsers
        x = event.pageX;
        y = event.pageY;
    }
    this.x = x;
    this.y = y;
}

function openSampleEmailWindow(sampleEmailURL) {
    openCustomWindow(sampleEmailURL, 'sampleEmailURL', 630, 700, 0, 0, false, true, 0);

}

function loadHitboxManually() {
    return appendJSSource('/jscript/hbx.js', '__X()');
}

function appendJSSource(strFilePath, strFunctionCall) {
    //loads a javascript file into the header and makes the passed function call when loaded
    if (strFilePath == null || strFilePath == '') {
        //no file path passed, return so as not to cause problems.
        return false;
    }
    if (document.createElement && document.getElementsByTagName) {
        var head = document.getElementsByTagName('head')[0];

        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', strFilePath);

        head.appendChild(script);
        if (strFunctionCall == null || strFunctionCall == "") {
            // no function call was passed so confirmation that file was loaded is impossible
            return false;
        } else {
            strFunctionCall = new String(strFunctionCall);
            rExp = /\"/gi;
            strFunctionCall = strFunctionCall.replace(rExp, '\\"');
            return appendJSSourceComplete(strFunctionCall, 0);
        }
    } else {
        return false;
    }
}

function appendJSSourceComplete(strFunctionCall, i) {
    //runs a function located in the JS file that was loaded by appendJSSource();
    strFunctionName = new String(strFunctionCall);
    strFunctionName = strFunctionName.substr(0, strFunctionName.indexOf('('));
    //recursive function that checks for the function name passed
    if (eval("typeof " + strFunctionName) == 'function') {
        eval(strFunctionCall);
        return true;
    } else {
        i++;
        if (i > 20) {
            //infinite loop guard times out after 10 seconds of waiting : either source was not laoded or the function was not found
            return false;
        } else {
            setTimeout('appendJSSourceComplete("' + strFunctionCall + '" ,' + i + ')', 500);
        }
    }
}
function openMappingPageSearch(strMapCriteriaType, strMapCriteriaValue, strHexCode, iCompanyPk, strHitboxName) {
    openMappingPage('', strMapCriteriaType, strMapCriteriaValue, strHexCode, iCompanyPk, strHitboxName, false);
}

function openMappingPagePropId(piPropertyID, psHexCode, piCompanyPK, psHitboxName) {
    g_fnOpenMappingByPropertyID(piPropertyID, '', '', psHexCode, piCompanyPK, psHitboxName, false);
}

function openMappingPagePropIdComp(propId, strHexCode, iCompanyPk, strHitboxName) {
    openMappingPage(propId, '', '', strHexCode, iCompanyPk, strHitboxName, true);
}

function g_fnOpenMappingByPropertyID(piPropertyID, lsMapCriteriaType, lsMapCriteriaValue, psHexCode, piCompanyPK, psHitboxName, pbComp) {

    //used to open the mapping page
    _hbLink(psHitboxName, 'right', '0,0,30,30');

    var lsMappingURL = _mappingUrl + '?propid=' + piPropertyID + '&code=' + psHexCode + '&ms=r&cobrandPK=' + piCompanyPK;

    if (piPropertyID != null && piPropertyID != "") {
        // Clear out cookie value
        fnClearSearchRequestCookieValue();

        window.location.href = lsMappingURL;
    }

}

function openMappingPage(propId, strMapCriteriaType, strMapCriteriaValue, strHexCode, iCompanyPk, strHitboxName, bComp) {
    //used to open the mapping page
    _hbLink(strHitboxName, 'right', '0,0,30,30');
    mappingURL = _mappingUrl + '?';
    if (bComp)
        mappingURL = '/Mapping/Mapping/mapCompVE.aspx?';
    if (propId != null && propId != '') {
        //property ID specific
        mappingURL = mappingURL + 'propid=' + propId + '&code=' + strHexCode + '&ms=r&cobrandPK=' + iCompanyPk;
    } else {
        //search criteria specific
        mappingURL = mappingURL + 'criteriaType=' + strMapCriteriaType + '&criteriaValue=' + strMapCriteriaValue + '&code=' + strHexCode + '&ms=r&cobrandPK=' + iCompanyPk;
    }
    child = window.open(mappingURL);
    if (navigator.userAgent.indexOf("Firefox") == -1) {
        //hack to fix some strange problem with window.open not working with windows live properly 
        //this hack was causing errors in FF2. Now disabled when firefox detected.
        setTimeout("child.window.location.reload()", 1000);
    }

}

function refreshTopBan() {
    //used to refresh the b@nner in the top of the page (funky spelling and abreviations used to defeat keyword searches)
    ban = document.getElementById("wrap-topBanFrame");
    if (ban != null)
        ban.src = "/pub/ban" + "ner.asp?iBan" + "nerType=1";
}

function refreshRightBan() {
    //used to refresh the b@nner on the right side of the page (funky spelling and abreviations used to defeat keyword searches)
    ban = document.getElementById("wrap-rightBanFrame");
    if (ban != null)
        ban.src = "/pub/ban" + "ner.asp?iBan" + "nerType=2";
}

function openGovCodes() {
    url = "/education/gov_discolsure_codes.html";
    openCustomWindow(url, 'GOVCodes', 660, 410, 0, 0, false, true, 0);
}

function openFSBOOpenHouse(situsId) {
    url = "/FSBO/OpenHouse.aspx?situsID=" + situsId;
    openCustomWindow(url, 'FSBOContactOwner', 710, 500, 0, 0, false, true, 0);
}

function openFSBOContactOwner(situsId) {
    url = "/FSBO/ContactOwner.aspx?situsID=" + situsId;
    openCustomWindow(url, 'FSBOContactOwner', 830, 710, 0, 0, false, true, 0);
}

function openFSBOFlyer(situsId) {
    url = "/FSBO/FSBOFlyerReport.aspx?situsID=" + situsId;
    openCustomWindow(url, 'FSBOContactOwner', 830, 830, 0, 0, false, true, 0);
}

function openFSBOShowing(situsId) {
    url = "/FSBO/RequestShowing.aspx?situsID=" + situsId;
    openCustomWindow(url, 'FSBOContactOwner', 830, 830, 0, 0, false, true, 0);
}

function openMapWindow(propAddress) {
    url = "http://maps.google.com/maps?q=" + propAddress;
    openCustomWindow(url, 'AddressMap', 0, 0, 0, 0, false, true, .75);
}


function varIsEmpty(testVar) {
    if (testVar == null) return true;
    if (isNaN(testVar) && testVar == '') return true;
    return false;
}

function getCSSAttribute(cssClassName, toChange) {
    //retrieves the value of a CSS class attribute
    if (!document.styleSheets) {
        window.alert("Your browser won't support the changing of a style sheet by javascript!");
        return false;
    }
    for (i = 0; document.styleSheets.length > i; i++) {
        //Mozilla
        if (document.styleSheets[i].rules != null) {
            for (j = 0; document.styleSheets[i].rules.length > j; j++) {
                if (document.styleSheets[i].rules[j].selectorText != null) {
                    if (document.styleSheets[i].rules[j].selectorText.toLowerCase() == cssClassName) {
                        return document.styleSheets[i].rules[j].style[toChange];
                    }
                }
            }
        } else if (!varIsEmpty(document.styleSheets[i].cssRules)) {
            //IE
            for (j = 0; document.styleSheets[i].cssRules.length > j; j++) {
                if (document.styleSheets[i].cssRules[j].selectorText != null) {
                    if (document.styleSheets[i].cssRules[j].selectorText.toLowerCase() == cssClassName) {
                        return document.styleSheets[i].cssRules[j].style[toChange];
                    }
                }
            }
        }
    }
}

function changeCSSAttribute(cssClassName, toChange, changeTo) {
    //changes the value of a CSS class attribute
    if (!document.styleSheets) {
        return false;
    }
    for (i = 0; document.styleSheets.length > i; i++) {
        //Mozilla
        if (document.styleSheets[i].rules != null) {
            for (j = 0; document.styleSheets[i].rules.length > j; j++) {
                if (document.styleSheets[i].rules[j].selectorText != null) {
                    if (document.styleSheets[i].rules[j].selectorText.toLowerCase() == cssClassName) {
                        document.styleSheets[i].rules[j].style[toChange] = changeTo;
                    }
                }
            }
        } else if (document.styleSheets[i].cssRules != null) {
            //IE
            for (j = 0; document.styleSheets[i].cssRules.length > j; j++) {
                if (document.styleSheets[i].cssRules[j].selectorText != null) {
                    if (document.styleSheets[i].cssRules[j].selectorText.toLowerCase() == cssClassName) {
                        document.styleSheets[i].cssRules[j].style[toChange] = changeTo;
                    }
                }
            }
        } else {
            window.alert("Your browser won't support the changing of a style sheet by javascript!");
            return false;
        }
    }
}

function openNewFeaturesWindow() {
    //shows the new features for the 2005 wrap & price change
    openCustomWindow('/pub/popup_2005_features.html', '2005Features', 820, 720, 0, 0, false, true);
}

function openBBBWindow() {
    /*
    used for opening the Better Business Bureau info on realtytrac
    */
    openCustomWindow('http://www.labbb.org/bbbweb/forms/business/companyreportpage_expository.aspx?companyid=13159967', 'BBB', 777, 345, 0, 0, false, true);
}

function openSurveyWindow() {
    /*
    used for opening the customer survey popup
    */
    openCustomWindow('/pub/pop-up-survey-winners.asp', 'upgradePopup', 830, 500, 0, 0, false, true);
}

function openAVMupgradeWindow(propId) {
    /*
    centralized function to open property lien records window
    */
    openCustomWindow('/database/upgradeAVMpopup.html?propId=' + propId, 'avmUpgrade', 750, 750, 0, 0, false, true);
}

function openLienBankUpgradeWindow(propId, buyLien, buyBank) {
    /*
    centralized function to open property lien records window
    */
    openCustomWindow('/database/upgradeLiensPopup.html?propId=' + propId + '&buyLien=' + buyLien + '&buyBank=' + buyBank, 'avmUpgrade', 750, 750, 0, 0, false, true);
}

function openFieldNamesWindow(loc) {
    /*
    centralized function to open property lien records window
    */
    openCustomWindow('/education/fieldNames.html#' + loc, 'propFieldNames', 470, 80, 125, 100, false, true);
}

function openPropLienWindow(propId) {
    /*
    centralized function to open property lien records window
    */
    openCustomWindow('/database/propLien.asp?propId=' + propId, 'propTypeCodes', 470, 440, 125, 100, false, true);
}

function openPropBankruptcyWindow(propId) {
    /*
    centralized function to open property bankruptcy records window
    */
    openCustomWindow('/database/propBankruptcy.asp?propId=' + propId, 'propTypeCodes', 470, 495, 125, 100, false, true);
}

function openPropTypeCodesWindow() {
    /*
    centralized function to open property codes definitions window
    */
    openCustomWindow('/pub/propTypeCodes.html', 'propTypeCodes', 750, 550, 125, 100, false, true);
}

function openSampleReportWindow(url) {
    /*
    centralized function to open samel xml reports window
    */
    openCustomWindow(url, 'sampleReport', 790, 550, 125, 100, false, true);
}

function openTermsOfUseWindow() {
    /*
    centralized function to open terms of use help window
    */
    openCustomWindow('/pub/terms.html', 'termsOfUse', 820, 550, 125, 100, false, true);
}

function openFeedbackWindow(userId) {
    //openCustomWindow('http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/doc_serve.php?&5=12&userid=' + userId, 'Feedback', 630, 640, 125, 100, false, false);
    var child = window.open("http://www.surveygizmo.com/s3/560876/RealtyTrac-Feedback", "Feedback", "width=950,height=680,scrollbars=yes,toolbar=no,status=no,resizable=yes,top=0,left=0");
    child.window.focus();
}

function openHelpWindow(location) {
    /*
    centralized function to open a help window
    paramter : location : specifies the location for the help section
    possible values:
    chat, answer, ask
    */
    var locationSpecificUrl = '';
    switch (location) {
        case 'chat':
            locationSpecificUrl = 'http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/live.php';
            break;
        case 'answer':
            locationSpecificUrl = 'http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/std_alp.php';
            break;
        case 'ask':
            locationSpecificUrl = 'http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/ask.php';
            break;
        default:
            if (location == parseInt(location) && location > 0) {
                locationSpecificUrl = 'http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/std_adp.php?p_faqid=' + location;
            }
            else {
                locationSpecificUrl = 'http://custhelp.realtytrac.com/Scripts/rightnow.cfg/php.exe/enduser/std_alp.php';
            }
    }
    openCustomWindow(locationSpecificUrl, 'SupportCenter', 850, 550, 125, 100, true, true);
}

function openFAQwindow(url) {
    /*
    centralized function to open faq window
    */
    openCustomWindow(url, 'faq', 500, 550, 125, 100, false, true);
}

function openWideFAQwindow(url) {
    /*
    centralized function to open faq window
    */
    openCustomWindow(url, 'faq', 820, 550, 125, 100, false, true);
}


function autoTab(input, len) {
    /************************************************
    DESCRIPTION: Automatically jumps the focus to the next field  
    in the tab sequence when a specified number of character is entered.  

PARAMETERS: 
    input - Text INPUT field to be tested.  
    len   - length of input before autotabbing.

  To use, include the following code as an inline event handler
    in an INPUT text field:
    onKeyUp="return autoTab(this, n);"  
    where n is a number specifying len. 
    
    RETURNS: 
    True if tab is made.

*************************************************/
    if (input.value.length >= len) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input) + 1) % input.form.length].focus();
    }

    function getIndex(input) {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
            if (input.form[i] == input) index = i;
        else i++;
        return index;
    }
    return true;
}

function promptLink(message, valueName, defaultValue, link) {
    /*
    used to show a prompt box before proceeding.
    the value entered is passed to the link as the valueName
    used on:
    /database/util/userResults.asp
    */

    value = (prompt(message, defaultValue));
    changeWindowLocation(link + '&' + valueName + '=' + value, "");
}

function confirmLink(message, link, link2, successAction) {
    /*
    used to show a confirmation box before proceeding.
    if users hits cancel and link2 is empty, nothing happens
    used on:
    /database/util/userResults.asp
    */

    if (confirm(message)) {
        if (successAction != null && successAction != '') {
            //execute passed action before redirect
            eval(successAction);
        }
        changeWindowLocation(link, "");
    }
    else if (link2 != '' && link2 != null) {
        changeWindowLocation(link2, "");
    }
}


bName = navigator.appName;

function prepareUrl(url) {
    //makes URL point to a non-secure page if no https is specified
    newUrl = String(url);
    newUrl.toLowerCase();
    if ((newUrl.indexOf('http') == -1) && (newUrl.indexOf('javascript') == -1) && (newUrl.indexOf('/util/') == -1) && (newUrl.indexOf('/') == 0)) {
        //make suret: url isn't fully qualified           not a javascript link               not in the admin panel              not a relative URL
        domain = String(document.domain);
        domain.toLowerCase();
        //put www in front of realtytrac.com domain name so that
        if (domain == 'realtytrac.com') domain = 'www.realtytrac.com';
        newUrl = 'http://' + domain + '/' + url;
    } else {
        //return url unmolested
        return url;
    }
    //return new url with domain
    return newUrl;
}

function changeWindowLocation(url, hitboxTrackingName) {
    if (hitboxTrackingName != '') _hbLink(hitboxTrackingName, 'right', '0,0,30,30');
    window.location.href = prepareUrl(url);
}

function openCustomWindow(url, name, width, height, leftPos, topPos, toolbars, scrollbars, windowRatio) {
    //function used for opening a window, uses passed parameters
    //name is the name of the window
    //toolbars and scrollbars are boolean fields that determine whether those should be shown on window
    //if a windowRatio is passes (and it is between 0 and 1) then the window will be sized as a percentage of the screen size (resolution)

    toolbarTxt = "toolbar=no,status=no";
    if (toolbars) {
        toolbarTxt = "toolbar=yes,status=yes";
    }
    scrollbarTxt = "scrollbars=no,resizable=yes";
    if (scrollbars) {
        scrollbarTxt = "scrollbars=yes,resizable=yes";
    }
    if (!isNaN(windowRatio) && windowRatio < 1 && windowRatio > 0) {
        width = screen.width * windowRatio;
        height = screen.height * windowRatio;
        leftPos = (screen.width - width) / 2;
        topPos = 20;
    }
    leftPosTxt = '';
    topPosTxt = '';
    if (!isNaN(leftPos) && !isNaN(topPos)) {
        if (bName != 'Netscape') {
            leftPos = leftPos + 10;
            topPos = topPos + 10;
        }
        topPosTxt = 'top=' + topPos;
        leftPosTxt = 'left=' + leftPos;
    }
    windowSpecs = topPosTxt + ',' + leftPosTxt + ',width=' + width + ',height=' + height + ',' + scrollbarTxt + ',' + toolbarTxt;
    child = window.open(prepareUrl(url), name, windowSpecs);
    child.window.focus();
}

function openPostcard(propID, reload) {
    openCustomWindow('/database/noframes/postcard_selection.asp?propId=' + propID + '&reload=' + reload, 'PrintPostcard', 585, 700, '', '', false, true);
}
function openExamine(propId, webSitePk, queryStr) {
    if (webSitePk == null) webSitePk = 1;
    if (queryStr == null) queryStr = '';
    openCustomWindow('/database/noframes/examineSave.asp?pageTo=examineComps.asp&propId=' + propId + '&webSitePk=' + webSitePk + queryStr, 'xamine', 800, 725, '-10', '-10', false, false);
}

tab = 1;
function setTabIndex(id) {
    eval('document.frm.' + id + '.tabIndex = ' + tab++);
}

function DropDownSelect(p_cntrlname, p_value) {
    //selects a option in a Select control by control name and option value.
    // ES 10/24/05
    var len;
    len = document.getElementById(p_cntrlname).options.length;
    for (var i = 0; i < len - 1; i++) {
        if (document.getElementById(p_cntrlname).options[i].value == p_value) {
            document.getElementById(p_cntrlname).options.selectedIndex = i;
        }
    }
}

// used by member and non-member quick search.
function fnVerifyState(pbValidUser, poForm, psHBlink, psSearchType) {

    //Depreciated pbValidUser
    //pbValidUser = 0;

    var lsSearchFieldValue = fnTrim(poForm.txtQuickSearch.value.replace(",", ""));
    var lsAllStates = "Alabama|AL~Alaska|AK~Arizona|AZ~Arkansas|AR~California|CA~Colorado|CO~Connecticut|CT~Delaware|DE~District of Columbia|DC~Florida|FL~Georgia|GA~Hawaii|HI~Idaho|ID~Illinois|IL~Indiana|IN~Iowa|IA~Kansas|KS~Kentucky|KY~Louisiana|LA~Maine|ME~Maryland|MD~Massachusetts|MA~Michigan|MI~Minnesota|MN~Mississippi|MS~Missouri|MO~Montana|MT~Nebraska|NE~Nevada|NV~New Hampshire|NH~New Jersey|NJ~New Mexico|NM~New York|NY~North Carolina|NC~North Dakota|ND~Ohio|OH~Oklahoma|OK~Oregon|OR~Pennsylvania|PA~Rhode Island|RI~South Carolina|SC~South Dakota|SD~Tennessee|TN~Texas|TX~Utah|UT~Vermont|VT~Virginia|VA~Washington|WA~West Virginia|WV~Wisconsin|WI~Wyoming|WY";
    lsAllStates = lsAllStates.toLowerCase();
    lsSearchFieldValue = lsSearchFieldValue.toLowerCase();
    var laStates = lsAllStates.split("~");
    var laSearch = lsSearchFieldValue.split(' ');
    var lsReturn = "";
    var lreSearchField = /west virginia/gi;
    var lbWestVirginiaFlag = lreSearchField.test(lsSearchFieldValue);
    var lsSearchURL = '';

    if (lsSearchFieldValue == "") { alert(fnErrorNoCityOrState("You must enter a City and a State to search!")); return false; }

    if (isNaN(lsSearchFieldValue)) {//NON ZIPCODE SEARCH
        //	[ Check for one word ] [ below statement looking for the exeption of west virginia]
        if ((laSearch.length == 1) || ((laSearch.length == 2) && (lsSearchFieldValue == "west virginia"))) { alert(fnErrorNoCityOrState("You must enter both city and state!")); return false; }

        for (i = 1; i <= laStates.length; i++) {
            var laPart = laStates[i].split("|");
            var liStartOfState = laPart[0].split(" ").length;
            var liLoopCount = laSearch.length - liStartOfState;

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //	EXEPTION - "west virginia"
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (lbWestVirginiaFlag) {
                for (j = 0; j <= laSearch.length - 3; j++) {
                    lsReturn = lsReturn + " " + laSearch[j];
                }

                if (psSearchType != null) {
                    lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=wv" + "&selStatus=" + psSearchType;
                }
                else {
                    lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=wv";
                }

                // Clear out cookie value
                fnClearSearchRequestCookieValue();

                changeWindowLocation(lsSearchURL, psHBlink);

                return false;
            }

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //	FULL STATE-MULTIPLE
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if ((lsSearchFieldValue.search(laPart[0]) >= 0) && (laSearch[laSearch.length - 1].length != 2)) {
                if (liStartOfState == laSearch.length) {//USER ONLY ENTERED A STATE
                    alert(fnErrorNoCityOrState("Please enter a city along with the state"));
                    return false;
                } else {

                    for (j = 0; j <= liLoopCount - liStartOfState; j++) {
                        lsReturn = lsReturn + " " + laSearch[j];
                    }

                    if (psSearchType != null) {
                        lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=" + laPart[1] + "&selStatus=" + psSearchType;
                    }
                    else {
                        lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=" + laPart[1];
                    }

                    // Clear out cookie value
                    fnClearSearchRequestCookieValue();

                    changeWindowLocation(lsSearchURL, psHBlink);

                    return false;
                }
            }

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //	STATE ABBREVIATION
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if ((laSearch[laSearch.length - 1].search(laPart[1]) >= 0) && (laSearch[laSearch.length - 1].length == 2)) {
                for (k = 0; k <= laSearch.length - 2; k++) {
                    lsReturn = lsReturn + " " + laSearch[k];
                }

                if (psSearchType != null) {
                    lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=" + laPart[1] + "&selStatus=" + psSearchType;
                }
                else {
                    lsSearchURL = _freeSearchResultUrl + "?searchType=city&txtCity=" + lsReturn + "&txtCity=" + laPart[1];
                }

                // Clear out cookie value
                fnClearSearchRequestCookieValue();

                changeWindowLocation(lsSearchURL, psHBlink);

                return false;
            }

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            //	NO STATE MATCH
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (i == laStates.length) {
                alert(fnErrorValidState());
                return false;
            }
        }

    } else {
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //	ZIP CODE SEARCH
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        if (psSearchType != null) {
            lsSearchURL = _freeSearchResultUrl + "?searchType=zip&txtZip=" + lsSearchFieldValue + "&selStatus=" + psSearchType;
        }
        else {
            lsSearchURL = _freeSearchResultUrl + "?searchType=zip&txtZip=" + lsSearchFieldValue;
        }

        // Clear out cookie value
        fnClearSearchRequestCookieValue();

        changeWindowLocation(lsSearchURL, psHBlink);

        return false;
    }
    return false;
} //end function 

//Used by member quick search bar
function fnViewSavedSearch(poForm) {
    var element = document.getElementById("cboSavedSearch");

    if (element && element.value != 0) {
        if (typeof (g_SearchEngine) != "undefined" && g_SearchEngine != null) {
            g_SearchEngine.RestoreSearch(element.value);
        }
        else {
            try {
                changeWindowLocation(_searchResultUrl + "?prefId=" + element.value, "headerQuickSearchBar_savedSearch");

            }
            catch (e) { }
        }
    }
}

// used by member and non-member quick search.
function fnTrim(psCleanup) {
    while (psCleanup.substring(0, 1) == ' ') {
        psCleanup = psCleanup.substring(1, psCleanup.length);
    }
    while (psCleanup.substring(psCleanup.length - 1, psCleanup.length) == ' ') {
        psCleanup = psCleanup.substring(0, psCleanup.length - 1);
    }
    psCleanup.replace(/^\s*|\s*$/g, "");
    return psCleanup;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	PopUnder functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Client Side Cookie Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function fnSetCookie(psName, psValue, piExpires, psPath, psDomain, psSecure) {
    var ldToday = new Date();
    ldToday.setTime(ldToday.getTime());

    //piExpires = Days
    if (piExpires) { piExpires = piExpires * 1000 * 60 * 60 * 24; }
    var ldExpiresDate = new Date(ldToday.getTime() + (piExpires));

    document.cookie = psName + "=" + escape(psValue) +
					((piExpires) ? ";expires=" + ldExpiresDate.toGMTString() : "") +
					((psPath) ? ";path=" + psPath : "") +
					((psDomain) ? ";domain=" + psDomain : "") +
					((psSecure) ? ";secure" : "");

}

function fnGetCookie(psName) {
    var liStart = document.cookie.indexOf(psName + "=");
    var liLen = liStart + psName.length + 1;

    if ((!liStart) && (psName != document.cookie.substring(0, psName.length))) { return null; }
    if (liStart == -1) { return null; }
    var liEnd = document.cookie.indexOf(";", liLen);
    if (liEnd == -1) {
        liEnd = document.cookie.length;
    }
    return unescape(document.cookie.substring(liLen, liEnd));
}

function fnDeleteCookie(psName, psPath, psDomain) {
    if (fnGetCookie(psName)) {
        document.cookie = psName + "=" +
		((psPath) ? ";path=" + psPath : "") +
		((psDomain) ? ";domain=" + psDomain : "") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function fnLoginBox(poFillElement) {
    loElement = document.getElementById(poFillElement);
    if (loElement.style.display == "block") {
        loElement.style.display = "none";
    }
    else {
        loElement.style.display = "block";
        window.setTimeout("fnFillLogin('frm_UserName')", 200);
    }
}

function fnFillLogin(poFocusElement) {
    var loUserName = document.getElementById('frm_UserName');
    var loPassword = document.getElementById('frm_Password');
    var loRemember = document.getElementById('frm_RememberLogin');

    if (fnGetCookie("RememberUN") != null) {
        loUserName.value = fnGetCookie('RememberUN');
        loPassword.focus();
    }
    else {
        loUserName.value = "";
        loUserName.focus();
    }

    loRemember.checked = (fnGetCookie("RememberLogin") == 0) ? false : true;
    loPassword.value = "";
}

function fnSearchSubmit(poForm) {
    var loZip = poForm.searchFormZip;
    var loZipcode = poForm.zipcode;
    var loCity = poForm.searchFormCity;
    var loState = poForm.searchFormState;

    if (fnTrim(loZip.value) != '' && !isNaN(loZip.value)) {
        loZipcode.value = loZip.value;
        loCity.value = '';
        loState.value = '';
    }
    else if (fnTrim(loCity.value) != '' && fnTrim(loState.value) == '') {
        alert(fnErrorNoState());
        return false;
    }
    else if (fnTrim(loCity.value) == '' && fnTrim(loState.value) != '') {
        alert(fnErrorNoCity());
        return false;
    }
    else if (fnTrim(loCity.value) != '' && fnTrim(loState.value) != '') {
        loZipcode.value = loCity.value + ', ' + loState.value;
        loZip.value = '';
    }
    else {
        alert(fnErrorMissingVariables());
        return false;
    }

    // Clear out cookie value
    fnClearSearchRequestCookieValue();

    _hbLink('homeSearch', 'right', '0,0,30,30');
    return true;
}

function fnEnterSubmit(psSubmit, psEvent) {
    // check if the key hit is "return," submit via the submit function if it is
    // Usage: pass the name of the button (poSubmit) and an event (psEvent, usually event) when calling this script
    var liCharacter;

    liCharacter = (psEvent && psEvent.which) ? psEvent.which : ((psEvent) ? psEvent.keyCode : null); //determine whether to use the Netscape or IE key character

    if (liCharacter == 13 || psEvent == "enter")	// if the user hits return or clicks the button
    {
        fnActivate(psSubmit);
    }
}

function fnActivate(psSubmit) {
    // pass the id of the button (psSubmit) when calling this script
    if (psSubmit == 'GO') {
        g_fnHeaderLoginGet('frm_UserName, frm_Password', '/pub/login.asp?checkLogin=true&sessionTestSet=true');
    } else if (psSubmit == 'SearchNMList') {
        g_fnValidateSearchSubmit('SearchList');
    } else if (psSubmit == 'SearchMList') {
        g_fnValidateSearchSubmit('SearchList', '', '', '', '', '', '', '', '', '', _searchResultUrl);
    }
}

function g_fnHeaderLoginGet(paElementIDs, psDestination) {
    // submit the login and check for existing cookies
    var loUserName = document.getElementById('frm_UserName');
    var loPassword = document.getElementById('frm_Password');
    var loRemember = document.getElementById('frm_RememberLogin');
    var lsErrorMessage = "";

    if (!loUserName.value || !loPassword.value) {
        loUserName.focus();
        alert(fnErrorNoLoginInfo());
        return false;
    }

    if (loRemember && loRemember.checked == true) {
        //IE 6 is blocking cookies: no good way around this 06.2007 BGM
        fnSetCookie("RememberUN", loUserName.value, 365, "/", "", ""); //UserName value
        fnSetCookie("RememberLogin", 1, 365, "/", "", "");
    } else {
        fnDeleteCookie("RememberUN", "/", "");
        fnSetCookie("RememberLogin", 0, 365, "/", "", "");
    }

    fnForm(paElementIDs, psDestination, "&");

    _hbLink('header_login_go', 'right', '0,0,30,30');
    return true;
}

function fnForm(paElementIDs, psDestination, psVariableInitialAdditionOverRide, psVariables) {
    // paElementNames are the id's of all elements to be submitted, psDestination is the destination the elements are being submitted to.
    var laElementIDs = paElementIDs.split(", "); // put the Elements into an array called laElementIDs
    var loElementID; 			// used in the loop for the specific element
    var lsVariableInitialAddition = (psVariableInitialAdditionOverRide) ? psVariableInitialAdditionOverRide : "?";
    var lsVariables = (psVariables != null) ? psVariables : ""; // the variables to be listed in the destination URL

    if (paElementIDs) {
        for (var x = 0; x < laElementIDs.length; x++) {
            //cycle through the elements
            var loElementID = document.getElementById(laElementIDs[x]);
            if (x != 0) { lsVariables += "&"; } // check if it's the first addition of a variable: if it's not add an &
            lsVariables += loElementID.name + "=" + loElementID.value; // add on the variable		
        }
    }

    if (lsVariables.toLowerCase().match("password") != null) {
        document.getElementById('ifLogin').src = psDestination + lsVariableInitialAddition + lsVariables;
    }
    else {
        document.location.href = psDestination + lsVariableInitialAddition + lsVariables; // add on the variable to the end of the destination
    }

}

function g_fnClearFormField(psFieldIdToClear, psColor) {
    var lsFieldIdToClear = document.getElementById(psFieldIdToClear);

    lsFieldIdToClear.value = '';
    lsFieldIdToClear.style.color = (undefined != psColor && psColor != '') ? psColor : '#000';
}

function g_fnValidateSearchSubmit(psButtonClicked, psFormName, psFormFieldName_City, psFormFieldName_State, psFormFieldName_Zip, psFormFieldName_SearchCriteria, psFormFieldDefaultValue_City, psFormFieldDefaultValue_Zip, psViewMapButtonName, piIsForm, psURLDestination, psTemplate) {
    // initialize and set values
    var lsFormFieldCityName = (psFormFieldName_City) ? fnTrim(psFormFieldName_City) : 'frm_City';
    var lsFormFieldStateName = (psFormFieldName_State) ? fnTrim(psFormFieldName_State) : 'frm_State';
    var lsFormFieldZipName = (psFormFieldName_Zip) ? fnTrim(psFormFieldName_Zip) : 'frm_Zip';
    var lsFormFieldCityValueDefaultValue = (psFormFieldDefaultValue_City) ? fnTrim(psFormFieldDefaultValue_City) : 'Enter City';
    var lsFormFieldZipValueDefaultValue = (psFormFieldDefaultValue_Zip) ? fnTrim(psFormFieldDefaultValue_Zip) : 'Enter Zip';
    var lsViewMapButtonName = (psViewMapButtonName) ? fnTrim(psViewMapButtonName) : 'SearchMap';
    var lsFormName = (psFormName) ? fnTrim(psFormName) : 'quickSearchForm';
    var liIsForm = (piIsForm) ? piIsForm : null;
    var lsURLDestination = (psURLDestination) ? psURLDestination : _freeSearchResultUrl;
    var lsButtonToTrack = (psButtonClicked) ? psButtonClicked : null;
    var lsCriteriaValue;
    var lsCriteriaType;
    var lsDefaultButton = 'SearchList';
    var lsTemplate = (psTemplate) ? psTemplate : "MCode";
    var loTemplate = document.getElementById(lsTemplate);
    var lbMember = (psURLDestination) ? 1 : null;
    var lsTemplateComplete;
    var lsErrorMessage = "";
    var loFormFieldCityName = document.getElementById(lsFormFieldCityName);
    var loFormFieldStateName = document.getElementById(lsFormFieldStateName);
    var loFormFieldZipName = document.getElementById(lsFormFieldZipName);
    var lsVariables;

    //Begin Validation
    if ((loFormFieldCityName.value == '' || loFormFieldCityName.value == lsFormFieldCityValueDefaultValue) && loFormFieldStateName.value == '' && (loFormFieldZipName.value == '' || loFormFieldZipName.value == lsFormFieldZipValueDefaultValue)) {
        //No values entered
        lsErrorMessage += "- " + fnErrorNoCity() + "\n";
        lsErrorMessage += "- " + fnErrorNoState() + "\n";
    }
    else if (loFormFieldZipName.value != "" && loFormFieldZipName.value != lsFormFieldZipValueDefaultValue && (loFormFieldZipName.value.length != 5 || isNaN(loFormFieldZipName.value))) {
        //incorrect zip entered
        lsErrorMessage += "- " + fnErrorBadZipCode() + "\n";
    }
    else if (loFormFieldCityName.value != '' && loFormFieldCityName.value != lsFormFieldCityValueDefaultValue && loFormFieldStateName.value == '') {
        //City entered but no state or zip
        lsErrorMessage += "- " + fnErrorNoState() + "\n";
    }
    else if (loFormFieldStateName.value != '' && (loFormFieldCityName.value == lsFormFieldCityValueDefaultValue || loFormFieldCityName.value == '') && (loFormFieldZipName.value == '' || loFormFieldZipName.value == lsFormFieldZipValueDefaultValue)) {
        //State selected but no Zip or City
        lsErrorMessage += "- " + fnErrorNoCity() + "\n";
    }

    if (lsErrorMessage) {
        alert(lsErrorMessage);
    }
    else {
        if (loFormFieldZipName.value != '' && loFormFieldZipName.value != lsFormFieldZipValueDefaultValue) {
            lsVariables = (lbMember) ? 'txtZip=' + loFormFieldZipName.value : "";
            loFormFieldCityName.value = '';
            loFormFieldStateName.value = '';
            lsCriteriaType = 'zip';
            lsCriteriaValue = loFormFieldZipName.value;
        }
        else {
            lsVariables = (lbMember) ? 'txtCity=' + loFormFieldCityName.value + '&txtCity=' + loFormFieldStateName.value : "";
            loFormFieldZipName.value = '';
            lsCriteriaType = 'city';
            lsCriteriaValue = loFormFieldCityName.value + '~' + loFormFieldStateName.value;
        }


        if (psButtonClicked == lsViewMapButtonName) {
            lsTemplateComplete = (lbMember) ? '&code=' + loTemplate.value : "";
            lsVariables = "criteriaType=" + lsCriteriaType + '&criteriaValue=' + lsCriteriaValue + lsTemplateComplete;
            lsURLDestination = _mappingUrl;
        }
        else {
            lsCriteriaValue = lsCriteriaValue.replace('~', ', ');
            lsVariables = (lbMember) ? lsVariables : 'zipcode=' + lsCriteriaValue + "&zipOnly=true";

        }

        // Clear out cookie value
        fnClearSearchRequestCookieValue();

        fnForm('', lsURLDestination, '', lsVariables);

        _hbLink(lsButtonToTrack, 'right', '0,0,30,30');
        return true;
    }
}

/********************************
Error Messages
********************************/

function fnErrorNoState(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please select a state."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;

}

function fnErrorNoCounty(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please select a county."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;

}

function fnErrorNoAddress(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please select an address."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;

}

function fnErrorNoCity(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please enter a city."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoZip(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please enter a zip."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorMissingVariables(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Some search parameters are missing."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorBadZipCode(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please enter a 5-digit numerical zip code."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoCityOrState(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please enter a city and select a state."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoLoginInfo(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please fill in both username and password."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorValidState(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please enter a valid state!"; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoSavedSearch(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "There are no saved searches in this list"; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoSavedSearchName(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "You must give the search a name to save it."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoSavedSearchSelect(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please select a saved search."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorIllegalCharacter(psOverRideMessage, psIllegalCharacter) {
    // returns an error message
    var lsIllegalCharacter = (psIllegalCharacter != undefined) ? psIllegalCharacter : 'a character you typed';
    var lsDefaultMessage = "Use of " + lsIllegalCharacter + " is not supported."; // default error message
    var lsReturn = (psOverRideMessage != '') ? psOverRideMessage : lsDefaultMessage;

    return lsReturn;
}

function fnErrorReturn(psDefaultMessage, psOverRideMessage) {
    var lsReturn = (psOverRideMessage != undefined) ? psOverRideMessage : psDefaultMessage;

    return lsReturn;
}

function fnErrorCatchAll(psErrors) {
    alert('These fields must be entered:\n\n' + psErrors);
}

function fnClearSearchRequestCookieValue() {
    // Clear out cookie value
    fnSetCookie("SearchRequest", "", null, "/", null, null);
}

function fnShowHideFieldDef(mDiv, obj) {
    // Remove any whitespace characters.
    var nDiv = mDiv.replace(/\s/g, '_');

    // position and show.
    var iDiv = document.getElementById(nDiv);

    if (!iDiv) {
        return false;
    }

    var curleft = 0;
    var curtop = 0;
    var curwidth = 0;
    var newWidth = 456;
    // retrieves shadow <div>
    var sDiv = iDiv.lastChild;

    if (obj.offsetParent && obj.offsetWidth) {
        curleft = obj.offsetLeft;
        //curtop = obj.offsetTop;
        curtop = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
        curwidth = obj.offsetWidth;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft;
            //curtop += obj.offsetTop;
        }
        curtop += 60;
        curleft += curwidth + 8;
    }
    else {
        return false;
    }

    iDiv.style.top = curtop + "px";
    iDiv.style.left = curleft + "px";
    newWidth -= curleft;

    if (sDiv.tagName == 'DIV') {
        iDiv.style.width = newWidth + "px";
        sDiv.style.width = newWidth + "px";
    }

    iDiv.style.display = (iDiv.style.display.indexOf("block") < 0) ? "block" : "none";
}

function g_fnStopDoubleSubmit(poForm) {
    try {
        var inputs = poForm.getElementsByTagName("input");

        for (var i = 0; i < inputs.length; i++) {
            var type = inputs[i].getAttribute("type");

            switch (type) {
                case "submit":
                case "image":
                    inputs[i].disabled = true;
                    break;
            }
        }
    }
    catch (e) {
        //no trap
    }
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
        return string;
    }
};


function noSelects(state) {
    var f = document.getElementsByTagName('SELECT');
    for (i = 0; i < f.length; i++) {
        if (state > 0) {
            f[i].style.display = 'none';
        }
        else {
            f[i].style.display = 'inline';
        }
    }
}


///--- This code allows to dinamically add elements and add events to them ---///
var Dom =
{
    get: function(el) {
        if (typeof el === 'string') {
            return document.getElementById(el);
        }
        else {
            return el;
        }
    },

    add: function(el, dest) {
        var el = this.get(el);
        var dest = this.get(dest);
        dest.appendChild(el);
    },

    remove: function(el) {
        var el = this.get(el);
        el.parentNode.removeChild(el);
    }
};

var Event =
{
    add: function() {
        if (window.addEventListener) {
            return function(el, type, fn) {
                Dom.get(el).addEventListener(type, fn, false);
            };
        }
        else if (window.attachEvent) {
            return function(el, type, fn) {
                var f = function() {
                    fn.call(Dom.get(el), window.event);
                };

                Dom.get(el).attachEvent('on' + type, f);
            };
        }
    } ()
};

var _stateTextArray = "Select a State,Alabama,Alaska,Arizona,Arkansas,California,Colorado,Connecticut,Delaware,District of Columbia,Florida,Georgia,Guam,Hawaii,Idaho,Illinois,Indiana,Iowa,Kansas,Kentucky,Louisiana,Maine,Maryland,Massachusetts,Michigan,Minnesota,Mississippi,Missouri,Montana,Nebraska,Nevada,New Hampshire,New Jersey,New Mexico,New York,North Carolina,North Dakota,Ohio,Oklahoma,Oregon,Pennsylvania,Puerto Rico,Rhode Island,South Carolina,South Dakota,Tennessee,Texas,Utah,Vermont,Virgin Islands,Virginia,Washington,West Virginia,Wisconsin,Wyoming,other/not listed";
var _stateValueArray = "NONE,AL,AK,AZ,AR,CA,CO,CT,DE,DC,FL,GA,GU,HI,ID,IL,IN,IA,KS,KY,LA,ME,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,PR,RI,SC,SD,TN,TX,UT,VT,VI,VA,WA,WV,WI,WY,Other";
var _international = false;
var _countryUSA = "UNIT";
var _defaultValue = "";

function g_fnChangeCountry(poElement, psFormName, psStateName, psZipCode, psPhoneParts, psPhone1, psInternationalName, psStateAsterisk, psAgentContact, psPhoneParts2, psPhone2, psCurrencyCalculator) {

    _international = false;

    var lsInternationalName = "International";

    var oldObject = document.getElementById(psStateName);
    //		var zipRequired = document.getElementById(psZipCode + "_astrisk")
    if (_defaultValue == 'NONE') _defaultValue = '';

    var zip = document.getElementById(psZipCode);
    var ZipTemp;

    var phoneParts = typeof (psPhoneParts) != 'undefined' ? document.getElementById(psPhoneParts) : null;
    var phone1 = typeof (psPhone1) != 'undefined' ? document.getElementById(psPhone1) : null;
    var stateAsterisk = typeof (psStateAsterisk) != 'undefined' ? document.getElementById(psStateAsterisk) : null;
    var divAgentContact = typeof (psAgentContact) != 'undefined' ? document.getElementById(psAgentContact) : null;
    var hdnInternational = document.getElementById((typeof (psInternationalName) != 'undefined') && psInternationalName != null ? psInternationalName : lsInternationalName);
    var phoneParts2 = typeof (psPhoneParts2) != 'undefined' ? document.getElementById(psPhoneParts2) : null;
    var phone2 = typeof (psPhone2) != 'undefined' ? document.getElementById(psPhone2) : null;
    var psCurrencyCalculator = typeof (psCurrencyCalculator) != 'undefined' ? document.getElementById(psCurrencyCalculator) : null;



    if (poElement.value != _countryUSA) {
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //	International
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        _international = true;

        // State Dropdown to Textbox  
        var newObject = document.createElement('input');
        newObject.type = 'text';

        newObject.value = _defaultValue;
        if ((oldObject.value != 'NONE') && (oldObject.value.length > 2)) {
            newObject.value = oldObject.value;
        }

        if (oldObject.name) newObject.name = oldObject.name;
        if (oldObject.id) newObject.id = oldObject.id;
        if (oldObject.className) newObject.className = oldObject.className;

        oldObject.parentNode.replaceChild(newObject, oldObject);

        //Phone Parts to FreeForm Textbox

        if (phoneParts && phone1) {
            phoneParts.style.display = "none";
            phone1.style.display = "";
        }

        if (phoneParts2 && phone2) {
            phoneParts2.style.display = "none";
            phone2.style.display = "";
        }

        zip.maxLength = 20;

        //zip.className = "txtPostalCode";


        //			if (zipRequired != null) { zipRequired.style.display = "none"; }

        if (stateAsterisk) {
            stateAsterisk.style.display = 'none';
        }

        if (divAgentContact) {
            divAgentContact.style.display = 'none';
        }

        //Set hidden field  
        if (hdnInternational) {
            hdnInternational.value = 1;
        }

        //CurrencyCalculator
        if (psCurrencyCalculator) {
            psCurrencyCalculator.style.display = "";
        }

    }
    else {
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //	Domestic
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	  
        var newObject = document.createElement('select');
        var stateValue = _stateValueArray.split(",");
        var stateText = _stateTextArray.split(",");

        _defaultValue = (_defaultValue != "") ? _defaultValue : oldObject.value;
        if (oldObject.value) newObject.value = _defaultValue;
        if (oldObject.name) newObject.name = psStateName;
        if (oldObject.id) newObject.id = psStateName;
        if (oldObject.className) newObject.className = oldObject.className;

        for (i = 0; i < stateValue.length; i++) {
            var option = document.createElement("option");
            option.value = stateValue[i];
            option.text = stateText[i];
            newObject.options.add(option);
        }

        oldObject.parentNode.replaceChild(newObject, oldObject);

        //Change back to PhoneParts
        if (phoneParts && phone1) {
            phoneParts.style.display = "";
            phone1.style.display = "none";
        }

        if (phoneParts2 && phone2) {
            phoneParts2.style.display = "";
            phone2.style.display = "none";
        }



        zip.maxLength = 5;
        //if (zipRequired != null) { zipRequired.style.display = "inline"; }

        if (stateAsterisk) {
            stateAsterisk.style.display = '';
        }


        if (divAgentContact) {
            divAgentContact.style.display = '';
        }

        //Set hidden field  
        if (hdnInternational) {
            hdnInternational.value = 0;
        }

        //CurrencyCalculator
        if (psCurrencyCalculator) {
            psCurrencyCalculator.style.display = "none";
        }


    }

}

function g_fnChangeOptionValues(psValue) {
    try {
        if (_international) {
            var oldSelect = document.getElementById(psValue);
            var newSelect = document.createElement('select');

            if (oldSelect.onchange) newSelect.onchange = oldSelect.onchange;
            if (oldSelect.name) newSelect.name = oldSelect.name;
            if (oldSelect.id) newSelect.id = oldSelect.id;
            if (oldSelect.className) newSelect.className = oldSelect.className;

            for (i = 0; i < oldSelect.options.length; i++) {
                if (oldSelect.options[i]) {
                    if ((oldSelect.options[i].value == "") ||
						(oldSelect.options[i].value == "amex") ||
						(oldSelect.options[i].value == "visa") ||
						(oldSelect.options[i].value == "mc")) {
                        newSelect.options[newSelect.options.length] = new Option(oldSelect.options[i].text, oldSelect.options[i].value, oldSelect.options[i].selected, oldSelect.options[i].selected);
                    }
                }
            }
            oldSelect.parentNode.replaceChild(newSelect, oldSelect);
        }
        else {
            var select = document.getElementById(psValue);

            select.options[select.options.length] = new Option("Personal Check", "pchk");
            select.options[select.options.length] = new Option("Company Check", "cochk");
        }
    }
    catch (e) { }
}

function g_fnLoadInternational(pbInternational, psCountryName, psFormName, psStateName, psStateValue, psZipCodeName, psPhonePartsName, psPhone1, psInternational, psCountryFormName, psStateAsterisk, psAgentContact, psPhoneParts2, psPhone2, psCurrencyCalculator) {
    try {
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //	INTERNATIONAL USER SETTINGS
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if (!varIsEmpty(psCountryFormName) && !varIsEmpty(psFormName)) {
            //look up country in case browser cached the value
            psCountryName = psFormName[psCountryFormName].value;
            
            if (!varIsEmpty(psCountryName)) {
                if (psCountryName == _countryUSA) {
                    pbInternational = false;
                } else {
                    pbInternational = true;
                }
            }
        }
        if (pbInternational) {
            var newObject = document.createElement('input');
            newObject.value = psCountryName;

            this.g_fnChangeCountry(newObject, psFormName, psStateName, psZipCodeName, psPhonePartsName, psPhone1, psInternational, psStateAsterisk, psAgentContact, psPhoneParts2, psPhone2, psCurrencyCalculator);

            document.getElementById(psStateName).value = psStateValue;
        }
    }
    catch (e) { }
}

function _getElementObject(element) {
    try {
        var type = typeof element;
        if (type == 'string') {
            return document.getElementById(element);
        }
        else {
            return element;
        }
    } catch (e) { }
}

function getInternationByCountry(country) {
    try {
        var result = false;
        var control = _getElementObject(country);
        if ((control) && (control.value != 'UNIT') && (control.value != '')) {
            result = true;
        }
        return result;
    } catch (e) { }
}

function updateInternationalLabels(international, state, zip, txtZipInputSyle, txtStateInputStyle) {
    try {
        var useInternational = false;
        var type = typeof international;
        if (type == 'boolean') {
            useInternational = international;
        }
        else {
            var control = _getElementObject(international);
            if ((control) && (control.value == '1')) {
                useInternational = true;
            }
        }

        var stateControl = _getElementObject(state);
        var zipControl = _getElementObject(zip);
        var zipInput = _getElementObject(txtZipInputSyle);
        var stateInput = _getElementObject(txtStateInputStyle);

        if ((stateControl) && (zipControl)) {
            if (useInternational) {
                stateControl.innerHTML = 'Prov/Cnty';
                zipControl.innerHTML = 'Postal Code';
                if ((zipInput) && (stateInput)) {
                    zipInput.style.marginLeft = "0px";
                    stateInput.style.marginLeft = "9px";
                    stateInput.style.width = "120px";

                }
            }
            else {
                stateControl.innerHTML = 'State';
                zipControl.innerHTML = 'ZIP Code';
                zipInput.style.marginLeft = "18px";
                stateInput.style.marginLeft = "43px";
                stateInput.style.width = "124px";
            }
        }

        if ((!zipInput) && (!stateInput)) {
            zipInput.style = "";
            stateInput.style = "";
        }
    } catch (e) { }
}

function ToggleMyNote(currentID) {
    if (typeof (currentID) != "undefined" && currentID != null) {
        var image = document.getElementById("toggleImg_" + currentID);
        var descriptionContainer = document.getElementById("noteDesription_" + currentID);
        var noteContainer = document.getElementById("fullNote_" + currentID);

        if (descriptionContainer != null && noteContainer != null) {
            var fullNoteVisible = (noteContainer.className == "myRTFullNote");
            descriptionContainer.className = fullNoteVisible ? "myRTNoteDescription" : "myRTNoteDescriptionHidden";
            noteContainer.className = fullNoteVisible ? "myRTFullNoteHidden" : "myRTFullNote";

            if (image != null) {
                image.src = fullNoteVisible ? "/images/my_rt/Cobrand_plus.gif" : "/images/my_rt/Cobrand_minus.gif";
            }
        }
    }
}

function fnSavedNoteSubmit() {
    var radioButtons = document.getElementsByName("myNoteID");
    var propertyID = 0;
    var url = "/PropertyDetails/PropertyDetails.aspx";

    if (radioButtons != null) {
        for (var i = 0; i < radioButtons.length; i++) {
            if (radioButtons[i].checked) {
                propertyID = radioButtons[i].value;
            }
        }
    }

    if (propertyID > 0) {
        url += "?propid=" + propertyID;
        window.location = url;
    }
}

/* image button rollovers - start */
function setButtonImageRoll(imgObj) {
    var buttonObj = document.getElementById(imgObj);
    if (typeof buttonObj != 'undefined') {
        var imgNameBase = getFileNameBaseFromSrc(buttonObj.src);
        var imgNameFormat = getFileFormatFromSrc(buttonObj.src);
        var defaultImage = new Image();
        defaultImage.src = "/images/buttons/" + imgNameBase + "" + imgNameFormat;
        var rollImage = new Image();
        rollImage.src = "/images/buttons/" + imgNameBase + "-over" + imgNameFormat;
        buttonObj.onmouseover = function() {
            this.src = rollImage.src;
        };
        buttonObj.onmouseout = function() {
            this.src = defaultImage.src;
        };
    }
}
function getFileFormatFromSrc(src) {
    var ff = ".jpg";
    var res = src.match(/\.(gif|png|jpg)$/);
    if (res != null) {
        ff = res[0];
    }
    return ff;
}
function getFileNameBaseFromSrc(src) {
    var fnm = "";
    var srcParts = src.split("/");
    fnm = srcParts[srcParts.length - 1].replace(/\.(gif|png|jpg)$/, "");
    return fnm;
}
/* image button rollovers - end */

/* show/hide any element by id - start */
function findElement(element_id) {
    if (document.getElementById && document.getElementById(element_id)) {
        return document.getElementById(element_id);
    } else {
        return false;
    }
}

function hideElement(element_id) {
    element = findElement(element_id);
    if (element) {
        element.style.display = 'none';
        return element;
    } else {
        return false;
    }
}

function showElement(element_id) {
    element = findElement(element_id);
    if (element) {
        element.style.display = '';
        return element;
    } else {
        return false;
    }
}
/* show/hide any element by id - end */

function fnErrorNoSavedScenario(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "There are no saved scenarios in this list"; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

function fnErrorNoSavedScenarioSelect(psOverRideMessage) {
    // returns an error message
    var lsDefaultMessage = "Please select a saved scenario."; // default error message
    var lsReturn = fnErrorReturn(lsDefaultMessage, psOverRideMessage);

    return lsReturn;
}

/*moved from user profile web*/
function searchTbxFocus(sender) {
    sender.style.color = '#333';
}
function searchTbxBlur(sender) {
    sender.style.color = '#999';
}

function validateSearchParams(sender, e) {
    if (agentZipId == null || agentCityStateId == null) {
        return;
    }

    e.IsValid = ValidateAgentSearch(agentCityStateId, agentZipId, false, '', '');
	return e.IsValid;
}

var agentLeadsUrl = null;

function SubmitAgentSearch(agentCityStateId, agentZipId, leadSource, serverName)
{
	var validationResult = ValidateAgentSearch(agentCityStateId, agentZipId, true, leadSource, serverName);
	
	if(validationResult && agentLeadsUrl && agentLeadsUrl.length > 0)
	{
		window.location = agentLeadsUrl;
	}
}

function ValidateAgentSearch(agentCityStateId, agentZipId, redirect, leadSource, serverName)
{
	var result = true;
	
	if (agentCityStateId == null || agentZipId == null) {
        return false;
    }
	
    var agentZip = document.getElementById(agentZipId).value;
    agentZip = trim(agentZip);

    var cityState = document.getElementById(agentCityStateId).value;
    cityState = trim(cityState);

    var msg = 'Please enter search criteria.';
	var zipErrorMsg = '';
	var cityErrorMsg = '';
	var cityName ='';
	var stateCode='';

    if (cityState.length == 0 && agentZip.length == 0) {
        alert(msg);
        return false;
    }
	else
	{
		msg='';
	}

    if (agentZip.length > 0) {
        var zipRx = /^\d{5}$/;

        result = zipRx.test(agentZip);

        if (!result)
			zipErrorMsg = 'Zip code must consist of 5 digits.';
    }

    if (cityState.length > 0) {
        var comma = cityState.lastIndexOf(',');

        if (comma < 0)
        {
            result = false;
            cityErrorMsg = 'Address format incorrect.\nExample: Irvine, CA';
        }
        else
        {
            var state = cityState.substr(comma + 1);
            state = trim(state).toUpperCase();

            var stateRx = /^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/;

            result = stateRx.test(state);

            if (result == false)
                cityErrorMsg = 'Please specify correct state code.\nExample: Irvine, CA';
			else{
				stateCode = state;
				cityName = trim(cityState.substr(0, comma));
			}
        }
    }

    if ((zipErrorMsg.length > 0 && cityErrorMsg.length == 0) || (zipErrorMsg.length > 0 && cityErrorMsg.length > 0))
	{
		alert(zipErrorMsg);
		result = false;
	}
	else if (cityErrorMsg.length > 0) {
		alert(cityErrorMsg);
	}
	else if(msg.length > 0)
	{
		alert(msg);
	}
	else
	{
		result = true;
	}
	
	if(result && redirect){
		agentLeadsUrl=serverName+'/agents/leads/landing.aspx?zipcode='+agentZip+'&city='+cityName+'&state='+stateCode+'&leadsource='+leadSource;
	}
	
	return result;
}


function lTrim(value) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}
function rTrim(value) {

    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");

}
function trim(value) {

    return lTrim(rTrim(value));
}
/*moved from user profile web*/

