﻿
/// <reference path="/common/jquery/jquery.js" />
/// <reference path="/common/jquery/jquery-ui.js" />
/// <reference path="/common/jquery/mlx.autocomplete.js" />
/// <reference path="/common/jquery/mlx.extensions.js" />  
/// <reference path="/common/utilities/string.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() { }; 
}

function LocationSuggestor_getLocationQuery() {
    var hidSearch = $("#" + this.clientID + "_hidSearch");
    if (hidSearch.val() == "")
        this.findMatchFromLatestOptions();
    return hidSearch.val();
}

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() {
    $("#" + this.clientID + "_txtSearch").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_showOops() {
    if (this.latestOptions.length > 0) {
        var suggestions = document.getElementById(this.clientID + "_divSuggestions");
       var txtSearch = document.getElementById(this.clientID + "_txtSearch");

        suggestions.style.top = (txtSearch.offsetHeight + 1) + "px";
        suggestions.style.display = "block";
        suggestions.focus();
    }
    else {
        var oops = document.getElementById(this.clientID + "_divOops");
        var txtSearch = document.getElementById(this.clientID + "_txtSearch");

        oops.style.top = (txtSearch.offsetHeight + 1) + "px";
        oops.style.display = "block";
        oops.focus();
    }
}

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 MiniSearch_Search() {
    var priceRange = this.getCurrentPrices();
    var bathRange = this.getCurrentBaths();
    var bedRange = this.getCurrentBeds();
    var className = this.getCurrentClass();
    var url = SE_PrepURL(SE_LN_EditSearchUrl);
    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 = JSON.parse(locationQuery);
        if (searchText.concatListingID != "") {
            location.href = SE_PrepURL(SE_LN_PropertyDetailUrl)
                    + "listingID=" + searchText.concatListingID;
            return;
        }
        else {
            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) : "";
        }
    }
    else {
        eval(this.locationSuggestor.clientID + "_suggestor.showOops();");
        return;
    }

    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[0] != null ? "&NBA=" + bathRange[0] : "";
        query += bathRange[1] != null ? "&XBA=" + bathRange[1] : "";
        query += bedRange[0] != null ? "&NBD=" + bedRange[0] : "";
        query += bedRange[1] != null ? "&XBD=" + bedRange[1] : "";
        query += "&CLASS=" + (className == "" || className.toLowerCase() == "any" ? "ANY" : className);
    }
    else
        query += "&CLASS=ANY";

    location.href = url + query + "&SUBMIT=T";
}

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() {
    var priceSlider = $("#" + this.clientID + "_divPriceSlider");

    priceSlider.slider(
            {
                range: true,
                min: Math.log(this.lowestPrice) * 100,
                max: Math.log(this.highestPrice) * 100,
                slide: function(event, ui) {
                    ms = eval(this.getAttribute("clientID") + "_minisearch");
                    ms.getPriceDisplayControl(this.getAttribute("clientID"))
                        .text(
                        ms.getPriceString(ui.values[0], ui.values[1], ms.lowestPrice, ms.highestPrice)
                        )
                },
                values: [Math.log(this.defaultPriceMin) * 100, Math.log(this.defaultPriceMax) * 100]
            }
        );

    priceSlider.attr("clientID", this.clientID);

    this.getPriceDisplayControl(this.clientID).text(
            this.getPriceString(
                priceSlider.slider("values", 0),
                priceSlider.slider("values", 1),
                this.lowestPrice, this.highestPrice)
        );

}

function MiniSearch_getPriceDisplayControl(clientID) {
    return $("#" + clientID + "_spnPriceDisplay");
}

function MiniSearch_getCurrentPrices() {
    var priceSlider = $("#" + this.clientID + "_divPriceSlider");
    var prices = [];
    prices[0] = MiniSearch_getPriceDisplayValue(this.getPriceValue(priceSlider.slider("values", 0)));
    prices[1] = MiniSearch_getPriceDisplayValue(this.getPriceValue(priceSlider.slider("values", 1)));

    if (prices[0] == this.defaultPriceMin)
        prices[0] = null;

    if (prices[1] == this.defaultPriceMax)
        prices[1] = null;

    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 bathSlider = $("#" + this.clientID + "_divBathSlider");
    var bathRange = [];
    bathRange[0] = this.getBathValue(bathSlider.slider("values", 0));
    bathRange[1] = this.getBathValue(bathSlider.slider("values", 1));

    if (bathRange[0] == this.defaultBathsMin)
        bathRange[0] = null;

    if (bathRange[1] == this.defaultBathsMax)
        bathRange[1] = null;

    return bathRange;
}

function MiniSearch_getCurrentBeds() {
    var bedSlider = $("#" + this.clientID + "_divBedSlider");
    var bedRange = [];
    bedRange[0] = this.getBedValue(bedSlider.slider("values", 0));
    bedRange[1] = this.getBedValue(bedSlider.slider("values", 1));

    if (bedRange[0] == this.defaultBedsMin)
        bedRange[0] = null;

    if (bedRange[1] == this.defaultBedsMax)
        bedRange[1] = null;

    return bedRange;
}

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);
    }
}

function MiniSearch_reloadPriceSlider() {
    var priceSlider = $("#" + this.clientID + "_divPriceSlider");

    if (this.getCurrentClass() == "RNT" && this.lowestPrice != 100) {
        priceSlider.slider('destroy');
        this.lowestPrice = 100;
        this.highestPrice = 20000;
        this.defaultPriceMin = this.lowestPrice;
        this.defaultPriceMax = this.highestPrice;
        this.loadPriceSlider();
    }
    else if (this.getCurrentClass() != "RNT" && this.lowestPrice != 25000) {
        priceSlider.slider('destroy');
        this.lowestPrice = 25000;
        this.highestPrice = 30000000;
        this.defaultPriceMin = this.lowestPrice;
        this.defaultPriceMax = this.highestPrice;
        this.loadPriceSlider();
    }
}

function ShiftOrEnter(event) {
    return (event.keyCode == 13 || event.keyCode == 16);
}

// ------------------------- End MiniSearch ------------------------------
