	(function( $ ) {
    $.widget( "ui.combobox", {
        _create: function() {
            var self = this,
                select = this.element.hide(),
                selected = select.children( ":selected" ),
                value = selected.val() ? selected.text() : "";
            var tabindex = select.attr("tabindex");
            var input = this.input = $( "<input>" )
                .insertAfter( select )
                .val( value )
                .autocomplete({
                    bullet: (this.options.bullet) ? this.options.bullet : null,
                    delay: 0,
                    minLength: 0,
                    autoFocus: true,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( select.find( "option" ).map(function() {
                                optgroup = $(select).find('option[value="'+this.value+'"]').parent('optgroup');
                                if (optgroup.length == 0) {
                                    var item_category = 0;
                                } else {
                                    var item_category = optgroup.attr('label');
                                }
                                var text = $( this ).text();
                                if ( this.value && ( !request.term || matcher.test(text.replace(window.amsCarrierStationAppendix, "")) || matcher.test(item_category) ) )
                                    return {
                                        label: !request.term ? text : text.replace(
                                            new RegExp(
                                                "(?![^&;]+;)(?!<[^<>]*)(" +
                                                $.ui.autocomplete.escapeRegex(request.term) +
                                                ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                            ), "<strong>$1</strong>" ),
                                        value: text,
                                        category: item_category,
                                        newClass: $(this).attr('class'),
                                        option: this
                                    };
                        }) );
                    },
                    select: function( event, ui ) {
                        ui.item.option.selected = true;
                        self._trigger( "selected", event, {
                            item: ui.item.option
                        });
                    },
                    change: function( event, ui ) {
                        if ( !ui.item ) {
                            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                                valid = false;
                            select.children( "option" ).each(function() {
                                if ( $( this ).text().match( matcher ) ) {
                                    this.selected = valid = true;
                                    return false;
                                }
                            });
                            if ( !valid ) {
                                // remove invalid value, as it didn't match anything
                                //$( this ).val( "" ); // jakykoli jiz napsany text chceme v inputu ponechat
                                select.val( "" );
                                input.data( "autocomplete" ).term = "";
                                return false;
                            }
                        }
                    }
                })
                .focus(function() {
                	var selected = $(select).find("option:selected");
                	// je vybrano "-- nevybrano --" a soucasne v poli je textova hodnota "-- nevybrano --"
                	if (selected.val() == "" && $(this).val() == $(selected).text()) {
                		$(this).val("");
                	}
                	else {
                		$(this).select();
                	}
                })
				.bind("autocompleteopen", function(event, ui){
					//find the currently selected item and highlight it in the list
					var opt = $(select).find("option:selected");
					input.data("autocomplete").widget().children('li.ui-menu-item').each(function() {		
						var $li = $(this);
						if ($li.data("item.autocomplete").option.value == opt.attr("value")) {
							input.data("autocomplete").menu.activate(event,$li);
							return false;
						}
					});
				})
                .addClass( "ui-widget ui-widget-content ui-corner-left" )
                .attr("tabindex", tabindex);
      
      input.val( $(select).find("option:selected").text());

            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                if (this.options.bullet) {
                    bullet = '?';
                } else {
                    bullet = '';
                }
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a class='"+ item.newClass +"'>" + bullet + item.label + "</a>" )
                    .appendTo( ul );
            };

            input.data( "autocomplete" )._renderMenu = function( ul, items ) {
                var self = this,
                    currentCategory = "";
                $.each( items, function( index, item ) {
                    if (item.category != 0) {
                        if ( item.category != currentCategory ) {
                            ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                            currentCategory = item.category;
                        }
                    }
                    self._renderItem( ul, item );
                });
            };

            this.button = $( "<button type=\"button\">?</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;
                    }

                    // pass empty string as value to search for, displaying all results
                    input.autocomplete( "search", "" );
                    input.focus();
                });
        },
        destroy: function() {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call( this );
        }
    });
	})( jQuery );

