/**
 * The following code provides a simple text/word counter option for any 
 * textarea. It either just keeps counting up, or limits the results to a
 * certain number - all depending on what the user has selected via the
 * field type settings.
 */
var cf_counter = {};
cf_counter.get_max_count = function(el) {
  var classes = $(el).attr('class').split(" ").slice(-1);
  var max = null;
  for (var i=0; i<classes.length; i++) {
    var result = classes[i].match(/max(\d+)/);
    if (result != null) {
      max = result[1];
      break;
    }
  }
  return max;
}

$(function() {
  $("textarea[class~='cf_wordcounter']").each(function() {
    var max = cf_counter.get_max_count(this);
    if (max == null) {
      return;
    }
    $(this).bind("keydown", function() {
      var val = $(this).val();
      var len = val.split(/[\s]+/);
      var field_name = $(this).attr("name");
      var num_words  = len.length - 1;
      if (num_words > max) {
        var allowed_words = val.split(/[\s]+/, max);
        truncated_str = allowed_words.join(" ");
        $(this).val(truncated_str);
      } else {
        $("#" + field_name + "_counter").find("span").html(parseInt(max) - parseInt(num_words));
      }
    });
    $(this).trigger("keydown");
  });
  $("textarea[class~='cf_textcounter']").each(function() {
    var max = cf_counter.get_max_count(this);
    if (max == null) {
      return;
    }
    $(this).bind("keydown", function() {
      var field_name = $(this).attr("name");
      if (this.value.length > max) {
        this.value = this.value.substring(0, max);
      } else {
        $("#" + field_name + "_counter").find("span").html(max - this.value.length);
      }
    });
    $(this).trigger("keydown");
  });
});