(function($) {
	// ex.: options = {maxRows:6}
    $.fn.autogrow = function(options) {
        this.filter('textarea').each(function() {            
            var $this       = $(this),
				lineHeight  = $this.css('lineHeight'),
				vLineHeight = lineHeight.replace(/px/g, ''),
                minHeight   = $this.height(),
				maxHeight   = (options && options['maxRows'] ? options['maxRows'] * vLineHeight : -1);
            
            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width(),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);
            
            var update = function() {                
                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n/g, '<br/>');
                
                shadow.html(val);
				if (maxHeight > 0)
					$(this).css('height', Math.min(shadow.height() + 20, maxHeight));
				else
					$(this).css('height', Math.max(shadow.height() + 20, minHeight));
            }
            
            $(this).change(update).keyup(update).keydown(update);
            
            update.apply(this);            
        });
        
        return this;
    }
    
})(jQuery);
