﻿
/// <reference path="/common/jquery/jquery.js" />
/// <reference path="/common/jquery/jquery-ui.js" />
/// <reference path="/common/jquery/mlx.extensions.js" />  


// -------------------- LocationSuggestor ----------------------

function LocationSuggestor(myClientID) {
    this.clientID = myClientID;
    this.findMatchFromLatestOptions = LocationSuggestor_findMatchFromLatestOptions;
    this.showOops = LocationSuggestor_showOops;
    this.hideOops = LocationSuggestor_hideOops;
    this.pickSuggestion = LocationSuggestor_pickSuggestion;
    this.setupSearchSave = LocationSuggestor_setupSearchSave;
    this.latestOptions = new Array();
    this.requestPending = false;
    this.getLocationQuery = LocationSuggestor_getLocationQuery;
    this.clearTextBox = LocationSuggestor_clearTextBox;
    this.searchAction = function() { };
    this.getTextBox = LocationSuggestor_getTextBox;
    this.onEnter = LocationSuggestor_onEnter;
    this.setAutocompleteURL = LocationSuggestor_setAutocompleteURL;
    this.showSearchResult = MiniSearch_ShowResult;
    this.selectedJSONValue = "";
    this.autocompleteURL = "";
    this.noRecordFound = false;
    this.isEnterClicked = false;
    this.clearCache = false;
    this.locationSelected = false;
    this.lastRecordNotFoundSearch = "";
    this.defaultText = "Address, City, Zip or MLS#";
    this.autoPostOnSelect = true;
    this.returnData = {};
}
LocationSuggestor.prototype.defaultAfterSelect = null;
LocationSuggestor.prototype.afterSelect = null;

LocationSuggestor.prototype.load = function () {
    var cache = {};
    var thisSuggestor = this;

    var autocompleteSource = function (request, response) {
        if (thisSuggestor.noRecordFound && !thisSuggestor.clearCache && (request.term.indexOf(thisSuggestor.lastRecordNotFoundSearch) >= 0)) {
            response([]);
            return;
        }

        var term = request.term.toLowerCase(),
            element = this.element,
            cache = this.element.data('autocompleteCache') || {},
            foundInCache = false;

        if (thisSuggestor.clearCache)
            cache = {};

        $.each(cache, function (key, data) {
            if (term.indexOf(key) === 0 && data.length > 0) {

                var csub = [];
                for (var i = 0, ol = data.length; i < ol; i++) {
                    if (data[i].label.toLowerCase().indexOf(request.term) >= 0)
                        csub.push(data[i]);
                }

                if (csub.length > 0) {
                    response(csub);
                    foundInCache = true;
                    return;
                }
            }
        });

        if (foundInCache && !thisSuggestor.clearCache) return;

        thisSuggestor.clearCache = false;
        thisSuggestor.noRecordFound = false;

        var soldInfo = "";
        if ($("[id $= 'ddlActiveSold']").length > 0) {
            if ($("[id $= 'ddlActiveSold']").val() == 'S')
                soldInfo = '&daysBackSold=' + $("[id $= 'ddlDaysBackSold']").val();
        }
        var query = $.trim(request.term);
        if (query.length > 0) {

            var localURL = thisSuggestor.autocompleteURL + '&term=' + query;
            if (soldInfo != '')
                localURL += soldInfo;

            $.getJSON(
	            localURL,
	            function (data) {

	                if (data && data.length > 0) {
	                    thisSuggestor.returnData = data;

	                    if (data.length == 1) {
	                        if (data[0].value == 'NORECORDFOUND') {
	                            thisSuggestor.noRecordFound = true;
	                            thisSuggestor.lastRecordNotFoundSearch = query;
	                            response([]);
	                            return;
	                        }
	                    }

	                    if (data[0].value != 'DONOTCACHE') {
	                        cache[term] = data;
	                        element.data('autocompleteCache', cache);
	                    }
	                    else if (data[0].value == 'DONOTCACHE') {
	                        data = data.slice(1);
	                    }
	                }

	                if (data) {
	                    if ((query == $.trim(thisSuggestor.getTextBox().val()) && (!thisSuggestor.isEnterClicked))) {
	                        response(data);
	                    }
	                    else
	                        response([]);
	                }
	            }
            );
        }
        else
            response([]);

    }

    var thisSuggestor = this;
    var txtSearch = thisSuggestor.getTextBox();
    txtSearch.val("");
    txtSearch.live('keydown',
        function (event, ui) {
            if (event.keyCode == '13') {
                if (txtSearch.val() != '') {

                    thisSuggestor.isEnterClicked = true;
                    txtSearch.catcomplete("close");
                    event.preventDefault();

                    if (!thisSuggestor.locationSelected)
                        MiniSearch_getAddressFromBing(thisSuggestor);
                }
            }
         }
    );
     txtSearch.live('keyup',
        function (event, ui) {
            if (event.keyCode == 32) {
                // blank - prevent double blanks
                txtSearch.val(txtSearch.val().replace('  ', ' '));
            }
        }
    );

    txtSearch.catcomplete(
        {
            source: autocompleteSource,
            minLength: 2,
            matchSubset: 1,
            select: function (event, ui) {

                txtSearch.val(ui.item.label);
                thisSuggestor.selectedJSONValue = ui.item;
                thisSuggestor.getHiddenDataField().val(JSON.stringify(ui.item));

                thisSuggestor.locationSelected = true;

                if (thisSuggestor.autoPostOnSelect) {
                    if (thisSuggestor.defaultAfterSelect)
                        thisSuggestor.onEnter();

                    if (thisSuggestor.afterSelect)
                        thisSuggestor.afterSelect();
                    else if (thisSuggestor.defaultAfterSelect)
                        thisSuggestor.defaultAfterSelect();
                    thisSuggestor.isEnterClicked = false;
                }
            }
        }
    );

    txtSearch.showDefaultText(this.defaultText, "ac_defaultTextActive");
    thisSuggestor.setupSearchSave();
}

function LocationSuggestor_getTextBox() {
    return $("#" + this.clientID + "_txtSearch");
}
LocationSuggestor.prototype.getHiddenDataField = function () {
    return $("#" + this.clientID + "_hidSearch");
}
function LocationSuggestor_getTextBox() {
    return $("#" + this.clientID + "_txtSearch");
}
function LocationSuggestor_getLocationQuery() {
    return this.selectedJSONValue;
}
function LocationSuggestor_onEnter() {
    if ((this.getTextBox().val().length > 0) && (this.getTextBox().val() != this.defaultText)) {
        this.getTextBox().catcomplete("close");
        this.getTextBox().attr("disabled", true);
        if ($("[id $= 'divSearchButton']").length > 0) {
            $("[id $= 'divSearchButton']").attr("disabled", true);
            $("[id $= 'btnSearch']").attr("disabled", true);
        }
    }
}

function LocationSuggestor_setAutocompleteURL(url) {
    this.autocompleteURL = url;
}

function LocationSuggestor_findMatchFromLatestOptions() {
    var searchText = document.getElementById(this.clientID + "_txtSearch").value;
    var hidSearch = $("#" + this.clientID + "_hidSearch");
    var itemIndex = -1;

    //check to see if there's only one item in the options list, and select the one item if there is.
    if (itemIndex == -1 && this.latestOptions.length == 2)
        itemIndex = 1;

    //Loop through once to find an exact match first
    for (var x = 0; x < this.latestOptions.length; x++) {
        var data = this.latestOptions[x].data;

        if (data && data[1] && data[0].toUpperCase() == searchText.trim().toUpperCase()) {
            itemIndex = x;
            break;
        }
    }

    //Loop through a second time to find an exact matched to the string before the hyphen
    if (itemIndex == -1) {
        for (var x = 0; x < this.latestOptions.length; x++) {
            var data = this.latestOptions[x].data;

            if (data && data[1]) {
                var s = data[0];

                if (s.indexOf("-") > 0)
                    s = s.substring(0, s.indexOf("-")).trim();

                if (s.toUpperCase() == searchText.trim().toUpperCase()) {
                    itemIndex = x;
                    break;
                }
            }
        }
    }

    if (itemIndex != -1)
        hidSearch.val(this.latestOptions[itemIndex].data[1]);
}

function LocationSuggestor_clearTextBox() {
    if (this.getTextBox().val().toLowerCase() != this.defaultText.toLowerCase())
        this.getTextBox().val("");
}
function LocationSuggestor_setupSearchSave() {
    var txtSearch = $("#" + this.clientID + "_txtSearch");
    var suggestor = this;
    txtSearch.keydown(function(event) {
        if (!ShiftOrEnter(event))
            $("#" + event.currentTarget.getAttribute("clientID") + "_hidSearch").val("");

        eval(event.currentTarget.getAttribute("clientID") + "_suggestor.hideOops();");

        if (!ShiftOrEnter(event)) {
            eval(event.currentTarget.getAttribute("clientID") + "_suggestor.latestOptions = [];");
        }
    });
    txtSearch.attr("clientID", this.clientID);

//    txtSearch.result(function(event, data, formatted) {
//        //selected item data, extras;
//        var hidSearch = $("#" + event.currentTarget.getAttribute("clientID") + "_hidSearch");

//        if (data && data[1])
//            hidSearch.val(data[1]);
//        else
//            hidSearch.val("");
//    });
//    
//    txtSearch.loadOptions(function(event, data) {
//        eval(event.currentTarget.getAttribute("clientID") + "_suggestor.latestOptions = data;");
//    });
//    
//    txtSearch.requestPending(function(event, rp) {
//        acDebug("Pending: " + rp.toString());
//        eval(event.currentTarget.getAttribute("clientID") + "_suggestor.requestPending = " + rp.toString());
//    });

//    txtSearch.submitSearch(function(event) {    
//        txtSearch.blur();
//        if (suggestor.searchAction)
//            suggestor.searchAction();
//    });
}

function LocationSuggestor_DoLocationSearch(ClientID, strJSON) {
    $("#" + ClientID + "_divSuggestions").hide();

    var suggestor = new LocationSuggestor(ClientID); 
    strJSON = strJSON.replace(/~/gi, '"');
    suggestor.getHiddenDataField().val(strJSON);
    suggestor.clearTextBox();
    if (typeof (SB_ShowResultsLoading) != 'undefined') SB_ShowResultsLoading();
    $("[id $= 'btnAddLocation']").click();
}

function LocationSuggestor_showOops(data) {

    var txtSearch = $("#" + this.clientID + "_txtSearch");
    var newPosition = (txtSearch.position().top + 1) + txtSearch.height();

    if (data && data.length > 0) {
        
        $("#" + this.clientID + "_divSuggestions").show();
        $("#" + this.clientID + "_divSuggestions").css('top', newPosition + "px");

        var suggestions = '<br />';
        for (var i = 0; i < data.length; i++) {
            var JSONValue = JSON.stringify(data[i]).replace(/"/gi, '~');
            suggestions += "<a href=\"javascript:LocationSuggestor_DoLocationSearch('" + this.clientID + "','" + JSONValue + "')\">" + data[i].label + '</a><br />';
        }
        $("#" + this.clientID + "_divSuggestedItems").html(suggestions);
    }
    else {
        $("#" + this.clientID + "_divOops").show();
        $("#" + this.clientID + "_divOops").css('top', newPosition + "px");
    }

}

function LocationSuggestor_hideOops() {
    document.getElementById(this.clientID + "_divOops").style.display = "none";
    document.getElementById(this.clientID + "_divSuggestions").style.display = "none";
}

function LocationSuggestor_drawSuggestion(clientID, optionText, optionIndex) {
    var a = document.createElement("a");
    a.href = "javascript:" + clientID + "_suggestor.pickSuggestion(" + optionIndex + ");";
    a.className = "ms-oops-a";
    var d = document.createElement("div");
    d.innerText = optionText;
    a.appendChild(d);
    return a;
}

function LocationSuggestor_pickSuggestion(itemIndex) {
    var hidSearch = $("#" + this.clientID + "_hidSearch");
    hidSearch.val(this.latestOptions[itemIndex].data[1]);
    this.search();
}

// -------------------- End LocationSuggestor ----------------------

// -------------------- MiniSearch ----------------------

function MiniSearch(myClientID) {
    this.clientID = myClientID;
    this.setupSearchButton = MiniSearch_setupSearchButton;
    this.setupMoreOptionsDisplay = MiniSearch_setupMoreOptionsDisplay;
    this.loadBedSlider = MiniSearch_loadBedSlider;
    this.loadBathsSlider = MiniSearch_loadBathsSlider;
    this.loadPriceSlider = MiniSearch_loadPriceSlider;
    this.reloadPriceSlider = MiniSearch_reloadPriceSlider;
    this.getBedString = MiniSearch_getBedString;
    this.getBedValue = MiniSearch_getBedValue;
    this.getBathString = MiniSearch_getBathString;
    this.getBathValue = MiniSearch_getBathValue;
    this.getPriceString = MiniSearch_getPriceString;
    this.getPriceValue = MiniSearch_getPriceValue;
    this.search = MiniSearch_Search;
    this.getCurrentPrices = MiniSearch_getCurrentPrices;
    this.getCurrentBaths = MiniSearch_getCurrentBaths;
    this.getCurrentBeds = MiniSearch_getCurrentBeds;
    this.getCurrentClass = MiniSearch_getCurrentClass;
    this.getBedDisplayControl = MiniSearch_getBedDisplayControl;
    this.getBathDisplayControl = MiniSearch_getBathDisplayControl;
    this.getPriceDisplayControl = MiniSearch_getPriceDisplayControl;

    this.locationSuggestor; // set on document.ready
    
    this.defaultBedsMin = 0;
    this.defaultBedsMax = 7;
    this.defaultBathsMin = 0;
    this.defaultBathsMax = 7;
    this.lowestPrice = 25000;
    this.highestPrice = 30000000;
    this.defaultPriceMin = this.lowestPrice;
    this.defaultPriceMax = this.highestPrice;
}

function GetQueryParamfromJSOn(searchText) {
    var query = "&TYPE=" + (searchText.streetAddress == "" ? "R" : "A")
    query += searchText.state.length > 0 ? "&ST=" + searchText.state : "";
    query += searchText.county.length > 0 && searchText.streetName.length == 0 ? "&COUNTY=" + escape(searchText.county) : "";
    query += searchText.city.length > 0 ? "&CITY=" + escape(searchText.city) : "";
    query += searchText.neighborhood.length > 0 ? "&NEIGHBORHOOD=" + escape(searchText.neighborhood) : "";
    query += searchText.postalCode.length > 0 ? "&ZIP=" + searchText.postalCode : "";
    query += searchText.streetName.length > 0 ? "&STREET=" + escape(searchText.streetName) : "";
    query += searchText.streetAddress.length > 0 ? "&ADDRESS=" + escape(searchText.streetAddress) : "";

    return query;
}

function MiniSearch_Search() {
    var priceRange = this.getCurrentPrices();
    var bathRange = this.getCurrentBaths();
    var bedRange = this.getCurrentBeds();
    var className = this.getCurrentClass();
    var url = SE_PrepURL(SE_LN_SearchResultsUrl);
    var query = ""
    var searchText = null;

    if (eval(this.clientID + "_minisearch.requestPending")) {
        acDebug("waiting for response...");
        setTimeout(this.clientID + "_minisearch.search();", 200);
        return;
    }

    var locationQuery = this.locationSuggestor.getLocationQuery();

    if (locationQuery != "") {
        searchText = locationQuery

        if (searchText.concatListingID != "") {
            if (searchText.friendlyUrl.length > 0)
                location.href = searchText.friendlyUrl;
            else
                location.href = SE_PrepURL(SE_LN_PropertyDetailUrl)
                        + "listingID=" + searchText.concatListingID;

            return;
        }
        else {
            if (searchText.friendlyUrl.length > 0)
                url = searchText.friendlyUrl;
            else
                query += GetQueryParamfromJSOn(searchText);
        }
    }
    else {
        MiniSearch_getAddressFromBing(this.locationSuggestor);
        if (this.locationSuggestor.selectedJSONValue == '')
            return;
        else
            query += GetQueryParamfromJSOn(this.locationSuggestor.selectedJSONValue);

        //eval(this.locationSuggestor.clientID + "_suggestor.showOops();");

    }

    var divMoreOptionsContent = $("#" + this.clientID + "_divMoreOptionsContent");
    if (divMoreOptionsContent.is(":visible") && (searchText == null || searchText.listingID == "")) {
        query += priceRange[0] != null ? "&NPR=" + priceRange[0] : "";
        query += priceRange[1] != null ? "&XPR=" + priceRange[1] : "";
        query += bathRange != '' ? "&NBA=" + bathRange : "";
        query += bedRange != '' ? "&NBD=" + bedRange : "";
        query += "&CLASS=" + (className == "" || className.toLowerCase() == "any" ? "ANY" : className);
    }
    else
        query += "&CLASS=ANY";

    location.href = SE_PrepURL(url) + "SUBMIT=T" + query;
}

function MiniSearch_ShowResult() {
    if ($("[id $= 'btnAddLocation']").length > 0) {
        this.clearTextBox();
        if (typeof (SB_ShowResultsLoading) != 'undefined') SB_ShowResultsLoading();

        $("[id $= 'btnAddLocation']").click();
    }
    else {
        return true;
    }
    
    return false;
}

function MiniSearch_getAddressFromBing(locationSuggestor) {
    locationSuggestor.onEnter();
    var query = $.trim(locationSuggestor.getTextBox().val());
    if ((query.length > 0) && (query != locationSuggestor.defaultText)) {

        if (locationSuggestor.returnData && locationSuggestor.returnData.length > 0) {

            locationSuggestor.selectedJSONValue = locationSuggestor.returnData[0];
            locationSuggestor.getHiddenDataField().val(JSON.stringify(locationSuggestor.returnData[0]));

            if (locationSuggestor.afterSelect)
                locationSuggestor.afterSelect();
            else if (locationSuggestor.defaultAfterSelect)
                locationSuggestor.defaultAfterSelect();
        }
        else {
            var autocompleteURL = locationSuggestor.autocompleteURL.replace('mlslocation', 'bingsearch');
            autocompleteURL += '&term=' + query;

            locationSuggestor.selectedJSONValue = '';
            $.getJSON(
            	autocompleteURL,
            	function (data) {
            	    locationSuggestor.onEnter();

            	    if (data.length == 1) {
            	        locationSuggestor.getHiddenDataField().val(JSON.stringify(data[0]));

            	        locationSuggestor.selectedJSONValue = data[0];
            	        locationSuggestor.getHiddenDataField().val(JSON.stringify(data[0]));
            	    }
            	    else {
            	        locationSuggestor.getTextBox().attr("disabled", false);
            	        locationSuggestor.showOops(data);
            	    }

            	    if (data.length > 0) {
            	        if (locationSuggestor.afterSelect)
            	            locationSuggestor.afterSelect();
            	        else if (locationSuggestor.defaultAfterSelect)
            	            locationSuggestor.defaultAfterSelect();
            	    }

            	}
            );
        }


    }
}

function MiniSearch_setupSearchButton() {
    var btnSearch = $("#" + this.clientID + "_btnSearch");
    btnSearch.hover(
	        function() {
	            $(this).addClass("ui-state-hover");
	        },
	        function() {
	            $(this).removeClass("ui-state-hover");
	        }
        )
}

function MiniSearch_setupMoreOptionsDisplay() {
    var divMoreOptions = $("#" + this.clientID + "_divMoreOptions")
    var divMoreOptionsContent = $("#" + this.clientID + "_divMoreOptionsContent")

    divMoreOptions.click(function() {
    if (divMoreOptionsContent.is(":hidden")) {

            divMoreOptionsContent.css("height", "");
            divMoreOptionsContent.slideDown(250);
            var icon = divMoreOptions.find(".ui-icon-triangle-1-s");
            if (icon) {
                icon.addClass("ui-icon-triangle-1-n");
                icon.removeClass("ui-icon-triangle-1-s");
            }
        } else {
            divMoreOptionsContent.animate(
                    { height: "1", hide: "hide" }, 250);


            var icon = divMoreOptions.find(".ui-icon-triangle-1-n");
            if (icon) {
                icon.addClass("ui-icon-triangle-1-s");
                icon.removeClass("ui-icon-triangle-1-n");
            }
        }
    });
}

function MiniSearch_loadBedSlider() {
    var bedSlider = $("#" + this.clientID + "_divBedSlider");
    bedSlider.slider(
            {
                range: true,
                min: 0,
                max: 70,
                slide: function(event, ui) {
                    ms = eval(this.getAttribute("clientID") + "_minisearch");
                    ms.getBedDisplayControl(this.getAttribute("clientID")).text(
                    eval(this.getAttribute("clientID") + "_minisearch").getBedString(ui.values[0], ui.values[1]));
                },
                values: [this.defaultBedsMin * 10, this.defaultBedsMax * 10]

            }
        );
    bedSlider.attr("clientID", this.clientID);
    this.getBedDisplayControl(this.clientID).text(
            this.getBedString(bedSlider.slider("values", 0), bedSlider.slider("values", 1)));
}

function MiniSearch_getBedDisplayControl(clientID) {
    return $("#" + clientID + "_spnBedsDisplay");
}
function MiniSearch_getBathDisplayControl(clientID) {
    return $("#" + clientID + "_spnBathsDisplay");
}

function MiniSearch_loadBathsSlider() {
    var bathSlider = $("#" + this.clientID + "_divBathSlider");
    bathSlider.slider(
        {
            range: true,
            min: 0,
            max: 70,
            slide: function(event, ui) {
                ms = eval(this.getAttribute("clientID") + "_minisearch");
                ms.getBathDisplayControl(this.getAttribute("clientID")).text(
                eval(this.getAttribute("clientID") + "_minisearch").getBathString(ui.values[0], ui.values[1]));
            },
            values: [this.defaultBathsMin * 10, this.defaultBathsMax * 10]
        });
    bathSlider.attr("clientID", this.clientID);

    this.getBathDisplayControl(this.clientID).text(
            this.getBathString(bathSlider.slider("values", 0), bathSlider.slider("values", 1)));
}

function MiniSearch_loadPriceSlider() {
    this.reloadPriceSlider();
}

function MiniSearch_getPriceDisplayControl(clientID) {
    return $("#" + clientID + "_spnPriceDisplay");
}

function MiniSearch_getCurrentPrices() {
    var prices = [];

    var priceMinctl = $("#" + this.clientID + "_ddlMinPrice");
    var priceMaxctl = $("#" + this.clientID + "_ddlMaxPrice");

    prices[0] = priceMinctl.val();
    prices[1] = priceMaxctl.val();

    return prices;
}

function MiniSearch_getBedValue(bedsRaw) {
    return parseInt(bedsRaw / 10);
}

function MiniSearch_getBedString(minBeds, maxBeds) {
    var iMinBeds = this.getBedValue(minBeds);
    var iMaxBeds = this.getBedValue(maxBeds);

    if (iMinBeds == 0 && iMaxBeds == 7) {
        return "Any number"
    }

    if (iMinBeds == 0)
        return "up to " + iMaxBeds;
    else if (iMaxBeds == 7)
        return iMinBeds + " or more";
    else
        return iMinBeds + " to " + iMaxBeds;
}

function MiniSearch_getBathValue(bathsRaw) {
    return parseInt(bathsRaw / 10);
}

function MiniSearch_getCurrentBaths() {
    var bathMin = '';
    var bathMinctl = $("#" + this.clientID + "_ddlMinBathrooms");
    bathMin = bathMinctl.val();

    return bathMin;
}

function MiniSearch_getCurrentBeds() {
    var bedMin = '';
    var bedMinctl = $("#" + this.clientID + "_ddlMinBedrooms");
    bedMin = bedMinctl.val();

    return bedMin;
}

function MiniSearch_getCurrentClass() {
    var ddlClass = $("#" + this.clientID + "_ddlPropertyType");
    return ddlClass.val();
}

function MiniSearch_getBathString(minBaths, maxBaths) {
    // returns string rounded to nearest .5 baths
    var MinBaths = this.getBathValue(minBaths);
    var MaxBaths = this.getBathValue(maxBaths);

    if (MinBaths == 0 && MaxBaths == 7) {
        return "Any number"
    }

    if (MinBaths == 0)
        return "Up to " + MaxBaths;
    else if (MaxBaths == 7)
        return MinBaths + " or more";
    else
        return MinBaths + " to " + MaxBaths;
}

function MiniSearch_getPriceValue(logPriceRaw, extentValue) {
    var price = Math.exp(logPriceRaw / 100);

    if (Math.abs(price / extentValue) > .99 && Math.abs(price / extentValue) < 1.01)
        price = extentValue;
    return price;
}

function MiniSearch_getPriceString(logMinPrice, logMaxPrice, minValue, maxValue) {

    var minPrice = this.getPriceValue(logMinPrice, minValue);
    var maxPrice = this.getPriceValue(logMaxPrice, maxValue);
    var propClass = this.getCurrentClass();

    if (minPrice <= minValue && maxPrice >= maxValue) {
        return "Any price"
    }

    if (minPrice <= minValue)
        return "Up to " + MiniSearch_getPriceDisplay(maxPrice, propClass);
    else if (maxPrice >= maxValue)
        return MiniSearch_getPriceDisplay(minPrice, propClass) + " and up";
    else
        return MiniSearch_getPriceDisplay(minPrice, propClass) + " to " + MiniSearch_getPriceDisplay(maxPrice, propClass);

}
function MiniSearch_getPriceDisplay(price, propClass) {
    return MiniSearch_getPriceDisplayValue(price, propClass).toString().format("C0");
}

function MiniSearch_getPriceDisplayValue(price, propClass) {
    if (propClass == "RNT") {
        if (price <= 2000)
            return (Math.round(price / 100) * 100);
        else if (price <= 3000)
            return (Math.round(price / 500) * 500);
        else if (price <= 5000)
            return (Math.round(price / 1000) * 1000);
        else if (price <= 10000)
            return (Math.round(price / 2500) * 2500);
        else if (price <= 20000)
            return (Math.round(price / 5000) * 5000);
    }
    else {
        if (price <= 1000000)
            return (Math.round(price / 25000) * 25000);
        else if (price <= 2000000)
            return (Math.round(price / 100000) * 100000);
        else if (price <= 5000000)
            return (Math.round(price / 250000) * 250000);
        else if (price <= 10000000)
            return (Math.round(price / 1000000) * 1000000);
        else if (price <= 30000000)
            return (Math.round(price / 5000000) * 5000000);
    }
}

var _RentalPrices = new Array(0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
    1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2500, 3000, 4000,
    5000, 7500, 10000, 15000, 20000);
var _ListingPrices = new Array(25000, 50000, 75000, 100000, 125000, 150000, 175000, 200000,
    225000, 250000, 275000, 300000, 325000, 350000, 375000, 400000, 425000, 450000, 475000, 500000,
    525000, 550000, 575000, 600000, 625000, 650000, 675000, 700000, 725000, 750000, 775000, 800000,
    825000, 850000, 875000, 900000, 925000, 950000, 975000, 1000000, 1100000, 1200000, 1300000, 1400000, 1500000,
    1600000, 1700000, 1800000, 1900000, 2000000, 2250000, 2500000, 2750000, 3000000, 3250000, 3500000,
    3750000, 4000000, 4250000, 4500000, 4750000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000, 15000000,
    20000000, 25000000, 30000000);

function LoadPriceRange(ctlID, priceRange, selectedPriceRange) {
    var ctlMin = document.getElementById(ctlID + "_ddlMinPrice");
    var ctlMax = document.getElementById(ctlID + "_ddlMaxPrice");

    ctlMin.options.length = 0;
    ctlMin.options[0] = new Option("Minimum", "");

    ctlMax.options.length = 0;
    ctlMax.options[0] = new Option("Maximum", "");

    for (var i = 0; i < priceRange.length; i++) {
        var price = new String(priceRange[i]).format("C0");
        ctlMin.options[ctlMin.options.length] = new Option(price, priceRange[i]);

        if (selectedPriceRange[0] != null && priceRange[i] == selectedPriceRange[0])
            ctlMin.options[ctlMin.options.length - 1].selected = true;

        ctlMax.options[ctlMax.options.length] = new Option(price, priceRange[i]);

        if (selectedPriceRange[1] != null && priceRange[i] == selectedPriceRange[1])
            ctlMax.options[ctlMax.options.length - 1].selected = true;
    }
}

function MiniSearch_PopulateRentalPrices(ctlID, selectedPriceRange) {
    LoadPriceRange(ctlID, _RentalPrices, selectedPriceRange);
}

function MiniSearch_PopulateRegularPrices(ctlID, selectedPriceRange) {
    LoadPriceRange(ctlID, _ListingPrices, selectedPriceRange);
}

function MiniSearch_reloadPriceSlider() {
    var selectedPriceRange = this.getCurrentPrices();

    if (this.getCurrentClass() == "RNT" && this.lowestPrice != 100) {
        MiniSearch_PopulateRentalPrices(this.clientID, selectedPriceRange);
        
        this.lowestPrice = 100;
        this.highestPrice = 20000;
        this.defaultPriceMin = this.lowestPrice;
        this.defaultPriceMax = this.highestPrice;
    }
    else if (this.getCurrentClass() != "RNT") {
        MiniSearch_PopulateRegularPrices(this.clientID, selectedPriceRange);

        this.lowestPrice = 25000;
        this.highestPrice = 30000000;
        this.defaultPriceMin = this.lowestPrice;
        this.defaultPriceMax = this.highestPrice;
    }
}

function ShiftOrEnter(event) {
    return (event.keyCode == 13 || event.keyCode == 16);
}

// ------------------------- End MiniSearch ------------------------------

