// JavaScript Document


var VisualLength = Class.create();
VisualLength.prototype = {
  initialize: function(attribute) {
    this.fields = ['INPUT', 'TEXTAREA'];
    this.attribute = attribute || 'maxlength';
    this.ignore = '__'+this.attribute;
    this.scan();
    this.create();
  },

  create: function() {
    this.box = Element.extend(document.createElement('div'));
//    this.box.setStyle({ position: 'absolute', backgroundColor: '#eeeeee;', border: '1px solid #000', display: 'none' });
    this.box.setStyle({ position: 'absolute', backgroundColor: '#FFF', border: '2px solid #990000', display: 'none' });
    document.body.appendChild(this.box);
  },

  show: function(e) {
    this.target = Event.element(e);
    this.max = this.target.getAttribute(this.attribute);
    this.checker();

    Position.clone(this.target, this.box);
    var top = parseInt(this.box.style.top) - 25;
    this.box.setStyle({ width: '5em', height: '1.5em', top: top+'px' }); 
    this.box.show();
  },

  hide: function() {
    this.box.hide();
  },

  checker: function() {
    var len = this.target.value.length;
    if(len > this.max)
      len = '<font color="red">'+len+'</font>';
    this.box.innerHTML = len + '/' + this.max;
  },

  scan: function(parent) {
    parent = parent || document;
    for(var t, i = 0; t = this.fields[i]; i++) {
      this.parse(parent.getElementsByTagName(t));
    }
  },

  parse: function(elms) {
    for(var elm, i = 0; elm = elms[i]; i++) {
      if(elm.getAttribute(this.attribute)) {
        if(elm.getAttribute(this.ignore)) continue;
        Event.observe(elm, 'focus', this.show.bind(this));
        Event.observe(elm, 'blur', this.hide.bind(this));
        Event.observe(elm, 'keydown', this.checker.bind(this));
        Event.observe(elm, 'keyup', this.checker.bind(this));
        elm.setAttribute(this.ignore, 'true');
      }
    }
  }
};
