﻿$.widget("custom.more", $.ui.autocomplete, {

    _renderMenu: function (ul, items) {
        
        var self = this;

        $.each(items, function (index, item) {
            if (item.category == "search") {
                self._renderSearchItem(ul, item)
            } else {
                self._renderItem(ul, item);
            }

        });
    },

    _renderItem: function (ul, item) {
        return $("<li></li>")
			.data("item.autocomplete", item)
			.append("<a href=' " + item.url + "'>" + this._highlightText(item.label, this.term) + "</a>")
			.appendTo(ul);
    },

    _renderSearchItem: function (ul, item) {
        return $("<li></li>")
			.data("item.autocomplete", item)
			.append("<a style='color:red;' href=' " + item.url + "'>" + item.label + "</a>")
			.appendTo(ul);
    },

    _highlightText: function (haystack, needle) {

        tmpHaystack = haystack.toLowerCase();
        tmpNeedle = needle.toLowerCase();


        pos1 = tmpHaystack.indexOf(tmpNeedle);
        pos2 = pos1 + tmpNeedle.length;

        if (pos1 >= 0) {

            tmpNeedle = "<span style='color: red'>" + haystack.substr(pos1, pos2-pos1) + "</span>";

            return haystack.substr(0, pos1) + tmpNeedle + haystack.substr(pos2);


        }

        return haystack;

    }

});




$(document).ready(function () {


    var peopleQuickSearchCharNum = 3;
    var peopleQuickSearch = $("#PeopleQuickSearchFormValueName");

    peopleQuickSearch.more({

        source: function (request, response) {
            $.ajax({
                url: "/Ajax/PeopleQuickSearch?term=" + request.term,
                success: function (data) {
                    response(data);
                }
            })
        },
        minLength: peopleQuickSearchCharNum,
        select: function (event, ui) {
            window.location.href = ui.item.url;
        }

    });



});
