(function( $ ){
    $.fn.usersearch = function(){
        hiddenfield = this;
        autofield = $(this.clone().attr('id', this.attr('id') + "_autocomplete")).insertBefore(this);
       // hiddenfield.hide();
        split = function( val ) {
            return val.split( /,\s*/ );
        }
        extractLast = function ( term ) {
            return split( term ).pop();
        }
        
        autofield.autocomplete({
            minLength:1,
            source: function( request, response ) {
                var t = extractLast( request.term );
                
                $.ajax({
                    url:$UTILS_USER_SEARCH, 
                    cache:false,
                    type:'post',
                    datatype:'json', 
                    data:{term:t},
                    success: function(data, textStatus) {
                        //dlog(data);
                        response( $.map( data, function( item ) {
                            return {
                                fullname: item.name,
                                label: item.name + " ["+ item.username +"]",
                                value: item.username
                            }
                        }));
                    }
                });
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                //dlog("hval: " + hiddenfield.val());
                var vals = (hiddenfield.val());
                /*if(hiddenfield.val()){
                    vals = hiddenfield.val();
                } else {
                    vals = this.value;
                }*/
                //dlog(vals);
                vals = split(vals);
                //dlog(vals);
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                //vals.pop();
                // add the selected item
                terms.push( ui.item.fullname );
                vals.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                //vals.push( "" );
                this.value = terms.join( ", " );
                hiddenfield.val(vals.join( "," ));
                return false;
            }
        });
    }
})( jQuery );
