function WordCount( characterCount ) {
  this.characterLimit = characterCount;
  this.wordCount = this;
  
  (function ($, wordCount ) {
    $(document).ready(function() {
      $('.component-textarea').prepend('<p class="fr word-count-display">('+wordCount.limit()+' caractères maximum)</p>');        
      $('.component-textarea textarea').bind( 'keyup change', {wordCount: wordCount}, wordCount.textChanged );
    });
  }(jQuery, this ));
  
}

WordCount.prototype.limit = function() {
  return this.characterLimit;
}

WordCount.prototype.entered = function() {
  return jQuery('.component-textarea textarea').val().length;
}
WordCount.prototype.over = function() {
  var caracteresRestants = this.wordCount.limit() - this.wordCount.entered();
  
  if( caracteresRestants < 0 ) {
    return caracteresRestants * -1;
  }
  return 0;
}

WordCount.prototype.textChanged = function( event ) {
  var wordCount = event.data.wordCount;
  var display = jQuery('.word-count-display');
  var caracteresRestants = wordCount.limit() - wordCount.entered();
  
  if( caracteresRestants === 0 ){
    display.text( '(aucuns caractères restants)' );
  }
  else if( wordCount.over() === 1 ){
    display.html( '(<span class="over">1 caractère en trop</span>)' );
  } 
  else if( caracteresRestants < 1 ){
    display.html( '(<span class="over">'+wordCount.over()+' caractères en trop</span>)' );
  } 
  else {
    display.text( '('+ caracteresRestants + ' caractères restants)' );
  }
  
    if( caracteresRestants < 0 ){
    display.find('span').addClass('text-warning');
  }
  else {
    display.find('span').removeClass('text-warning');
  }
  
};

