/**
 * todo: make it possible to count words instead of characters 
 *
 **/
jQuery.fn.textLimiter = function(){
    return this.each(function(){
            if(typeof(nr) == "undefined") { nr = 0; }                           
            var counter_id   = 'counter' +nr;                           
            var max          = this.getAttribute('maxlength');
            var html_counter = '<div id="' +counter_id + '" class="counter" style="margin-top:0px;font-style:italic;">caractères restants : <span>' +max+ '</span></div>';
            $(this).after(html_counter);
            var jquery_pattern = '#' +counter_id +' > span';
            this.relatedElement = $(jquery_pattern)[0];
            nr++;
            $(this).bind("keyup", function(){
                var maxLength     = this.getAttribute('maxlength');
                var currentLength = this.value.length;
                if(currentLength >= maxLength) {
                    this.relatedElement.className = 'toomuch';
                    this.relatedElement.value = 0;
                    this.value = this.value.substring(0, maxLength);
                } else {
                    this.relatedElement.className = '';
                }
                var left_over = maxLength - currentLength; 
                this.relatedElement.firstChild.nodeValue = left_over;
            });
    });
};
