$(document).ready(function()
{
  
  var max_length = 200;
  
  // Length limit
  function get_description_length(textarea)
  {
    return $(textarea).val().replace(/[\t ]+/g, " ").replace(/[\r\n]+/g, "\n").replace(/(^\s+|\s+$)/g, "").length;
  }
  
  function update_description_length()
  {
    
    var textarea = $(this);
    
    // Normalise the input by removing new lines, tabs and multiple consecutive spaces
    var length = get_description_length(this);
    
    var id = textarea.attr("id");
    var label = $("#" + id + "-length");
    
    if (length > max_length)
    {
      label
        .addClass("length-error")
        .text("Your description is " + length + " characters long. Please reduce it to " + max_length + " characters.");
    }
    else
    {
      var remaining = max_length - length;
      var s = (remaining == 1 ? "" : "s");
      label
        .removeClass("length-error")
        .text("You have " + remaining + " character" + s + " remaining.");
    }
    
  }
  
  function check_description_length()
  {
    var textareas = $(".limitlength", this).get();
    for (i in textareas)
    {
      if (get_description_length(textareas[i]) > max_length)
      {
        alert("Sorry, your description is too long. Please reduce it to " + max_length + " characters.");
        textareas[i].focus();
        return false;
      }
    }
    return true;
  }
  
  $(".limitlength")
    .bind("change keyup", update_description_length)
    .each(update_description_length);
  
  $("form:has(.limitlength)").bind("submit", check_description_length);
  
});


