
if (typeof(avt) == 'undefined') avt = {}; 

avt.sb_initbox = function(rootCtrlId, suggestionCount, suggestionsUrl) {

    avt.sb.$("#" + rootCtrlId).find("input.searchBox").keydown(function(event) {
        if (event.keyCode==13 && !(this.suggestionsOpen && avt.sb.$(".sbautocomplete .ui-state-hover").size() > 0)) { 
            avt.sb.$(this).parents(".sbInp:first").find(".searchBtn").click(); 
            return false; 
        }
    });
    
    if (suggestionCount != 0) {

        if (avt.sb.$(".sbautocomplete").size() == 0) {
            avt.sb.$("body").append("<div class='sbautocomplete'></div>");
        }

        avt.sb.$("#" + rootCtrlId).find("input.searchBox").autocomplete({
            appendTo: ".sbautocomplete",
		    source: suggestionsUrl,
		    minLength: 2,
		    search: function() {
			    // custom minLength
			    var term = this.value.split( /\s+/ ).pop();
			    if ( term.length < 2 ) {
				    return false;
			    }
		    },
		    open: function() {
			    this.suggestionsOpen=true;
		    },
		    close: function() {
			    this.suggestionsOpen=false;
		    },
		    focus: function() {
			    // prevent value inserted on focus
			    return false;
		    },
		    select: function( event, ui ) {
			    var terms = this.value.split( /\s+/ );
			    // remove the current input
			    terms.pop();
			    // add the selected item
			    terms.push( ui.item.value );
			    // add placeholder to get the comma-and-space at the end
			    terms.push( "" );
			    this.value = terms.join( " " );
			    return false;
		    }
	    });
    }
}

