﻿/*********************/
/* Global Type-Ahead */
/*********************/

(function ($) { // closure and $ portability

    GlobalJS = {};

    GlobalJS.ShowTypeAhead = function ($typeAheadMenu, elementID) {

        var $searchField = $("input#" + elementID);
        var searchTerm = "";
        var charLength = 0;
        var newLength = 0;
        var lengthChanged = false;
        var qsTimerID = 0;

        $searchField.val("");
        if ($('div#advanced-search').length) {
            id = $searchField.attr("id").substring($searchField.attr("id").length - 1);
            $("input#autoComplete" + id).attr("source", "").val("");
            AdvancedSearchJS.GetPropertiesCount();
        }

        $typeAheadMenu.css('display', 'none');
        $typeAheadMenu.find("#data-table-list table tbody").remove();

        //---- Setting the position of the type-ahead-menu for the Find-A-Location fields
        var txtFieldPos = $searchField.offset();
        var txtFieldWidth = $searchField.width();
        $typeAheadMenu.css({ 'width': txtFieldWidth + 30, 'top': txtFieldPos.top + 25, 'left': txtFieldPos.left - 10 });
        //if ($('div#advanced-search').length) $typeAheadMenu.css({ 'width': txtFieldWidth + 30, 'top': txtFieldPos.top + 25, 'left': txtFieldPos.left - 10 });
        //if ($('div#modify-results').length) $typeAheadMenu.css({ 'width': txtFieldWidth + 30, 'top': txtFieldPos.top - 98, 'left': txtFieldPos.left - 21 });

        //---- Positioning onResize of the window
        $(window).bind('resize.PageEvents', function () {
            var searchBoxPos = $searchField.offset();
            $typeAheadMenu.css('left', searchBoxPos.left - 10);
        });

        //---- Highlighting the search items row "red" by adding a class to them on mouseover
        $typeAheadMenu.find('tr').live("mouseover.PageEvents", 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.PageEvents', function () {
            var moreType = $(this).attr("moreType");
            QuickSearchDialogJS.GetMoreRecords(moreType, searchTerm);
        });

        //---- Hiding the type-ahead-menu when something else is clicked
        $('div#wrap').bind('click.PageEvents', function (evt) {
            if (!$(evt.target).is("a.moreAnchor") && $(evt.target).attr("id") != elementID && $typeAheadMenu.find('tr.selected').length == 1) {
                $('div#wrap').unbind('click.PageEvents');
                $typeAheadMenu.find('tr.selected td').trigger('click.PageEvents');
                $(document).unbind('.PageEvents');
                return;
            }
        });

        //---- Hidinga an empty find-location field in advanced-search if it has no search value
        $searchField.bind('blur.PageEvents', function () {
            if ($('div#advanced-search').length) {
                len = $searchField.attr("id").length;
                id = $searchField.attr("id").substring(len - 1);
                if (id > 1 && $.trim($(this).val()) == "") {
                    $("span#location" + id).css('display', 'none');
                    $('#find-a-location-panel .add-another-location').css('display', 'block');
                }
            }
        });

        //---- Handling the Search functionality
        //onClick or onEnter of a highlighted autocomplete item
        $typeAheadMenu.find('tr.selected td').live('click.PageEvents', function () {
            //console.log('clicked');
            //if ($typeAheadMenu.find('tr.selected').length == 1) {
            $searchField.val($(this).text());
            $searchField.attr('autocpid', $(this).attr("id"));
            $searchField.attr('autocptypeid', $(this).attr("typeid"));
            $searchField.attr('countryid', $(this).attr("countryid"));

            if ($('div#advanced-search').length) {
                id = $searchField.attr("id").substring($searchField.attr("id").length - 1);
                $("input#autoComplete" + id).attr('source', 'find').val($(this).attr("id"));
                AdvancedSearchJS.GetPropertiesCount();
            }

            $typeAheadMenu.css('display', 'none');
            $typeAheadMenu.find("#data-table-list table tbody").remove();
            //}
        });


        var id, timerID;
        //-------- Keyup functionality for the Find-A-Location fields --------//
        $searchField.unbind('keyup.PageEvents').bind('keyup.PageEvents', function (e) {
            searchTerm = $(this).val();
            searchTerm = searchTerm.replace(/^\s+/, "");

            len = $searchField.attr("id").length;
            id = $searchField.attr("id").substring(len - 1);

            //--Checking to see if the user changed the searchTerm and setting the lengthChanged flag
            charLength = searchTerm.length;
            //console.log("charLength=[" + charLength + "] and newLength=[" + newLength + "]");
            if (charLength != newLength) {
                lengthChanged = true;
                //if ($('div#advanced-search').length) {
                //    $("input#autoComplete" + id).attr("source", "").val("");
                //    clearTimeout(timerID);
                //    timerID = setTimeout("AdvancedSearchJS.GetPropertiesCount()", 500);
                //if (charLength == 0) {
                //AdvancedSearchJS.GetPropertiesCount();
                //clearTimeout(timerID);
                //timerID = setTimeout("AdvancedSearchJS.GetPropertiesCount()", 500);
                //}
                //}
                if ($('div#modify-results').length) {
                    $searchField.attr({ "autocpid": "", "autocptypeid": "", "countryid": "" });
                }
                newLength = charLength;
            }
            else {
                lengthChanged = false;
            }


            //--Don't search if there are less than 3 search-chars or if a webID (starting with C) has less than 4 digits
            if ((searchTerm.length < 3) || searchTerm.match(/^[cC][0-9]{2,3}$/)) {
                $typeAheadMenu.css('display', 'none');
                $typeAheadMenu.find("#data-table-list table tbody").remove();
                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');
                }
                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');
                    }
                }
                $(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');
                }
                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');
                    }
                }
                $(this).val($typeAheadMenu.find('.selected td').text());
            }

            //--On clicking Enter, just set the selection
            if (e.keyCode == 13) {  //Enter key
                lengthChanged = false;
                $typeAheadMenu.find('tr.selected td').trigger('click.PageEvents');
            }

            //--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) {
                    //if ($('div#advanced-search').length) $("p.matches").text("");
                    //$("#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 key up functionality

        $searchField.bind("get-uniqueId", function (event, identifier, data) {
            if (identifier == QuickSearchDialogJS.UniqueId) {
                QuickSearchDialogJS.SetAutoCompleteMenus(data);
            }
        });

    }
    // end GlobalJS.ShowTypeAhead

    //Resizing the Featured images and the Grid images
    GlobalJS.ResizeGridImg = function (imgDomEl) {
        $(imgDomEl).resizeto({ width: 316, height: 232 });
    }

    //Resizing the List images
    GlobalJS.ResizeListImg = function (imgDomEl) {
        $(imgDomEl).resizeto({ width: 246, height: 178 });
    }
    

})(jQuery);

