var TextareaExpander = Behavior.create({
  initialize: function() {
    this.textarea = this.element;
    
    /* height can be returned as null in webkit-based browsers */
    var min_height = this.textarea.getStyle('height');
    if(min_height){ this.min_height = min_height.replace('px', ''); }
    
    this.font_size = this.textarea.getStyle('font-size').replace('px', '') * 1.5;

    this.textarea.observeExclusively("keyup", this.resize.bind(this));
    this.textarea.observeExclusively("mouseup", this.resize.bind(this));

    if($F(this.textarea).split("\n").size() > 1) {
      this.resize();
    }
  },
  
  resize: function() {
    var lines = $F(this.textarea).split("\n");    
    var width = this.textarea.getStyle('width').replace('px', '');
    var count = $A(lines).inject(lines.size(), function(acc, line){   
      if(wrapped_line_count = Math.ceil(line.length / (width/9)) > 1) {
        return acc + wrapped_line_count;
      } else {
        return acc;
      }
    });

    var height = Math.max(count * this.font_size, this.min_height);
    this.textarea.setStyle({'height' : height + 'px'}) 
  }
});

Event.addBehavior({
  'textarea.expandable': TextareaExpander
});