var charcounter = Class.create();

charcounter.prototype = {

    initialize: function(options) {

        this.inputelement = options.inputelement;
        this.maxlength = options.maxlength;
        this.counterelement = options.counterelement;
        if (this.inputelement != null)
            this.charsleft = this.maxlength - this.inputelement.value.length;
        this.timedobserver;

        Event.observe(this.inputelement, 'keyup', this.handleKeyPress.bindAsEventListener(this), false);
        Event.observe(this.inputelement, 'mousedown', this.handleMouseClick.bindAsEventListener(this), false);

        this.updateCharsLeft();
    },

    handleKeyPress: function(event) {

        var str = this.inputelement.value;
        this.stripInputValue(str);
        Event.stop(event);
        this.updateCharsLeft();

    },

    stripInputValue: function(str) {
        if (this.inputelement.value.length >= this.maxlength) {
            str = str.slice(0, this.maxlength);
            this.inputelement.value = str;
        }
    },

    handleMouseClick: function(event) {
        this.timedobserver = new Form.Element.Observer(
          this.inputelement,
          0.2,
          function(el, value) {
              this.stripInputValue(value);
              this.updateCharsLeft();
          } .bind(this)
        )

    },

    updateCharsLeft: function() {
        this.charsleft = this.maxlength - this.inputelement.value.length;
        this.counterelement.innerHTML = this.charsleft;
        if (this.timedobserver)
            this.timedobserver.stop();
    }

};

