$.fn.magicInput = function() {
  function r(el,newline) {
    var isblank = false;
    if ($(el).val() == '') {
      isblank = true;
      $(el).val(' ');
    }
    var new_height = el.scrollHeight + (newline?15:0);
    if (el.scrollWidth > el.clientWidth && !$(el).data('addedscrollbar')) {
      new_height += jQuery.getScrollbarWidth() + parseInt($(el).css('padding-bottom'));
      $(el).data('addedscrollbar',true);
    }
    
    var linecount = 0;
    $.each($(el).val().split('\n'),function(l){ linecount++; });
    new_height += 15 * (linecount - $(el).data('newlines'));
    $(el).data('newlines',linecount);
    $(el).css('height',new_height+'px');
    if( (add_height = el.scrollHeight - el.clientHeight) > 0 ) {
      $(el).css('height',(new_height+add_height)+'px');
    }
    if (isblank) {
      $(el).val('');
    }
  }
  return this.each(function(){
    $(this).css('height','1px');
    var linecount = 0;
    $.each($(this).val().split('\n'),function(l){ linecount++; });
    $(this).data('newlines',linecount);
    r(this,true);
    $(this).blur(function(){
      r(this);
    })
    $(this).keydown(function(ev){
      r(this);
    }).keyup(function(ev){r(this)});
  });
}

/*! Copyright (c) 2008 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
 
/**
* Gets the width of the OS scrollbar
*/
;(function($) {
  var scrollbarWidth = 0;
  $.getScrollbarWidth = function() {
    if ( !scrollbarWidth ) {
      if ( $.browser.msie ) {
        var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
            .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
          $textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
            .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
        scrollbarWidth = $textarea1.width() - $textarea2.width();
        $textarea1.add($textarea2).remove();
      } else {
        var $div = $('<div />')
          .css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
          .prependTo('body').append('<div />').find('div')
            .css({ width: '100%', height: 200 });
        scrollbarWidth = 100 - $div.width();
        $div.parent().remove();
      }
    }
    return scrollbarWidth;
  };
})(jQuery);