﻿

function SearchAutoFill(pSelector, pOptions) {
    var _Info = {
        FillPanel : "FillResults",
        FillPanelSel : null,
        FillPanelOuter : null,
        FillPanelOuterSel : null,
        SearchBox : null,
        ResultsPanel : null,
        KeywordServicePage: "/pages/GetKeywords.aspx",
        SearchQueryParam : "Match",
        LimitQueryParam : "Limit",
        SliderSpeed: 150,
        KeyDelayBeforeFill: 200,
        MinKeysBeforeFill: 2,
        MaxListItems: 25,
        ResultsWidthOffset: 2,
        ResultsTopOffset: 2,
        AJAXOptions : {
            type: 'GET',
            dataType: 'xml',
            timeout: 2000,
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) { /* do nothing with the error by default */ }
        }        
    };
    
    var _CloseResultsPanel = false;
    var _bPanelIsOpen = false;
    var _KeysPressed = 0;
    var _baseAJAXOptions = _Info.AJAXOptions;

    $.extend(_Info, pOptions);
    _Info.AJAXOptions = _baseAJAXOptions;
    $.extend(_Info.AJAXOptions, pOptions.AJAXOptions);

    _Info.FillPanelSel = "#" + _Info.FillPanel;
    _Info.FillPanelOuter = _Info.FillPanel + "Outer";
    _Info.FillPanelOuterSel = "#" + _Info.FillPanelOuter;
    
    _Info.SearchBox = $(pSelector);

    if (_Info.SearchBox) {
        PrepareAJAX();
        CreateResultsPanel();

        _Info.SearchBox.keydown(HandleKey);
        _Info.SearchBox.blur(StartClosingResults);
        _Info.SearchBox.focus(StopClosingResults);
    }

    function CreateResultsPanel() {
        _Info.ResultsPanel = $("#" + _Info.FillPanelOuter);

        if (_Info.ResultsPanel == null || _Info.ResultsPanel.length < 1) {
            $("body").append("<div id='" + _Info.FillPanelOuter + "'><div id='" + _Info.FillPanel + "'><div>Inner Div</div></div></div>");
            _Info.ResultsPanel = $("#" + _Info.FillPanelOuter);
            _Info.ResultsPanel.focus(StopClosingResults);
            _Info.ResultsPanel.blur(StartClosingResults);
            _Info.ResultsPanel.hide();
        }
        
        PositionResultsPanel();
    }


    function PositionResultsPanel() {
        var iTop = _Info.SearchBox.position().top + _Info.SearchBox.height() + _Info.ResultsTopOffset;
        var iLeft = _Info.SearchBox.offset().left;

        _Info.ResultsPanel.css("top", iTop).css("left", iLeft);
    }


    // allows for the Escape key to clear the box and close the dialog
    function HandleKey(e) {
        if (_Info.KeywordServicePage == "") {
            return true;
        }
        else {
            var SuppressKey = false;
            switch (e.keyCode) {
                case 27:
                    if (_bPanelIsOpen) {
                        _Info.SearchBox.focus();
                        CloseResultsWindow();
                    } else {
                        _Info.SearchBox.val("");
                    }

                    SuppressKey = true;
                    break;

                case 40:
                    MoveDown();
                    SuppressKey = true;
                    break;

                case 38:
                    MoveUp();
                    SuppressKey = true;
                    break;

                case 13:
                    if (_bPanelIsOpen) {
                        SubmitSearch();
                        SuppressKey = true;
                    }
                    break;
            }

            if (SuppressKey) {
                e.preventDefault();
                e.stopPropagation();
                e.keyCode = 0;
                return false;
            }
            searchChanged();
            return true;
        }
    }


    function searchChanged() {
	    _KeysPressed++;
	    setTimeout(DecrementKeys, _Info.KeyDelayBeforeFill);
    }


    function SubmitSearch() {
        _Info.SearchBox.focus();
        CloseResultsWindow();
        _Info.SearchBox.parent("div").find(":submit").click();
    }


    function MoveUp() {
        if (!_bPanelIsOpen) { return; }
        
        var oCurrentItem = $(_Info.FillPanelSel + " div.AutofillSelected");
        if (oCurrentItem && oCurrentItem.length > 0) {
            oCurrentItem.removeClass("AutofillSelected");
            var oNext = oCurrentItem.prev("div");
            oNext.addClass("AutofillSelected");

        } else {
            $(_Info.FillPanelSel + " div:last").addClass("AutofillSelected");
            _Info.SearchBox.attr("OriginalValue", _Info.SearchBox.val());
            _Info.SearchBox.blur();
        }

        SetSelectedValue();
    }


    function MoveDown() {
        if (!_bPanelIsOpen) { return; }

        var oCurrentItem = $(_Info.FillPanelSel + " div.AutofillSelected");
        if (oCurrentItem && oCurrentItem.length > 0) {
            oCurrentItem.removeClass("AutofillSelected");
            var oNext = oCurrentItem.next("div");
            oNext.addClass("AutofillSelected");
            
        } else {
            $(_Info.FillPanelSel + " div:first").addClass("AutofillSelected");
            _Info.SearchBox.attr("OriginalValue", _Info.SearchBox.val());
            _Info.SearchBox.blur();
            
        }

        SetSelectedValue();
    }


    function SetSelectedValue() {

        var oCurrentItem = $(_Info.FillPanelSel + " div.AutofillSelected a");
        var oVal = oCurrentItem.text()

        if (oVal == null || oVal == '') {
            _Info.SearchBox.val(_Info.SearchBox.attr("OriginalValue"));
            _Info.SearchBox.focus();
        } else {
            _Info.SearchBox.val(oVal);
            oCurrentItem.focus();
        }
    }


    function DecrementKeys() {
	    _KeysPressed--;
	    if (_KeysPressed == 0) { DoAutoFill(); }
    }


    function DoAutoFill() {
        var oTerm = _Info.SearchBox.val();
        if (oTerm && oTerm.length >= _Info.MinKeysBeforeFill) {
            LoadKeywords(oTerm);
        } else {
            StartClosingResults();
        }
    }



    function LoadKeywords(ptext) {
        $.getJSON(_Info.KeywordServicePage + '?' + _Info.SearchQueryParam + '=' + escape(ptext) + '&' + _Info.LimitQueryParam + '=' + _Info.MaxListItems, null, function(data) { PopulateFillPanel(data); });
    }


    function PopulateFillPanel(pKeywords) {
        if (pKeywords && pKeywords.length > 0) {

            $(_Info.FillPanelSel).empty();

		    for (i = 0; i < pKeywords.length; i++) {
		        $(_Info.FillPanelSel).append("<div><a href='#'>" + pKeywords[i] + "</a></div>");
		    }

		    $(_Info.FillPanelSel + " div a").focus(StopClosingResults).blur(StartClosingResults).keydown(HandleKey).click(function(e) {
		        SetSelectedValue();
		        SubmitSearch()
		        e.preventDefault();
		    });

		    $(_Info.FillPanelSel + " div").hover(
		        function() { $(_Info.FillPanelSel + " div").removeClass("AutofillSelected"); $(this).addClass("AutofillSelected"); },
		        function() { $(this).removeClass("AutofillSelected"); }
		    );
    		
            // parse search results
            PositionResultsPanel();

		    if (_bPanelIsOpen == false) {
		        _Info.ResultsPanel.slideDown(_Info.SliderSpeed);
	            _bPanelIsOpen = true;
	        }


	        $(_Info.FillPanelSel + " > div").click(function() {
                _Info.SearchBox.val($(this).text());
                StartClosingResults();
            });
        } else {
           StartClosingResults();
        }
    }

    function PrepareAJAX() {
        $.ajaxSetup(_Info.AJAXOptions);
    }


    // Panel Closing routines - allows the panel to close when focus is lost
    // note - should *not* close the panel if the focus shifts to/from the search to the results
    function StopClosingResults() {
        _CloseResultsPanel = false;
    }

    function StartClosingResults() {
        _CloseResultsPanel = true; 
        setTimeout(CloseResults, 100);
    }

    function CloseResultsWindow() {
        _CloseResultsPanel = true;
        CloseResults();
    }

    function CloseResults() {
        if (_CloseResultsPanel) {
            _Info.ResultsPanel.slideUp(_Info.SliderSpeed);
            _bPanelIsOpen = false;
        }
        _CloseResultsPanel = false;
    }

}

var defSearchText;
defSearchText = "Search for:";
var emptyClass;
emptyClass = 'emptySearchText';

$(document).ready(function() {
    // Set the default text for the search text box.
    var srchInput = $('input[id$="baSearchBar_SearchText"]')[0];
    if (document.activeElement != srchInput)
    {
        srchInput.value = defSearchText;
    }
   

    // Set the onfocus and onblur even handlers for the text box.
    $('input[id$="baSearchBar_SearchText"]')
        .addClass(emptyClass)
        .focus(function() {
            if (this.value == defSearchText) {
                $(this).removeClass(emptyClass);
                this.value = "";
            }
        })
        .blur(function() {
            if (this.value == "") {
                $(this).addClass(emptyClass);
                this.value = defSearchText;
            }
        })
        .keypress(function() {
            var idx = this.value.indexOf(defSearchText);
            if (idx > -1)
            {
                var first = this.value.substring(0, i);
                
                var second;
                if (this.value.length > i + defSearchText.length)
                {
                    second = this.value.substring(i+defSearchText.length);
                }
                this.value = first + second;
            }
            return true;
        });

    $('input[id$="baSearchBar_SearchButton"]')
        .click(function() {
            var searchText
            searchText = $('input[id$="baSearchBar_SearchText"]')[0];
            if (searchText.value == defSearchText) {
                $(searchText).removeClass(emptyClass);
                searchText.value = "";
            }
            WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(this.name, "", true, "", "", false, false));
        });
    
	// Move the search description up to the count string.
	var arr = $("#CCSearchStats"); 
	if (arr.length > 0)
	{
	    var ccss = arr[0];
	    arr = $("#SRST div"); 
	    if (arr.length > 0 && arr[0].innerHTML != null && arr[0].innerHTML != "")
	    {
		    var i = arr[0].innerHTML.lastIndexOf(".");
		    if (i > -1)
		    {
			    arr[0].innerHTML = arr[0].innerHTML.substring(0, i);
		    }
		    arr[0].innerHTML += " " + ccss.innerHTML;
	    }

	    var arr = $("#putSearchHere");
	    if (arr.length > 0) 
	    {
		    arr[0].innerHTML += " " + ccss.innerHTML;
		    $(".ms-PartSpacingVertical").css("margin-top", "0");
	    }

	    ccss.parentNode.removeChild(ccss);
	}
});

