/* ADVANCED SEARCH specific jquery */
/* site specific css for work done for advanced search in july 2011 */
/* move to whatever js file that makes sense */

(function ($) { // closure and $ portability

    $(document).ready(function () {

        if ($('div#advanced-search').length) {
            // setup tabs
            $('.tabs').tabs({
                classNamePanelCurrent: "current-panel"
            });

            // setup multi-selects
            $('.bedrooms-bathrooms select, .country-select, .state-select, .city-select, .neighborhood-select, #type-of-dollar').multiselect({
                multiple: false,
                header: false,
                selectedList: 1,
                height: "auto"
            });

            $(".bedrooms-bathrooms select").multiselect({
                beforeclose: function () {
                    AdvancedSearchJS.GetPropertiesCount();
                }
            });

            $('#property-type-select, #preferred-lifestyle').multiselect({
                header: false,
                noneSelectedText: "Any",
                beforeclose: function () {
                    AdvancedSearchJS.GetPropertiesCount();
                }
            });

            $("#price-col button, #preferred-col button").live("click", function () {
                AdvancedSearchJS.GetPropertiesCount();
            });

            //$('#advanced-search .ui-multiselect-menu').not('.ui-multiselect-single').append('<button type="button" class="select-button"></button>');
            $('#advanced-search .ui-multiselect-menu').not('.ui-multiselect-single').append('<button type="button" class="bt bt-gray select-button"><span>Select</span></button>');
            $('#advanced-search .ui-multiselect-menu .select-button').live("click", function () {
                $('#advanced-search .ui-multiselect-menu').css('display', 'none');
            });


            //----- Handling the money slider and currency
            var currencySign = "$";

            var convertMil = function (amount) {
                milSymbol = "M+";
                if (amount != AdvancedSearchJS.PriceRangeMax) {
                    milSymbol = "M";
                }
                if (amount.toString().match(/[0-9]{7,}$/)) {
                    return (amount / 1000000.0) + milSymbol;
                }
                if (amount >= 100000) {
                    return (amount / 1000.0) + "K+";
                }
                /*
                if (amount.toString().match(/[0-9]{4,}$/)) {
                return (amount / 1000.0) + "K";
                }*/
                if ((amount >= 1000) && (amount < 100000)) {
                    formatted = amount.toString();
                    var expression = new RegExp('([0-9]+)([0-9]{3})');
                    while (expression.test(formatted))
                        formatted = formatted.replace(expression, '$1,$2');
                    amount = formatted;
                }

                return amount;
            };

            // setup slider
            $("#advanced-search .slider-range").slider({
                range: true,
                min: AdvancedSearchJS.PriceRangeMin,
                max: AdvancedSearchJS.PriceRangeMax,
                step: AdvancedSearchJS.PriceRangeStep,
                values: [AdvancedSearchJS.PriceRangeStart, AdvancedSearchJS.PriceRangeEnd],
                slide: function (event, ui) {
                    leftVal = convertMil(ui.values[0]);
                    rightVal = convertMil(ui.values[1]);
                    $("#slider-amount-advanced-search").val(currencySign + leftVal + " - " + currencySign + rightVal);
                }
            });
            $("input#slider-amount-advanced-search").attr("disabled", true).css("text-align", "center");
            minVal = $("#advanced-search .slider-range").slider("values", 0);
            maxVal = $("#advanced-search .slider-range").slider("values", 1);
            $("#slider-amount-advanced-search").val(currencySign + convertMil(minVal) + " - " + currencySign + convertMil(maxVal));
            //another event handler for refreshing the properties counter  
            $("#advanced-search .slider-range").bind("slidechange", function (event, ui) {
                AdvancedSearchJS.GetPropertiesCount();
            });

            $("select#type-of-dollar").multiselect({
                multiple: false,
                click: function (event, ui) {
                    currencySign = "$";
                    if (ui.value != "USD") {
                        currencySign = "";
                    }
                    leftVal = convertMil($("#advanced-search .slider-range").slider("values", 0));
                    rightVal = convertMil($("#advanced-search .slider-range").slider("values", 1));
                    $("#slider-amount-advanced-search").val(currencySign + leftVal + " - " + currencySign + rightVal);
                    var $element = $(event.target);
                },
                beforeclose: function () {
                    AdvancedSearchJS.GetPropertiesCount();
                }
            });

            // the element to reveal can either be specified in the hash of the URL, or in metadata
            $('.enter-specific-price-range').revealNew({
                classShown: 'enter-specific-price-range-shown',
                show: "slideDown", showOptions: { duration: 300, easing: "easeOutQuart" },
                hide: "slideUp", hideOptions: { duration: 300, easing: "easeOutQuart" }
            }).click(function () {
                $('#slider-price-range').toggle();
            });
            //$(".specific-price-ranges input").change(function () {
            //    AdvancedSearchJS.GetPropertiesCount();
            //});

            //--Adding the filterChanged flag to the keyword input textbox
            var charLength = 0;
            var oldLength = 0;
            var lengthChanged = false;
            var qsTimerID;
            $("input#keywords-optional, input#webid").keyup(function (e) {
                charLength = $(this).val().length;
                if (charLength == oldLength) {
                    lengthChanged = false;
                }
                else {
                    lengthChanged = true;
                    $("p.matches").text("");
                    clearTimeout(qsTimerID);
                    qsTimerID = setTimeout(function () {
                        AdvancedSearchJS.GetPropertiesCount()
                    }, 500);
                    oldLength = charLength;
                }
            });

            /*var webIdLen = 0;
            var oldWebIdLen = 0;
            var webIdLenChanged = false;
            $("input#webid").keyup(function (e) {
                webIdLen = $(this).val().length;
                if (webIdLen == oldWebIdLen) {
                    webIdLenChanged = false;
                }
                else {
                    webIdLenChanged = true;
                    $("p.matches").text("");
                    clearTimeout(qsTimerID);
                    qsTimerID = setTimeout(function () {
                        
                    }, 500)
                }
            });*/


            $("button.search").click(function () {
                $("#SearchKeywords").val($("#keywords-optional").val());
                if (!AdvancedSearchJS.HasFilterChanged)
                    return false;
                else
                    $("form#advanced_search").submit();
            });



            //================ Handling the Find-Browse Panels =================//
            // setup shorter named vars
            var $findPanel = $('#find-a-location-panel');
            var $findPanelAddNew = $('#find-a-location-panel .add-another-location');
            var $browsePanel = $('#browse-all-locations-panel');
            var $browsePanelAddNew = $('#browse-all-locations-panel .add-another-location');
            var $browsePanelLocations = $('#browse-all-locations-panel .location');


            // add another location within find-location-panel
            $findPanelAddNew.live('click', function () {
                if ($.trim($findPanel.find("span.inputLabelPair:visible").last().find("input").val()) != "") {
                    $findPanel.find("div.module div").append($findPanel.find('.inputLabelPair:hidden').first());
                    $findPanel.find('.inputLabelPair:hidden').first().css('display', 'block');
                }
                if ($('#find-a-location-panel .inputLabelPair:hidden').length < 1) {
                    $(this).css('display', 'none');
                }
            });

            // add another location within browse-location-panel
            $browsePanelAddNew.live('click', function () {
                setLockedDivs();
                $browsePanel.find('.location:visible').find('.unlocked').css('display', 'none');
                $browsePanel.find('.location:visible').find('.locked').css('display', 'block');
                $browsePanel.find('.location:hidden').first().find('.unlocked').css('display', 'block');
                $browsePanel.find('.location:hidden').first().find('.locked').css('display', 'none');
                $browsePanel.append($browsePanel.find('.location:hidden').first());
                $browsePanel.find('.location:hidden').first().css('display', 'block');
                $browsePanelAddNew.css("display", "none");
            });

            // "edit" link toggling locked and unlocked searched items
            $('div.location .edit').click(function () {
                setLockedDivs();
                fixLocationDisplay();
                $browsePanel.find('.location:visible').find('.unlocked').css('display', 'none');
                $browsePanel.find('.location:visible').find('.locked').css('display', 'block');
                $(this).closest('.locked').toggle().closest('.location').find('.unlocked').toggle();
            });

            // remove location on find-location-panel
            $('#find-a-location-panel .remove').live('click', function () {
                len = $(this).closest('.inputLabelPair').attr("id").length;
                id = $(this).closest('.inputLabelPair').attr("id").substr(len - 1, 1);
                clearLocationSpan(id);
                clearLocationDiv(id);
                $("input#autoComplete" + id).attr("source", "").val("");
                fixLocationDisplay();
                AdvancedSearchJS.GetPropertiesCount();
            });

            // remove location on browse-location-panel
            $('#browse-all-locations-panel .remove').live('click', function () {
                len = $(this).closest('.location').attr("id").length;
                id = $(this).closest('.location').attr("id").substr(len - 1, 1);
                $("input#autoComplete" + id).attr("source", "").val("");
                clearLocationDiv(id);
                clearLocationSpan(id);
                fixLocationDisplay();
                $browsePanel.append($browsePanelAddNew);
                AdvancedSearchJS.GetPropertiesCount();
            });

            var clearLocationDiv = function (id) {
                locationDiv = "div#searched-location" + id;
                $(locationDiv).find(".unlocked select").each(function () {
                    $(this).val("0");
                    resetVal = $(this).find("[value='" + $(this).val() + "']").text();
                    $(this).next().find("span:eq(1)").text(resetVal);
                });
                AdvancedSearchJS.ResetDropDown($("#state" + id), "0", "Select State");
                AdvancedSearchJS.ResetDropDown($("#city" + id), "0", "Select City");
                AdvancedSearchJS.ResetDropDown($("#neighborhood" + id), "0", "Select Neighborhood");
                $(locationDiv).css('display', 'none');
                $(locationDiv).find(".unlocked").css("display", "block");
                //$(locationDiv).find(".search-details").text("");
                //$(locationDiv).find(".locked").css("display", "none");
                $(locationDiv).find("div.locked").css("display", "none").find("div.search-details").text("");
                $(locationDiv).find("a.edit").css("display", "block");
            };

            var clearLocationSpan = function (id) {
                locationSpan = "span#location" + id;
                $(locationSpan).find("input").val("");
                if (id > 1) {
                    $(locationSpan).css("display", "none");
                }
                $findPanelAddNew.css('display', 'block');
            };

            //Converts data from the unlocked-selected-options to the locked phrase
            var setLockedDivs = function () {
                $browsePanelLocations.each(function () {
                    var index = $(this).attr("id").substr($(this).attr("id").length - 1, 1);
                    if ($("input#autoComplete" + index).attr("source") == "browse") {
                        var vals = new Array();
                        idx = 0;
                        for (i = 0; i < 4; i++) {
                            var option = $(this).find('select').eq(i).find('option:selected').val();
                            var optionVal = "";
                            if (option > 0) {
                                var optionVal = $(this).find('select').eq(i).find('option:selected').text();
                                if (optionVal != "") {
                                    vals[idx] = optionVal;
                                    idx++;
                                }
                            }
                        }
                        vals.reverse();
                        mainVal = vals.join(", ");
                        $(this).find('.search-details').text(mainVal);
                        if (mainVal == "") {
                            $("input#autoComplete" + index).attr("source", "").val("");
                            $(this).css("display", "none");
                            $(this).find('.unlocked').css('display', 'block');
                            $(this).find('.locked').css('display', 'none');
                            $browsePanelAddNew.css('display', 'none');
                        }
                        else {
                            //if ($('#browse-all-locations-panel .location:hidden').length >= 1) {
                            //    $('#browse-all-locations-panel .add-another-location').css('display', 'block');
                            //}
                        }
                    }
                });
            };

            $("li.browse-all-locations").live('click', function () {
                setLocationData("left2right");
            });
            $("li.find-a-location-tab").live('click', function () {
                setLocationData("right2left");
            });

            var setLocationData = function (direction) {
                if (direction == "left2right") {
                    $("li#find-a-location-panel span.inputLabelPair input").each(function () {
                        fieldValue = $.trim($(this).val());
                        locationIndex = $(this).parent().attr("id").substring($(this).parent().attr("id").length - 1);
                        locationDiv = "div#searched-location" + locationIndex;
                        if (fieldValue == "") {
                            $("input#autoComplete" + locationIndex).val("").attr("source", "");
                            clearLocationDiv(locationIndex);
                        }
                        //If autocompleteid is set AND the find-tab set this id, send value to the detailDiv
                        else if ($("input#autoComplete" + locationIndex).val() != "" && $("input#autoComplete" + locationIndex).attr("source") == "find") {
                            $(locationDiv + " div.search-details").text(fieldValue);
                            setLocationDisplay(locationDiv, locationIndex, direction);
                        }
                    });
                    setLocationDivOptions();
                    fixLocationDisplay();
                }
                else {
                    $("li#browse-all-locations-panel div.unlocked").each(function () {
                        locationIndex = $(this).parent().attr("id").substring($(this).parent().attr("id").length - 1);
                        locationSpan = "span#location" + locationIndex;
                        setLockedDivs();    //Handles the delay that gives wrong info
                        //Set field value if autocompleteid is set AND the browse-tab set this value
                        if ($("input#autoComplete" + locationIndex).val() != "" && $("input#autoComplete" + locationIndex).attr("source") == "browse") {
                            lockedVal = $(this).parent().find("div.search-details").text();
                            $(locationSpan + " input").val(lockedVal);
                            setLocationDisplay(locationSpan, locationIndex, direction);
                        }
                        else if ($("input#autoComplete" + locationIndex).val() == "" && $("input#autoComplete" + locationIndex).attr("source") == "") {
                            clearLocationSpan(locationIndex);
                        }
                    });

                    //If there are no hidden inputs, hide the add-new-link
                    if ($('li#find-a-location-panel span.inputLabelPair:hidden').length < 1) {
                        $findPanelAddNew.css('display', 'none');
                    }
                }
            };

            var setLocationDivOptions = function () {
                pos = 0;
                SwitchDataArray = {};
                $("li#find-a-location-panel span.inputLabelPair input").each(function () {
                    locationIndex = $(this).parent().attr("id").substring($(this).parent().attr("id").length - 1);

                    //If autocompleteid is set AND the find-tab set this id, convert data to unlocked options
                    if ($("input#autoComplete" + locationIndex).val() != "" && $("input#autoComplete" + locationIndex).attr("source") == "find") {
                        fieldValue = $.trim($(this).val());
                        autoCpID = $("input#location-postal-webid" + locationIndex).attr("autocpid");
                        autoCpTypeID = $("input#location-postal-webid" + locationIndex).attr("autocptypeid");
                        //countryID = $("input#location-postal-webid" + locationIndex).attr("countryID");
                        locationDiv = "div#searched-location" + locationIndex;
                        //Do for Cities, Countries, Regions, but not Properties or Postal Codes
                        if (autoCpTypeID != 11 && autoCpTypeID != 8) {
                            //Setting up the data for this autocomplete phrase
                            optionsRay = fieldValue.split(", ");
                            optionsRay.reverse();
                            var SwitchData = { locationIndex: locationIndex,
                                itemArray: optionsRay,
                                country_id: 0,
                                state_id: 0,
                                city_id: 0,
                                neighborhood: 0
                            };

                            //Displaying the country for this autocomplete phrase
                            locationDiv = "div#searched-location" + locationIndex;
                            optionID = $(locationDiv + " select:eq(0) option").filter(function () { return $(this).text() == optionsRay[0] }).val();
                            $(locationDiv + " select:eq(0)").next(".ui-multiselect").find("span:eq(1)").text(optionsRay[0]);
                            $(locationDiv + " select:eq(0)").val(optionID);
                            SwitchData.country_id = optionID;   //autocompleteID of the country, the 1st portion of the autocomplete item
                            SwitchDataArray[pos++] = SwitchData;
                        }
                    }
                });
                //Simulating the click-event to populate the states
                if (pos > 0) {
                    AdvancedSearchJS.Switching = true;
                    current = 0;
                    AdvancedSearchJS.OnClickCountry(); //Call this to populate the states
                    //After each autocomplete phrase is successfully converted to select-options, the edit-link is shown
                }
            };

            var setLocationDisplay = function (locationElement, locationIndex, direction) {
                if (direction == "left2right") {
                    //FindPanel passed data to browsePanel, so hide the edit-link and show the detailDiv
                    locationDiv = locationElement;
                    $(locationDiv + " div.unlocked").css('display', 'none');
                    $(locationDiv + " div.locked a.edit").css('display', 'none');
                    $(locationDiv + " div.locked").css('display', 'block');
                }
                else {
                    //BrowsePanel passed data to findPanel, so show the span and disable its input
                    locationSpan = locationElement;
                    $("li#find-a-location-panel " + locationSpan).css("display", "block");
                }
            };

            var fixLocationDisplay = function () {
                $browsePanel.find("div.location").each(function () {
                    locationData = $(this).find("div.search-details").text();
                    if (locationData == "" && $(this).attr("id") == "searched-location1") {
                        $(this).find(".locked").css("display", "none");
                        $(this).find(".unlocked").css("display", "block");
                        $(this).css("display", "block");
                        $browsePanelAddNew.css("display", "none");
                    }
                    else if (locationData == "" || ($(this).find("div.locked").is(":visible") && locationData == "")) {
                        $(this).css("display", "none");
                        $(this).find(".locked").css("display", "none");
                        $(this).find(".unlocked").css("display", "block");
                        $browsePanelAddNew.css("display", "none");
                    }
                    else if (locationData != "") {
                        $(this).find(".unlocked").css("display", "none");
                        $(this).find(".locked").css("display", "block");
                        $(this).css("display", "block");
                    }
                });

                //Make sure that the add-browse-link shows if there is no open option-set
                if ($('#browse-all-locations-panel .unlocked:visible').length < 1) {
                    //$browsePanel.find('.location:hidden').first().css('display', 'block');
                    $browsePanel.append($browsePanelAddNew);
                    $browsePanelAddNew.css("display", "block");
                }

                //If there are no hidden locationDivs, hide the add-new-link
                if ($('#browse-all-locations-panel .location:hidden').length < 1) {
                    $browsePanelAddNew.css('display', 'none');
                }
            };

            //======== Handling the Type-ahead-Menu ========//
            //$("input.text-field").not('input#keywords-optional').focus(function () {
            $("input.quick-search-page-field").focus(function () {
                $(document).unbind(".QSDialogEvents");
                $(document).unbind(".PageEvents");
                GlobalJS.ShowTypeAhead($('div#type-ahead-menu'), $(this).attr("id"));
            });

        } // end if (#advanced-search-bg)

    }); //end document-ready

})(jQuery);
