﻿var watchItem;
$.fn.autoComplete = function (options) {
    options = jQuery.extend({
        servicePath: '', // The web service that returns the suggestions
        serviceMethod: '',
        wrapCSSClass: 'autoCompleteWrap',
        listCSSClass: 'autoCompleteList',
        itemCSSClass: 'autoCompleteItem',
        highlightCSSClass: 'autoCompleteHighlight',
        loadingURL: '/images/loading.gif',
        loadingImgClass: 'loading',
        maxResults: 10,
        timeoutDelay: 100
    }, options);

    // Config options
    var servicePath = options.servicePath;
    var serviceMethod = options.serviceMethod;
    var wrapCSSClass = options.wrapCSSClass;
    var itemCSSClass = options.itemCSSClass;
    var highlightCSSClass = options.highlightCSSClass;
    var listCSSClass = options.listCSSClass;
    var loadingURL = options.loadingURL;
    var loadingImgClass = options.loadingImgClass;
    var maxResults = options.maxResults;
    var timeoutDelay = options.timeoutDelay

    var textbox = $(this); // The autocomplete textbox
    var wrapper = $('<div></div>').css('position', 'relative'); // wrapper surrounds the textbox so we can position the list absolutely
    textbox.wrap(wrapper);

    // listwrap surrounds only the list so we can display a loading image while the results are fetched
    var listWrap = $('<div></div>')
        .addClass(wrapCSSClass)
        .insertAfter(textbox)
        .css({
            position: 'absolute',
            top: 0,
            left: 0,
            display: 'none',
            marginTop: textbox.outerHeight(false)
        });

    //The actual <ul> we'll be filling with suggestions
    var autoCompleteList = $('<ul></ul>')
        .addClass(listCSSClass)
        .appendTo(listWrap);

    // Display this while we're fetching results
    var loadingImg = $('<img />').attr({
        'src': loadingURL,
        'alt': 'Loading...'
    }).addClass(loadingImgClass)
    .prependTo(listWrap);


    var autoCompleteIndex = -1;
    var ACTimeout;
    textbox.keyup(function (e) {
        if (textbox.val().length > 2) { // Don't display suggestions until at least 3 letters are typed
            // left=37, Up=38, right=39, down=40, enter=13
            if (e.keyCode == 40) {
                // Select next item down
                autoCompleteSelectNextItem();
            } else if (e.keyCode == 38) {
                // Select next item up
                autoCompleteSelectPrevItem();
            } else if (e.keyCode == 13) {
                // Hide search suggestions
                hideAutoComplete();
            } else {
                clearTimeout(ACTimeout);
                ACTimeout = setTimeout(function () {
                    // Show suggestions
                    loadingImg.show();
                    listWrap.show();
                    jQuery.ajax({
                        type: "POST",
                        url: servicePath + "/" + serviceMethod,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify({ prefixText: textbox.val(), count: 10 }),
                        success: function (data) {
                            loadingImg.hide();
                            var totalItems = data.d.length;
                            if (totalItems < 1) {
                                listWrap.hide();
                            }
                            else {
                                if (maxResults < totalItems) {
                                    totalItems = maxResults;
                                }
                                autoCompleteList.children('li').remove();
                                for (i = 0; i < totalItems; i++) {
                                    var dataItem = data.d[i];
                                    var searchResultPrefix = '';
                                    if (dataItem.type == "PRODUCT") searchResultPrefix = dataItem.code + ": ";
                                    var newLi = $('<li id="' + dataItem.type + '_' + dataItem.code + '">' + searchResultPrefix + dataItem.name + '</li>')
                                        .addClass(itemCSSClass)
                                        .click(function (e) {
                                            hideAutoComplete();
                                            getSearchNavigateUrl($(this).attr('id'));
                                        })
                                        .hover(function () {
                                            $(this).addClass(highlightCSSClass);
                                        }, function () {
                                            $(this).removeClass(highlightCSSClass);
                                        })
                                        .appendTo(autoCompleteList);
                                }
                                watchItem = data;
                                autoCompleteList.show();
                            }
                        }
                    });
                }, timeoutDelay);
            }
        } else {
            // Hide suggestions if there are less than 3 characters in the textbox
            hideAutoComplete();
        }
    });

    function getSearchNavigateUrl(Code) {
        $('#txtToolbarSearch').val('');
        arr = Code.split("_");
        switch (arr[0]) {
            case "PRODUCT":
                DisplayProduct(arr[1]);
                location.hash = "#product/" + arr[1];
                break;
            case "NAVIGATOR":
                SetOptions('navigator,' + arr[1] + ',' + arr[1]);
                location.hash = "#search/navigator," + arr[1];
                break;
            case "NEWS":
                window.location = arr[1];
                break;
            default:
                DisplayPage(arr[1]);
                location.hash = "#page/" + arr[1];
        }
    }

    function highlightAutocompleteItem(itemIndex) {
        autoCompleteList.children('li')
            .removeClass(highlightCSSClass).removeClass('activeACItem')
            .eq(itemIndex).addClass(highlightCSSClass).addClass('activeACItem');
        textbox.val($('li.activeACItem').text());
        /* 
        activeACItem class is used to denote an item that has been selected by the cursors rather than simply hovered over
        (so you don't hover over one, press enter, and it thinks you want to use that as your query)
        */

    }

    function autoCompleteSelectNextItem() {
        var autoCompleteCount = autoCompleteList.children('li').size();
        if (autoCompleteIndex < autoCompleteCount - 1) {
            autoCompleteIndex += 1;
            highlightAutocompleteItem(autoCompleteIndex);
        }
    }

    function autoCompleteSelectPrevItem() {
        var autoCompleteCount = autoCompleteList.children('li').size();
        if (autoCompleteIndex > 0) {
            autoCompleteIndex -= 1;
            highlightAutocompleteItem(autoCompleteIndex);
        }
    }

    function hideAutoComplete() {
        autoCompleteList.children('li').remove();
        listWrap.hide();
        autoCompleteIndex = -1;
    }
}

