/**
 *  @author   epriestley
 *
 *  @requires function-extensions control-textinput vector
 *  @provides control-textarea
 */

function /* class */ TextAreaControl(textarea) {

  copy_properties(this, {
          autogrow : false,
            shadow : null,
    originalHeight : null,
      metricsValue : null
  });

  this.parent.construct(this, textarea);
};

TextAreaControl.extend(TextInputControl);

copy_properties(TextAreaControl.prototype, {

  setAutogrow : function(autogrow) {
    this.autogrow = autogrow;
    this.refreshShadow();
    return this;
  },

  onupdate : function() {
    this.parent.onupdate();

    var r = this.getRoot();
    if (this.autogrow && r.value != this.metricsValue) {
      this.metricsValue = r.value;

      copy_properties(this.shadow.style, {
          fontSize : parseInt(CSS.getStyle(r, 'fontSize'), 10) + 'px',
        fontFamily : CSS.getStyle(r, 'fontFamily') + 'px',
             width : (Vector2.getElementDimensions(r).x - 8) + 'px'
      });

      DOM.setContent(this.shadow, HTML(htmlize(r.value)));
      r.style.height = Math.max(
        this.originalHeight,
        Vector2.getElementDimensions(this.shadow).y + 15) + 'px';
    }
  },

  refreshShadow : function() {
    if (this.autogrow) {
      this.shadow = $N('div', {className: 'DOMControl_shadow'});
      document.body.appendChild(this.shadow);
      var r = this.getRoot();
      this.originalHeight = parseInt(CSS.getStyle(r, 'height'))
        || Vector2.getElementDimensions(this.getRoot()).y;
    } else {
      if (this.shadow) {
        DOM.remove(this.shadow);
      }
      this.shadow = null;
    }
  }


});


/* -(  Deprecated Textarea APIs  )------------------------------------------- */


function autogrow_textarea(element) {
  element = $(element);
  if (!element._hascontrol) {
    element._hascontrol = true;
    new TextAreaControl(element).setAutogrow(true);
  }
}

function textarea_maxlength(element, length) {
  element = $(element);
  if (!element._hascontrol) {
    element._hascontrol = true;
    new TextAreaControl(element).setMaxLength(length);
  }
}
