﻿/**
    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 + ',#' + PropertyStyleID + ',#' + BedsID + ',#' + BathsID).change(function() { that.UpdateCount(); });
        $('#' + LifestylesID + ',#' + AmenitiesID + ',#' + PropertyTypeID).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 */
        tempArray = $("#" + PropertyTypeID + " input:checkbox:checked ~ label").map(function() { return $(this).text(); }).get();

        // map the selected checkbox options to the proper endeca IDs in the PropertyType lookup table
        for (var i = 0; i < tempArray.length; i++) {
            var dimId = this.PropertyTypeDimVals[tempArray[i]];

            // if the mapped dim val exists (not null) then add it to the URL
            if (dimId) {
                ret += dimId + "+";
            }
        }

        /* 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).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)
            $('#' + LocationID).hide("normal");

        if (element) {
            element.children('input').val('');
            element.hide("normal");
            setTimeout(function() { element.remove(); }, 500);
        }
        else {
            locations.children().remove();
        }

        if (!SkipUpdateCount)
            that.UpdateCount();
    }

    this.HasLocation = function(dimval) {
        return $("#" + LocationID + " ul li input[value='" + dimval + "']").length == 1
    }

    this.toggleLocation = function(dimval) {
        if (this.HasLocation(dimval))
            this.RemoveLocation($("#" + LocationID + " ul li input[value='" + dimval + "']").parent(), false);
        else {
            for (var i = 0; i < autocompleteData.length; i++) {
                if (dimval == autocompleteData[i][1]) {
                    this.AddNewLocation(autocompleteData[i]);
                }
            }
        }
    }
    
    /*------------------------- 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;
});



function BrowseLocationHelper() {
    var that = this;

    var ResponseCache = {};
    
    this.clearParameters = function() {
        this.CountryName = null;
        this.CountryAlternate = null;
        this.CountryRegionName = null;
        this.CountryRegionAlternate = null;
        this.StateName = null;
        this.StateAlternate = null;
        this.StateRegionName = null;
        this.StateRegionAlternate = null;
        this.CityName = null;
        this.CityAlternate = null;
        this.CurrentEndecaDimVal = null;
    }

    this.populateResultsPanel = function(json) {
        // first put together the breadcrumb content
        var content = '';
        content = (this.CountryName ? '<a class="browseLocationLink" href="javascript:void(0)" onclick="objBrowseLocationHelper.clearParameters();objBrowseLocationHelper.fetchData()">' : '<a style="color:#285483">') + this.msgEntireWorld + '</a>';

        if (this.CountryName && this.CountryName != 'null')
            content += " > " + (this.CountryRegionName || this.StateName ? "<a href=\"javascript:void(0)\" class=\"browseLocationLink\" onclick=\"objBrowseLocationHelper.clearParameters();objBrowseLocationHelper.CountryName='" + this.CountryName + "';objBrowseLocationHelper.fetchData();\">" : "<a style=\"color:#285483\">") + (this.CountryAlternate ? this.CountryAlternate : this.CountryName) + "</a>";

        if (this.CountryRegionName && this.CountryRegionName != 'null')
            content += " > " + (this.StateName ? "<a href=\"javascript:void(0)\" class=\"browseLocationLink\" onclick=\"objBrowseLocationHelper.clearParameters();objBrowseLocationHelper.CountryName='" + this.CountryName + "';objBrowseLocationHelper.CountryRegionName='" + this.CountryRegionName + "';objBrowseLocationHelper.fetchData();\">" : "<a style=\"color:#285483\">") + (this.CountryRegionAlternate ? this.CountryRegionAlternate : this.CountryRegionName) + "</a>";

        if (this.StateName && this.StateName != 'null')
            content += " > " + (this.StateRegionName || this.CityName ? "<a href=\"javascript:void(0)\" class=\"browseLocationLink\" onclick=\"objBrowseLocationHelper.clearParameters();objBrowseLocationHelper.CountryName='" + this.CountryName + "';objBrowseLocationHelper.CountryRegionName='" + this.CountryRegionName + "';objBrowseLocationHelper.StateName='" + this.StateName + "';objBrowseLocationHelper.fetchData();\">" : "<a style=\"color:#285483\">") + (this.StateAlternate ? this.StateAlternate : this.StateName) + "</a>";

        if (this.StateRegionName && this.StateRegionName != 'null')
            content += " > " + (this.CityName ? "<a href=\"javascript:void(0)\" class=\"browseLocationLink\" onclick=\"objBrowseLocationHelper.clearParameters();objBrowseLocationHelper.CountryName='" + this.CountryName + "';objBrowseLocationHelper.CountryRegionName='" + this.CountryRegionName + "';objBrowseLocationHelper.StateName='" + this.StateName + "';objBrowseLocationHelper.StateRegionName='" + this.StateRegionName + "';objBrowseLocationHelper.fetchData();\">" : "<a style=\"color:#285483\">") + (this.StateRegionAlternate ? this.StateRegionAlternate : this.StateRegionName) + "</a>";

        if (this.CityName && this.CityName != 'null')
            content += " > <a>" + (this.CityAlternate ? this.CityAlternate : this.CityName) + '</a>';

        $('#BrowseLocationsPopup #headerText').html(content);

        // Now show the list of results.

        content = '<table width="435"><tr>';

//        if (json.RegionDataSet)
//            content += '<tr><td colspan="2" style="font-size:11px; font-weight:bold; text-decoration: underline;color:#285483;">' + (!this.StateName && !this.CountryRegionName ? this.msgBrowseByStates : this.msgBrowseByCities) + '</td></tr><tr>';
        if (json.RegionDataSet)
            content += '<tr><td colspan="2"><a href="javascript:void(0)" class="browseLocationLink" onclick="$(\'.nonRegionHiddenLocations\').show(); $(\'.trShowAllCitiesOrStates\').hide();" style="font-size:11px;font-weight:bold;">' + (!this.StateName && !this.CountryRegionName ? this.msgBrowseByStates : this.msgBrowseByCities) + '</a></td></tr><tr>';

        for (var i = 0; i < json.NonRegionDataSet.length; i++) {
            content += '<td width="40%">';


            if (json.NonRegionDataSet[i].country) {
                content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.NonRegionDataSet[i].dimval) ? 'checked' : '') + ' onmouseover="showTooltip(event,\'' + this.msgAddCountry + '\', 30, -20);" onclick="objSearchHelper.toggleLocation(\'' + json.NonRegionDataSet[i].dimval + '\')" />';
                if (json.NonRegionDataSet[i].hasChildren)
                    content += '<a href="javascript:void(0)" class="browseLocationLink" onmouseover="showTooltip(event,\'' + this.msgBrowseStatesRegions + '\', 30, -20);" onclick="objBrowseLocationHelper.CountryName=\'' + json.NonRegionDataSet[i].country + '\';objBrowseLocationHelper.fetchData();">' + (json.NonRegionDataSet[i].countryAlt ? json.NonRegionDataSet[i].countryAlt : json.NonRegionDataSet[i].country) + '</a>';
                else
                    content += '<span style="color:#285483">' + (json.NonRegionDataSet[i].countryAlt ? json.NonRegionDataSet[i].countryAlt : json.NonRegionDataSet[i].country) + '</span>';
            }
            else if (json.NonRegionDataSet[i].state) {
                content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.NonRegionDataSet[i].dimval) ? 'checked' : '') + ' onmouseover="showTooltip(event,\'' + this.msgAddState + '\', 30, -20);" onclick="objSearchHelper.toggleLocation(\'' + json.NonRegionDataSet[i].dimval + '\')" />';
                if (json.NonRegionDataSet[i].hasChildren)
                    content += '<a href="javascript:void(0)" class="browseLocationLink" onmouseover="showTooltip(event,\'' + this.msgBrowseCities + '\', 30, -20);" onclick="objBrowseLocationHelper.StateName=\'' + json.NonRegionDataSet[i].state + '\';objBrowseLocationHelper.fetchData();">' + (json.NonRegionDataSet[i].stateAlt ? json.NonRegionDataSet[i].stateAlt : json.NonRegionDataSet[i].state) + '</a>';
                else
                    content += '<span style="color:#285483">' + (json.NonRegionDataSet[i].stateAlt ? json.NonRegionDataSet[i].stateAlt : json.NonRegionDataSet[i].state) + '</span>';
            }
            else if (json.NonRegionDataSet[i].city) {
                content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.NonRegionDataSet[i].dimval) ? 'checked' : '') + ' onmouseover="showTooltip(event,\'' + this.msgAddCity + '\', 30, -20);" onclick="objSearchHelper.toggleLocation(\'' + json.NonRegionDataSet[i].dimval + '\')" />';
                if (json.NonRegionDataSet[i].hasChildren)
                    content += '<a href="javascript:void(0)" class="browseLocationLink" onmouseover="showTooltip(event,\'' + this.msgBrowseNeighborhoods + '\', 30, -20);" onclick="objBrowseLocationHelper.CityName=\'' + json.NonRegionDataSet[i].city + '\';objBrowseLocationHelper.fetchData();">' + (json.NonRegionDataSet[i].cityAlt ? json.NonRegionDataSet[i].cityAlt : json.NonRegionDataSet[i].city) + '</a>';
                else
                    content += '<span style="color:#285483">' + (json.NonRegionDataSet[i].cityAlt ? json.NonRegionDataSet[i].cityAlt : json.NonRegionDataSet[i].city) + '</span>';
            }
            else if (json.NonRegionDataSet[i].neighborhood) {
                content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.NonRegionDataSet[i].dimval) ? 'checked' : '') + ' onmouseover="showTooltip(event,\'' + this.msgAddNeighborhood + '\', 30, -20);" onclick="objSearchHelper.toggleLocation(\'' + json.NonRegionDataSet[i].dimval + '\')" />';
                content += '<span style="color:#285483">' + (json.NonRegionDataSet[i].neighborhoodAlt ? json.NonRegionDataSet[i].neighborhoodAlt : json.NonRegionDataSet[i].neighborhood) + '</span>';
            }

            content += "</td>";

            if (i % 2 == 1) {
                content += '</tr><tr';
                if (i >= 3)
                    content += ' class="nonRegionHiddenLocations"';
                content += '>';
            }
        }


        if (json.RegionDataSet) {
            var message = (!this.StateName && !this.CountryRegionName ? this.msgShowAllStates : this.msgShowAllCities);
            content += '<tr class="trShowAllCitiesOrStates"><td colspan="2" style="text-align:right;"><a href="javascript:void(0)" class="browseLocationLink" onclick="$(\'.nonRegionHiddenLocations\').show(); $(\'.trShowAllCitiesOrStates\').hide();" style="font-size:11px;font-weight:bold;">' + message + '</a></td></tr><tr>';
            content += '<tr><td colspan="2"><hr /></td></tr><tr>';
            content += '<tr><td colspan="2" style="font-size:11px; font-weight:bold; text-decoration: underline; color:#285483;"><a href="javascript:void(0)" class="browseLocationLink" onclick="$(\'.regionHiddenLocations\').show(); $(\'.trShowAllRegions\').hide();" style="font-size:11px;font-weight:bold;">' + this.msgBrowseByRegions + '</a></td></tr><tr>';
            
            for (var i = 0; i < json.RegionDataSet.length; i++) {
                content += '<td width="40%">';

                if (!this.StateName) {
                    content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.RegionDataSet[i].dimval) ? 'checked' : '') + ' onmouseover="showTooltip(event,\'' + this.msgAddRegion + '\', 30, -20);" onclick="objSearchHelper.toggleLocation(\'' + json.RegionDataSet[i].dimval + '\')" />';
                    content += '<a href="javascript:void(0)" class="browseLocationLink" onmouseover="showTooltip(event,\'' + this.msgBrowseStates + '\', 30, -20);" onclick="objBrowseLocationHelper.CountryName=\'' + this.CountryName + '\'; objBrowseLocationHelper.CountryRegionName=\'' + json.RegionDataSet[i].region + '\'; objBrowseLocationHelper.fetchData();">' + json.RegionDataSet[i].region + '</a>';
                }
                else {

                    content += '<input type="checkbox" ' + (objSearchHelper.HasLocation(json.RegionDataSet[i].dimval) ? 'checked' : '') + ' onclick="objSearchHelper.toggleLocation(\'' + json.RegionDataSet[i].dimval + '\')" />';
                    content += '<a href="javascript:void(0)" class="browseLocationLink" onmouseover="showTooltip(event,\'' + this.msgBrowseCities + '\', 30, -20);" onclick="objBrowseLocationHelper.CountryName=\'' + this.CountryName + '\'; objBrowseLocationHelper.StateName=\'' + this.StateName + '\'; objBrowseLocationHelper.StateRegionName=\'' + json.RegionDataSet[i].region + '\'; objBrowseLocationHelper.fetchData();">' + json.RegionDataSet[i].region + '</a>';
                }

                content += '</td>';

                if (i % 2 == 1) {
                    content += '</tr><tr';
                    if (i >= 3)
                        content += ' class="regionHiddenLocations"';
                    content += '>';
                }
            }
            content += '</tr><tr class="trShowAllRegions"><td colspan="2" style="text-align:right;"><a href="javascript:void(0)" class="browseLocationLink" onclick="$(\'.regionHiddenLocations\').show(); $(\'.trShowAllRegions\').hide();" style="font-size:11px;font-weight:bold;">' + this.msgShowAllRegions + '</a></td></tr><tr>';
        }

        content += '</tr></table>';

        $('#BrowseLocationsPopup .popupContent').html(content);

        // if regions are present then only show the first 4 results of each dataset
        if (json.RegionDataSet) {
            $('.nonRegionHiddenLocations,.regionHiddenLocations').hide();

            if (json.NonRegionDataSet.length > 4)
                $('.trShowAllCitiesOrStates').show();
            else
                $('.trShowAllCitiesOrStates').hide();

            if (json.RegionDataSet.length > 4)
                $('.trShowAllRegions').show();
            else
                $('.trShowAllRegions').hide();
        }

    }


    this.fetchData = function() {
        var params = {};
        params.op = this.AsyncHandlerOperation;

        if (this.CountryName && this.CountryName != 'null') params.country = this.CountryName;
        if (this.CountryRegionName && this.CountryRegionName != 'null') params.countryRegion = this.CountryRegionName;
        if (this.StateName && this.StateName != 'null') params.state = this.StateName;
        if (this.StateRegionName && this.StateRegionName != 'null') params.stateRegion = this.StateRegionName;
        if (this.CityName && this.CityName != 'null') params.city = this.CityName;

        var cacheKey = JSON.stringify(params);

        if (ResponseCache[cacheKey]) {
            this.populateResultsPanel(ResponseCache[cacheKey]);
        }
        else {
            $('#BrowseLocationsPopup .popupContent').html(this.msgLoading);
            $.getJSON('/AsyncHandler.ashx', params, function(json) { ResponseCache[cacheKey] = json; that.populateResultsPanel(json); });
        }
    }
}
