$(function() {  
  updateWordLimits();
  updateCharLimits();
});

function updateWordLimits() {
  $("textarea.wordlimit").each(function() {
    limit = $(this).get(0).className.replace(/\D+/, "");
    $(this).data('limit', limit);
  
    if ($("p.word_count[rel="+$(this).attr('id')+"]").length == 0) {
      $html='<p class="sidenote word_count" rel='+$(this).attr('id')+'>Word count: <span class="current">0</span> out of a maximum of ' + limit;
      $(this).after($html);
      var current = countWords($(this).val());
      $("p[rel="+$(this).attr('id')+"] span.current").text(current < limit ? current : limit);
      handler = function() {
        var current = countWords($(this).val());
        $("p[rel="+$(this).attr('id')+"] span.current").text(current < $(this).data('limit') ? current : $(this).data('limit'));
        if (current > $(this).data('limit')) {
          $(this).val(trimWords($(this).val(), $(this).data('limit')));
          setCaretPosition($(this), $(this).val().length - 1);
          $(this).get(0).scrollTop = $(this).get(0).scrollHeight;
        }
      };
      $(this).bind('keyup', handler);
      $(this).bind('mouseleave', handler);
    } else {
    
    }
  });
}

function trimWords(string, amount) {
  while (countWords(string) > amount) {
    string = string.substr(0, string.length - 1);
  }
  return string;
}

function countWords(string) {
  var foo = string.match(/[A-Za-z\'\-]+/g);
  return foo ? foo.length : 0;
}

function updateCharLimits() {
  $("textarea.charlimit").each(function() {
    limit = $(this).get(0).className.replace(/\D+/, "");
    $(this).data('limit', limit);
  
    if ($("p.word_count[rel="+$(this).attr('id')+"]").length == 0) {
      $html='<p class="sidenote word_count" rel='+$(this).attr('id')+'>Character count: <span class="current">0</span> out of a maximum of ' +  limit;
      $(this).after($html);
      var current = $(this).val().length;
      $("p[rel="+$(this).attr('id')+"] span.current").text(current < limit ? current : limit);
      handler = function() {
        var current = $(this).val().length;
        $("p[rel="+$(this).attr('id')+"] span.current").text(current < $(this).data('limit') ? current : $(this).data('limit'));
        if (current > $(this).data('limit')) {
          $(this).val($(this).val().substring(0, $(this).data('limit')));
          setCaretPosition($(this), $(this).val().length - 1);
          $(this).get(0).scrollTop = $(this).get(0).scrollHeight;
        }
      };
      $(this).bind('keyup', handler);
      $(this).bind('mouseleave', handler);
    } else {
    
    }
  });
}

function setCaretPosition(elem, caretPos) {
  if(elem != null) {
    if(elem.createTextRange) {
      var range = elem.createTextRange();
      range.move('character', caretPos);
      range.select();
    }
    else {
      if(elem.selectionStart) {
        elem.focus();
        elem.setSelectionRange(caretPos, caretPos);
      }
      else
        elem.focus();
    }
  }
}

