﻿/**
    This object is used in the criteria panel on both the property search and search results page.
*/
function SearchHelper(locationID, lifestylesID, typeForSaleID, typeForRentID, amenitiesID, priceID, propertyTypeID, propertyStyleID, bedsID, bathsID, propertyCountID, viewResultsID)
{    
    /*------------------------- MEMBERS BEGIN  ***/
    var LocationID       = locationID;
    var LifestylesID     = lifestylesID;
    var TypeForSaleID    = typeForSaleID;
    var TypeForRentID    = typeForRentID;
    var AmenitiesID      = amenitiesID;
    var PriceID          = priceID;
    var PropertyTypeID   = propertyTypeID;
    var PropertyStyleID  = propertyStyleID;
    var BedsID           = bedsID;    
    var BathsID          = bathsID;
    var PropertyCountID  = propertyCountID;
    var ViewResultsID    = viewResultsID;
    var CurrencyID;
    var LifestylesDimVals; // this array will hold the endeca Dimensio IDs for the list of lifestyles
    var AmenitiesDimVals; // this array will hold the endeca Dimensio IDs for the list of amenities
    var ForRentDimVal;
    var ForSaleDimVal;
    var AsyncHandlerOperation;
    var CurrencyExchangeRate;
    var PriceRangeForSale;
    var PriceRangeForRent;
    var TextNoMatches = 'There are no properties in the system the match the selected criteria.\nPlease further refine your search and click on this link again.';
    var TextNoMinimum = 'No Minimum';
    var TextNoMaximum = 'No Maximum';
    var TextLoading = 'Loading';
    var that = this;

    var DefaultPropertySearchUrl;
    
    /*------------------------- MEMBERS END  ***/  

    /*------------------------- CONSTRUCTOR BEGIN  ***/ 
    Initialize();
    /*------------------------- CONSTRUCTOR END  ***/


    function Initialize() {
        this.Location       = $('#' + LocationID);
        this.Lifestyle      = $('#' + LifestylesID);
        this.TypeForSale    = $('#' + TypeForSaleID);
        this.TypeForRent    = $('#' + TypeForRentID);
        this.Amenities      = $('#' + AmenitiesID);
        this.Price          = $('#' + PriceID);
        this.PropertyType   = $('#' + PropertyTypeID);
        this.PropertyStyle  = $('#' + PropertyStyleID);
        this.Beds           = $('#' + BedsID);
        this.Baths          = $('#' + BathsID);
        this.PropertyCount  = $('#' + PropertyCountID);
        this.ViewResults    = $('#' + ViewResultsID);
        this.Currency       = $('#' + CurrencyID);
        $('#' + LocationID + ',#' + TypeForSaleID + ',#' + TypeForRentID + ',#' + PropertyTypeID + ',#' + PropertyStyleID + ',#' + BedsID + ',#' + BathsID).change(function() { that.UpdateCount(); });
        $('#' + LifestylesID + ',#' + AmenitiesID).click(function(event) { that.UpdateCount(); });
        this.Price.bind('slidechange', function(event, ui) { that.UpdateCount(); return true; });
    }


    /*------------------------- PRIVATE METHODS BEGIN  ***/ 
    /*------------------------- PRIVATE METHODS END  ***/     

    /*------------------------- PUBLIC METHODS BEGIN  ***/    
    /************************************
    Gets all the selected options from the criteria panel and returns the matching URL for searching Endeca
    ************************************/
    this.GetURL = function() {
        var ret = this.DefaultPropertySearchUrl + "+";
        var forRent = false;

        /* For Rent/For Sale option */
        if ($(TypeForRent).is(":checked")) {
            ret += this.ForRentDimVal + "+";
            forRent = true;
        }
        else {
            ret += this.ForSaleDimVal + "+";
            forRent = false;
        }

        /* Location options */
        var locs = $('#' + LocationID + ' input:hidden').get();
        for (var i = 0; i < locs.length; i++) {
            ret += locs[i].value + '+';
        }

        /* Lifestyles */
        var tempArray = $("#" + LifestylesID + " input:checkbox:checked ~ label").map(function() { return $(this).text(); }).get();

        // map the selected checkbox options to the proper endeca IDs in the lifestyles lookup table
        for (var i = 0; i < tempArray.length; i++) {
            var dimId = this.LifestylesDimVals[tempArray[i]];

            // if the mapped dim val exists (not null) then add it to the URL
            if (dimId) {
                ret += dimId + "+";
            }
        }

        /* Amenities */
        tempArray = $("#" + AmenitiesID + " input:checkbox:checked ~ label").map(function() { return $(this).text(); }).get();

        // map the selected checkbox options to the proper endeca IDs in the amenities lookup table
        for (var i = 0; i < tempArray.length; i++) {
            var dimId = this.AmenitiesDimVals[tempArray[i]];

            // if the mapped dim val exists (not null) then add it to the URL
            if (dimId) {
                ret += dimId + "+";
            }
        }

        /* Property Type */
        if ($(PropertyType).val() != "0")
            ret += $(PropertyType).val() + "+";

        /* Property Style */
        if ($(PropertyStyle).val() != "0")
            ret += $(PropertyStyle).val() + "+";

        /* Beds */
        if ($(Beds).val() != "0")
            ret += $(Beds).val() + "+";

        /* Baths */
        if ($(Baths).val() != "0")
            ret += $(Baths).val() + "+";

        // Remove the trailing plus sign from the N= parameter
        ret = ret.substring(0, ret.length - 1);

        if (!CurrencyID)
            ret += "&curr=USD";
        else
            ret += "&curr=" + $('#' + CurrencyID).val();


        /* Price Ranges (NOTE: this needs to come in last on this function body) */
        var whichRange = forRent ? this.PriceRangeForRent : this.PriceRangeForSale;
        var minPrice = whichRange[Price.slider('option', 'values')[0]].value;
        var maxPrice = Price.slider('option', 'values')[1];
        if (maxPrice > whichRange.length)
            maxPrice = whichRange.length - 1;
        var maxPrice = whichRange[maxPrice].value;

        if (minPrice > 0 || maxPrice != -1) {
            ret += "&Nrs=collection()/record[P_USDPrice >= " + minPrice;

            if (maxPrice != -1)
                ret += " and P_USDPrice <= " + maxPrice;

            ret += "]";
        }

        return ret;
    }
    
    /************************************
    Returns the property count for a given search criteria
    ************************************/
    this.UpdateCount = function() {
        if (that.UpdateCountTimer)
            clearTimeout(that.UpdateCountTimer);

        that.UpdateCountTimer = setTimeout(function() {
            that.UpdateCountTimer = null; //clear the timer

            // Set the counter text to "Loading"
            $(PropertyCount).html(TextLoading);
            
            var queryString = that.GetURL();

            // Append the appropriate async operation identifier
            queryString = "op=" + that.AsyncHandlerOperation + "&" + queryString;

            // uncomment the alert below for debugging the async call
            //alert(queryString);

            $.getJSON("/AsyncHandler.ashx?" + queryString, function(data) { $(PropertyCount).html(data.matchCount); });
        }, 10);

    }
    
    /************************************
    Returns the result set of a search in json format
    ************************************/
    this.ExecuteSearch = function(currencyID) {
        CurrencyID = currencyID;
        var url = this.GetURL();
        
        if($(PropertyCount).html() == "0")
            alert(that.TextNoMatches);
        else   
            window.location.href = 'PropertySearchResults.aspx?' + url ;
    }
    
    
    /************************************
    Change the selected display currency
    ************************************/
    this.ChangeCurrency = function(currencyID) {        
        CurrencyID = currencyID;
        
        var url = this.GetURL();       

        window.location.href = '?' + url + '#searchcontainer' ;    
    }

    this.ClearSearchOptions = function() {
        this.RemoveLocation(null, true);
        $(':checkbox:checked').attr('checked', false);
        TypeForSale[0].checked = true;
        Price.slider('option', 'max', that.PriceRangeForSale.length - 1);
        PropertyType.get(0).selectedIndex = 0;
        PropertyStyle.get(0).selectedIndex = 0;
        Beds.get(0).selectedIndex = 0;
        Baths.get(0).selectedIndex = 0;
        Price.slider("values", 0, 0);
        Price.slider("values", 1, that.PriceRangeForSale.length - 1);
        this.PriceSlide(null, { values: [0, that.PriceRangeForSale.length - 1] });
        this.PropertyIdSearchBox.val('');
    }

    this.PriceSlide = function(event, ui) {
        isForRent = $(TypeForRent).is(":checked");
        var whichRange = isForRent ? that.PriceRangeForRent : that.PriceRangeForSale;

        var startValue = ui.values[0] == 0 ? that.TextNoMinimum : whichRange[ui.values[0]].format;

        var endValue = whichRange[ui.values[1]].value == -1 ? that.TextNoMaximum : whichRange[ui.values[1]].format;

        $("#amount").val(startValue + ' - ' + endValue);
    }

    this.AddNewLocation = function(item) {
        var value = item[0];
        var endecaDimVals = item[1];

        $("#" + LocationID + " ul").show();

        if ($("#" + LocationID + " ul li input[value='" + endecaDimVals + "']").length == 0)
        {
            $("#" + LocationID + " ul").append('<li id="location' + searchCounter + '"><a href="javascript:void(0)" onclick="objSearchHelper.RemoveLocation($(this).parent())"><img width="12" height="12" style="vertical-align:-1px" alt="" src="/images/FindaProperty/minus_img.gif"/></a> ' + value + '<input type="hidden" id="locationValue' + searchCounter + '" value="' + endecaDimVals + '" /></li>');
            $("#location" + searchCounter).hide().show("normal");
            searchCounter++;

            $("#locationTxt").val('');
        }

        that.UpdateCount();
    }

    this.RemoveLocation = function(element, SkipUpdateCount) {
        var locations = $("#" + LocationID + " ul");
        if (locations.children().length == 1 || !element)
            locations.hide("normal");

        if (element) {
            element.children('input').val('');
            element.hide("normal");
            setTimeout(function() { element.remove(); }, 500);
        }
        else {
            locations.children().remove();
        }

        if (!SkipUpdateCount)
            that.UpdateCount();
    }
    
    /*------------------------- PUBLIC METHODS END  ***/    
}

// Variables 
	var opened = true;
	var num = 0;
	var prevText = "";
	var searchCounter = 0;
	var locationSearchTimer;
	

// On Document Ready 
$(document).ready(function() {
    opened = true;
});
