jQuery.fn.boxable = function(options) {
  this.each(function() {
    var input = this;
    var div = $(input).wrap('<div></div>').parent()[0];
    var list = $(input).before('<ul></ul>').prev()[0];
    
    var label = options.label || function(result) { 
      return result.label;
    };
    var value = options.value || function(result) { 
      return result.value;
    };
    var divClass = options.divClass || 'boxable'

    $(input).bind('box', function(e, result) {
      if(input.value.length > 0) {
        var li = $(list).append('<li></li>').find(':last');
        $(li).append(label(result));
        $(li).append('<input type="hidden" name="'+input.name+'" value="'+value(result)+'">');
        $(li).append('<a href="javascript:;"><img src="/images/token_x.gif"></a>');
        var x = $('a', li);
        $(x).click(function() {
          $(li).remove();
        });
      }
    });
    
    $(div).addClass(divClass).click(function() {
      $(input).focus();
    });

    $(input).keydown(function(e) {
      if(e.which == 8 && input.value.length == 0)
        $('li:last', list).remove();
    });

    $(input.form).submit(function() {
      input.disabled = true
      //return false
    });

    // We use the title to store tips, we don't want to store the tip as a tag
    if(input.value.length > 0 && input.value != input.title) {
      var results = $.parseJSON(input.value);
      $.each(results, function() {
        $(input).trigger('box', this);        
      });
      $(input).val(input.title);
      $(input).removeClass('active')
    }

  });
  return this;
}

