jQuery.fn.counter = function() {
  $(this).each(function() {
    $(this).focus(function(){
      var max = $(this).attr('maxlength');
      var val = $(this).attr('value');
      var cur = 0;
      if(val) // value="", or no value at all will cause an error
        cur = val.length;
      var left = max-cur;
      left = (left>=0)?left+'&nbsp;left':Math.abs(left)+'&nbsp;to&nbsp;many'
      $(this).after("<div class='counter'>"
        + left.toString()+" </div>");
      // You can use something like this to align the
      // counter to the right of the input field.
      var c = $(this).next(".counter");
      c.width(40);
      c.css("position","relative");
      //c.css("top",-$(this).height()-8);
      c.css("left",$(this).width()+8);
      //c.css("background","yellow");
      return true;
    });
    $(this).blur(function(){
      $(this).next(".counter").empty();
    });
    $(this).keyup(function(i) {
      var max = $(this).attr('maxlength');
      var val = $(this).attr('value');
      var cur = 0;
      if(val)
        cur = val.length;
      var left = max-cur;
      left = (left>=0)?left+'&nbsp;left':Math.abs(left)+'&nbsp;to&nbsp;many'
      $(this).next(".counter").html(left.toString());
      if(max>=cur) e.stopPropagation();
      return this;
    });
    $(this).keypress(function(e){
      var max = $(this).attr('maxlength');
      var val = $(this).attr('val');
      if(val.length>=max) e.stopPropagation();
    });
  });
  return this;
}
