/**
 * CharCount.js
 *
 * @author andy brudtkuhl
 * @classDescription charcount for textboxes ... if user goes over char count the extra characters are automagically stripped from the end
 * @params
 *  - textElement: textbox or textarea to count chars in
 *  - maxChars: number of characters allowed
 *  - label: element to notify user how many chars are left
 *  - doExpand: OPTIONAL - TRUE = expand textarea on click adding more rows
 **/

mdp.charCount = function(_textElement, _maxChars, _label, _doExpand) {
    var self = this;
    this.textElement = _textElement;
    this.maxChars = _maxChars;
    this.label = _label;
    this.doExpand = _doExpand;

    this.textElement.bind({
        "focus": function() {
            self.focused = true;
        },
        "blur": function() {
            self.focused = false;
        },
        "click": function(e) {
            if (self.doExpand != undefined && self.doExpand){ self.textElement.attr('rows', '6'); }
            getTextLength(e);
        },
        "keydown":getTextLength,
        "keyup":getTextLength
    });

    function getTextLength(e){
        var chars = getChars();
        if(chars > self.maxChars){
            self.textElement.value = self.textElement.value.substring(0,self.maxChars);
            alert("Too Many Characters! : " + self.maxChars + " is the limit");
        }
        displayStatus(chars);
    }

    function displayStatus(chars){
        if (chars >= self.maxChars) {
            self.label.html("<strong>0 characters left</strong>");
        }
        else {
            self.label.text(self.maxChars-chars + " characters left");
        }
    }

    function getChars(){
        return self.textElement.val().length;
    }

    function init(){
        displayStatus(getChars());
        self.textElement.attr("maxlength",self.maxChars);
    }

    init();

};
