/************************* Script for the Quick-Search functionality**************************/
// ===== 08-10-11 - Updated to [christiesgreatestates-20110809] =====//

//=======================================================================================//
//============================== Front-End-related Script ===============================//
//=======================================================================================//
//var qsTimerID;

(function ($) { // closure and $ portability

    $(document).ready(function () {

        /*****************/
        /* slider plugin */
        /*****************/

        //Setting the $-sign when the currency is USD. Removing it otherwise
        var currencySign = "$";
        $("select#dollar").multiselect({
            multiple: false,
            click: function (event, ui) {
                currencySign = "$";
                if (ui.value != "USD") {
                    currencySign = "";
                }
                leftVal = convertMil($("#slider-range").slider("values", 0));
                rightVal = convertMil($("#slider-range").slider("values", 1));
                $("#slider-amount").val(currencySign + leftVal + " - " + currencySign + rightVal);
            }
        });

        var convertMil = function (amount) {
            milSymbol = "M+";
            if (amount != QuickSearchDialogJS.PriceRangeMax) {
                milSymbol = "M";
            }
            if (amount.toString().match(/[0-9]{7,}$/)) {
                return (amount / 1000000.0) + milSymbol;
            }
            return amount;
        };

        $("#slider-range").slider({
            range: true,
            min: QuickSearchDialogJS.PriceRangeMin,
            max: QuickSearchDialogJS.PriceRangeMax,
            step: QuickSearchDialogJS.PriceRangeStep,
            values: [QuickSearchDialogJS.PriceRangeMin, QuickSearchDialogJS.PriceRangeMax],
            slide: function (event, ui) {
                leftVal = convertMil(ui.values[0]);
                rightVal = convertMil(ui.values[1]);
                $("#slider-amount").val(currencySign + leftVal + " - " + currencySign + rightVal);
            }
        });
        $("#slider-amount").attr("disabled", true).css("text-align", "center");
        //Default range on display
        minVal = $("#slider-range").slider("values", 0);
        maxVal = $("#slider-range").slider("values", 1);
        $("#slider-amount").val(currencySign + convertMil(minVal) + " - " + currencySign + convertMil(maxVal));


        //===== Additions from new changes to the site - Updated to [christiesgreatestates-20110809] =====//
        /********************************/
        /* multi select dropdown plugin */
        /********************************/
        $('#property-type-menu-form select#property-type').multiselect({
            header: false,
            noneSelectedText: "Any",
            selectedList: 1,
            height: "auto",
            //minWidth: 231
            minWidth: 223
        });

        $('#property-type-menu-form select#lifestyle').multiselect({
            header: false,
            noneSelectedText: "Any",
            selectedList: 1,
            height: "auto",
            //minWidth: 231
            minWidth: 223
        });

        //$('.ui-multiselect-menu').not('.ui-multiselect-single').append('<button type="button" class="select-button"></button>');
        $('.ui-multiselect-menu').not('.ui-multiselect-single').append('<button type="button" class="bt-select bt bt-gray"><span><b class="arrow right">Select</b></span></button>');

        $('#property-type-menu-form select#dollar').multiselect({
            multiple: false,
            header: false,
            noneSelectedText: "Select an option",
            selectedList: 1,
            height: "auto",
            minWidth: 58
        });

        //$('.ui-multiselect-menu .select-button').live("click", function () {
        $('.ui-multiselect-menu .bt-select').live("click", function () {
            $(this).parent().siblings('.ui-multiselect').click();
        });


        /*******************/
        /* checkbox groups */
        /*******************/
        $.fn.checkboxGroup = function () {
            return this.each(function () {
                var update = function ($el) {
                    if ($el.is(":checked")) {
                        $el.closest("label").addClass("checked");
                    } else {
                        $el.closest("label").removeClass("checked");
                    }
                };

                $(this).find("input")
                                    .click(function () { update($(this)) })
                                    .each(function () { update($(this)) });
            });
        };
        $('.checkbox-group').checkboxGroup();

        $.fn.radioGroup = function () {
            var $container = $(this);
            return this.each(function () {
                var update = function ($el) {
                    $container.find("label").removeClass("checked");
                    $el.closest("label").addClass("checked");
                };

                $(this).find("input")
                                    .click(function () { update($(this)) })
                                    .find(":checked").each(function () { update($(this)) });
            });
        };
        $('.radio-group').radioGroup();
        //==================================================================================//


        /******************************/
        /* Type-Ahead Search Box Menu */
        /******************************/
        var propertyTypeMenuPos = {};
        //---- The element to reveal can either be specified in the hash of the URL, or in metadata
        $('input#quickSearchTextBox').revealNew({
            triggerEvent: "focus",
            show: "fadeIn", showOptions: { duration: $.fd(250) }
        })
        //---- Positioning the property-type-menu and the type-ahead-menu
        .bind("focus", function () {
            $(document).unbind(".PageEvents");
            $(document).unbind(".QSDialogEvents");
            var $propertyTypeMenu = $('#property-type-menu');
            if ($(this).val().length < 3) {
                $propertyTypeMenu.css('display', 'block');
                propertyTypeMenuPos = $propertyTypeMenu.position();
            }
            else {
                $propertyTypeMenu.css('display', 'none');
            }
            $('div#type-ahead-menu').css({ 'width': $propertyTypeMenu.width(), 'top': propertyTypeMenuPos.top, 'left': propertyTypeMenuPos.left });
            QuickSearchDialogJS.ShowTypeAhead($('div#type-ahead-menu'), $(this).attr("id"), $propertyTypeMenu);
        });


        QuickSearchDialogJS.ShowTypeAhead = function ($typeAheadMenu, elementID, $propertyTypeMenu) {

            var $searchField = $("input#" + elementID);
            var searchTerm = "";
            var charLength = 0;
            var newLength = 0;
            var lengthChanged = false;
            var qsTimerID = 0;
            var itemHighlighted = false;

            $typeAheadMenu.css('display', 'none');
            $typeAheadMenu.find("#data-table-list table tbody").remove();

            if (elementID == "noResultsQuickSearch") {
                txtFieldPos = $("div.input-search-wrap").offset();
                txtFieldWidth = $("div.input-search-wrap").width();
                $typeAheadMenu.css({ 'width': txtFieldWidth + 22, 'top': txtFieldPos.top + 30, 'left': txtFieldPos.left - 10 });
            }

            //---- Positioning onResize of the window
            $(window).bind('resize.QSDialogEvents', function () {
                var searchBoxPos = $searchField.offset();
                $('#property-type-menu, #type-ahead-menu').css('left', searchBoxPos.left - 4);
            });

            //---- Highlighting the search items row "red" by adding a class to them on mouseover
            $typeAheadMenu.find('tr').live("mouseover.QSDialogEvents", function () {
                $typeAheadMenu.find('tr').removeClass("selected");
                $(this).addClass("selected");
                $searchField.val($(this).find('td').text());
            });

            //---- Getting more records when the user clicks the "See more" link
            $typeAheadMenu.find("a.moreAnchor").unbind("click").bind('click.QSDialogEvents', function () {
                var moreType = $(this).attr("moreType");
                QuickSearchDialogJS.GetMoreRecords(moreType, searchTerm);
            });

            //---- binding a click to close the search menu onmouseout, unbinding when mouseover ----//
            /*$searchField.bind('mouseout.QSDialogEvents', function () {
            $('div#wrap').bind('click.QSDialogEvents', function (evt) {
            if (elementID == "quickSearchTextBox") $propertyTypeMenu.css('display', 'none');
            $typeAheadMenu.css('display', 'none');
            $(document).unbind('.QSDialogEvents');
            });
            });
            $searchField.bind('mouseover.QSDialogEvents', function () {
            $('div#wrap').unbind('click.QSDialogEvents');
            });*/

            //---- Hiding the type-ahead-menu when something else is clicked
            $('div#wrap').unbind("click").bind('click.QSDialogEvents', function (evt) {
                if (!$(evt.target).is("a.moreAnchor") && $(evt.target).attr("id") != elementID) {
                    if (elementID == "quickSearchTextBox") $propertyTypeMenu.css('display', 'none');
                    $typeAheadMenu.css('display', 'none');
                    $(document).unbind('.QSDialogEvents');
                }
            });

            $typeAheadMenu.find("#data-table-list table").bind('mouseover.QSDialogEvents', function () {
                itemHighlighted = true;
            });


            //---- Handling the Search functionality
            //onClick or onEnter of a highlighted autocomplete item
            $typeAheadMenu.find("tr.selected td").live("click.QSDialogEvents", function () {
                $typeAheadMenu.css('display', 'none');
                QuickSearchDialogJS.QuickSearch($(this).attr("id"), $(this).attr("typeid"), $(this).attr("propertyid"));
                itemHighlighted = false;
                return false;
            });
            //onClick of the quicksearch search-icon
            $('#hlbtnQuickSearch').bind('click.QSDialogEvents', function () {
                $typeAheadMenu.css('display', 'none');
                if (itemHighlighted) var chosenAutoCompleteId = $(thisTypeMenu + " ul#data-table-list tr.selected td").attr("id");
                //so if user didn't highlight anything, chosenAutoCompleteId => undefined
                //QuickSearchDialogJS.QuickSearch(chosenAutoCompleteId);
                if (searchTerm.length > 2) {
                    QuickSearchDialogJS.QuickSearch(chosenAutoCompleteId, $(this).attr("typeid"), $(this).attr("propertyid"));
                }
                return false;
            });
            //onClick of the search-button
            $("button.search-button").bind('click.QSDialogEvents', function () {
                QuickSearchDialogJS.QuickSearch();  //no autocomplete data used in this search
                return false;
            });


            //---- Handling the type-ahead-menu functionality upon key-press
            $searchField.unbind('keyup.QSDialogEvents').bind('keyup.QSDialogEvents', function (e) {
                searchTerm = $(this).val();
                searchTerm = searchTerm.replace(/^\s+/, "");

                //--Checking to see if the user changed the searchTerm and setting the lengthChanged flag
                charLength = searchTerm.length;
                if (charLength != newLength) {
                    lengthChanged = true;
                    newLength = charLength;
                }
                else {
                    lengthChanged = false;
                }

                //--Handling the display of the property-type-menu and the type-ahead-menu
                //If there are < 3 chars, show the property-type-menu and hide the type-ahead-menu
                if (searchTerm.length < 3) {
                    $typeAheadMenu.css('display', 'none');
                    $typeAheadMenu.find("#data-table-list table tbody").remove();
                    if (elementID == "quickSearchTextBox") $propertyTypeMenu.css('display', 'block');
                    itemHighlighted = false;
                    return;
                }
                else {
                    if (elementID == "quickSearchTextBox") $propertyTypeMenu.css('display', 'none');
                }
                //Also hide the type-ahead-menu if a webID (starting with C) has less than 4 digits
                if (searchTerm.match(/^[cC][0-9]{2,3}$/)) {
                    $typeAheadMenu.css('display', 'none');
                    $typeAheadMenu.find("#data-table-list table tbody").remove();
                    itemHighlighted = false;
                    return;
                }

                //--Handling the UP and DOWN keys for scrolling through the autocomplete results
                var oldSelected = $typeAheadMenu.find('.selected');
                if (e.keyCode == 40) { //arrow down
                    if (oldSelected.next('tr').text() != "") {
                        oldSelected.removeClass('selected');
                        oldSelected.next('tr').addClass('selected');
                        itemHighlighted = true;
                    }
                    else {
                        //to avoid selection on hidden object -> use nextAll & prevAll instead of next & prev
                        var closestTableFirstTr = oldSelected.closest('li').nextAll('li:visible').first().find('table tr:first');
                        //var closestTableFirstTr = oldSelected.closest('li').next('li').find('table tr:first'); =>From search-result-quickSearch.js
                        if (closestTableFirstTr.text() != "") {
                            oldSelected.removeClass('selected');
                            closestTableFirstTr.addClass('selected');
                            itemHighlighted = true;
                        }
                    }
                    $(this).val($typeAheadMenu.find('.selected td').text());
                }

                if (e.keyCode == 38) { //arrow up
                    if (oldSelected.prev('tr').text() != "") {
                        oldSelected.removeClass('selected');
                        oldSelected.prev('tr').addClass('selected');
                        itemHighlighted = true;
                    }
                    else {
                        var closestTableLastTr = oldSelected.closest('li').prevAll('li:visible').first().find('table tr:last');
                        //var closestTableLastTr = oldSelected.closest('li').prev('li').find('table tr:last'); =>From search-result-quickSearch.js
                        if (closestTableLastTr.text() != "") {
                            oldSelected.removeClass('selected');
                            closestTableLastTr.addClass('selected');
                            itemHighlighted = true;
                        }
                    }
                    $(this).val($typeAheadMenu.find('.selected td').text());
                }

                //--Activating the Search button on clicking Enter
                if (e.keyCode == 13) {  //Enter key
                    clearTimeout(qsTimerID);
                    $('#hlbtnQuickSearch').trigger('click.QSDialogEvents');
                    return;
                }

                //--If the user presses any key other than UP or DOWN
                if ((e.keyCode != 40) && (e.keyCode != 38)) {
                    //if there are 3 or more characters and the user changed the search-chars, query for its autocomplete results
                    if (searchTerm.length > 2 && lengthChanged) {
                        //$("#data-table-list table tbody").remove();
                        //$("#data-table-list table").parent().hide();
                        //$typeAheadMenu.css('display', 'none');
                        clearTimeout(qsTimerID);
                        qsTimerID = setTimeout(function () {
                            QuickSearchDialogJS.GetAutoCompleteItemsByUniqueID('GetSearchBoxAutoCompleteByLocation',
                                                                            searchTerm,
							                                                QuickSearchDialogJS.InitNbDisplayItems,
							                                                $searchField, //QuickSearchDialogJS.SetAutoCompleteMenus,
                                                                            QuickSearchDialogJS.error);
                        }, 500);
                    }
                }
            });
            //end keyUp event code

            $searchField.bind("get-uniqueId", function (event, identifier, data) {
                if (identifier == QuickSearchDialogJS.UniqueId) {
                    QuickSearchDialogJS.SetAutoCompleteMenus(data);
                }
            });

        };
        //end QuickSearchJS-Type-ahead()

    });  //End document-ready

})(jQuery);

