﻿(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var self = this;
            var input = this.input = this.element;

            //attach automplete 
            input.autocomplete({
                delay: 0,
                minLength: 3,

                // Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace 
                // the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does 
                //not prevent the menu from closing.
                select: function (event, ui) {
                    self._trigger("selected", event, ui);
                },

                //Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item.
                change: function (event, ui) {
                    self._trigger("changed", event, ui);
                    /*
                    if (!valid) {
                    // remove invalid value, as it didn't match anything
                    $(this).val("");
                    input.data("autocomplete").term = "";
                    return false;
                    }
                    */
                }
            }).addClass("ui-widget ui-widget-content ui-corner-left");

            //custom rendering to group by category.
            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
						.data("item.autocomplete", item)
                        .append(item.groupTitle ? ("<div class='ui-autocomplete-title'><strong>" + item.groupTitle + "</strong></div>") : "")
						.append("<a>" + item.label + "</a>")
						.appendTo(ul);
            };

            //add button
            this.button = $("<button type='button'>&nbsp;</button>")
					.attr("tabIndex", -1)
					.insertAfter(input)
					.button({
					    icons: {
					        primary: "ui-icon-triangle-1-s"
					    },
					    text: false
					})
                    .attr("title", "")
					.removeClass("ui-corner-all")
					.addClass("ui-corner-right ui-button-icon")
					.click(function () {
					    // close if already visible
					    if (input.autocomplete("widget").is(":visible")) {
					        input.autocomplete("close");
					        return;
					    }
					    // work around a bug (likely same cause as #5265)
					    $(this).blur();

					    // search for current value
					    input.autocomplete("option", "minLength", 0);
					    input.autocomplete("search", input.val());
					    input.focus();
					    input.autocomplete("option", "minLength", 3);
					});
        },

        destroy: function () {
            this.button.remove();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);
