/*
 * jQuery UI Combobox
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.button.js
 *	jquery.ui.position.js
 *	jquery.ui.autocomplete.js
 */
(function($) {
	$.widget("ui.combobox", {
		_init: function() {
			var self = this;
			var select = this.element.hide();
			var input = $("<input />")
				.val($(this.element).hasClass('select')?$("option:selected", this.element).text():'')
				.insertAfter(select)
				.autocomplete({
					source: function(request, response) {
						var matcher = new RegExp(request.term, "i");
						response(select.children("option").map(function() {
							var text = $(this).text();
							if (this.value && (!request.term || matcher.test(text)))
								return {
									id: this.value,
									label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
									value: text
								};
						}));
					},
					delay: 0,
					select: function(event, ui) { 
						if (!ui.item) {
							$(this).val("");
							return false;
						}
						select.val(ui.item.id);
						select.trigger('change');
						self._trigger("change", event, {
							item: select.find("[value='" + ui.item.id + "']")
						});						
					},
					minLength: 0
				})
				.addClass("ui-widget ui-widget-content ui-corner-left");
			$("<button>&nbsp;</button>")
			.attr("tabIndex", -1)
			.attr("title", "Show All Items")
			.insertAfter(input)
			.button({
				icons: {
					primary: "ui-icon-triangle-1-s"
				},
				text: false
			}).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 false;
				}
				// pass empty string as value to search for, displaying all results
				input.autocomplete("search", "");
				input.focus();
				return false;
			});
		}
	});

})(jQuery);
