(function( $ ) {

$.widget( "ui.tradoriasuggest", $.ui.autocomplete, {
    _renderItem: function( ul, item) {
        var header = item.header > "" ? "<div class='ui-widget-header'>" + item.header + "</div>" : "";
        var info = item.label;
        if (item.count > 0) {
            info = item.label + "&nbsp;<span style='font-size:x-small; color:gray; text-align:right;'>(mindestens " + addDots(item.count) + " Produkt"+(item.count>1?"e":"")+")</span>";
        }
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( header + "<a>" + info + "</a>" )
            .appendTo( ul );
    },
    _search: function( value ) {
        this.term = this.element
            .addClass( "ui-autocomplete-loading" )
            // always save the actual value, not the one passed as an argument
            .val();
        this.source( { term: value, category: $("select[name=search_catalog]").val() }, this.response );
    }
});

}( jQuery ));

function addDots(nStr) {
	nStr += '';
	x = nStr.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

$(function() {
    // $("#searchterm")
    $("input[type=text][name=search]").tradoriasuggest({
        source: autocompleteSearchURL,
        select: function(event, ui) {
            if (ui.item.type == "cat") {
                window.location = ui.item.link;
                ui.item.value = ui.item.label;
            } else {
                setTimeout("$('form[name=search]').submit();", 100);
            }
        }
    });
});