/*
*	Auto Grow Text Area
*	Inspired by FaceBook autoGrow textareas and
*	http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
*
*
*	author: Giancarlo Gomez
*/
var autoGrowTextarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    	
	this.options = $H({
      'min_height' : 30,
      'max_length' : 400,
	  'border': 0
    }).update(options);
	
   	this.textarea.observe('keyup', this.refresh.bind(this));
				
    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-1000px',
      left: '-1000px',
      width:  this.textarea.getStyle('width'),
	  padding: this.textarea.getStyle('padding'),
	  border:this.options.get('border') + 'px solid white'
    });
	
	this.textarea.setStyle({
		overflow:'hidden'
  	});
				
    this.textarea.insert({ after: this._shadow });

    this.refresh();  
  },

  refresh: function()
  { 
  	
  	// in case this was hidden we need to apply the width to the shadow div
	if (this._shadow.getWidth() < this.textarea.getWidth()){
				
		this._shadow.setStyle( {width: this.textarea.getStyle('width')});
	}	
	
	var c = $F(this.textarea).stripScripts().stripTags();
  
    this._shadow.update(c.replace(/\n/g, '<br/>&nbsp;'));
				
	
	var h = parseInt(this._shadow.getStyle('height'));
	
	if (isNaN(h)){
		h = 0;
	}	
	this.textarea.setStyle({
	  height: Math.max(h, this.options.get('min_height')) + 'px'
	});
	
  }
});
