/*
   Provides a countdown of characters left for a text
   input field.
   
   To use:
   1) you must have a div with an id of "countdown". This
      is where the countdown text is shown
   
   2) In Lift, when you bind the field to be counted,
      add an onkey binding. E.g.,
      "message" -> SHtml.textareas(m,m(_),"onkeyup"->Run("showcount(this)")
      
   3) In lift give the field to be counted the id of "countdownsource".
   
   Optionally:
   4) Look in the css for styles: countdown, negative, zero, positive.
*/

function isWebKit() {
	var userAgent = navigator.userAgent.toLowerCase();
	return /webkit/.test(userAgent);
}
	
/* Compute the length of the content as we would send it
   more or less. I.e., CRLF -> LF and handle Safari's
   extra trailing linefeed problem. But we need to keep
   the count as the user would expect it, by not trimming.*/
function crTrimmedLength(s) {

  if (s == undefined) {
  	return 0;
  }
  
	// Windows sends two characters for return
	var removedR = s.replace(/\r/gm, "");

	// The result is the length, but handling the case 
	// where Safari (Mac or PC) seems to want to add an 
	// extra 0A character.
	if (isWebKit()) {
 		return removedR.replace(/\n$/, "").length;
	} else {
		return removedR.length;
	}

}
	
var positive_text = "{} character[s] left"
var zero_text = "No room left. Stop typing!"
var negative_text = "Message too long. Remove {} character[s]"

function customize_text(s,v) {
	var substituted = s.replace("{}",v);
	// Plural/singular logic only good for English, and regular pluralization at that:
	// TODO: Fix for i18n or other changes to the three _text vars above.
	if (v == 1) {
		return substituted.replace("[s]","")
	} else {
		return substituted.replace("[s]","s")
	}
}


function showcount(field) {
	showcountfortext(field.value);
}

function showcountfortext(text) {
	var len = crTrimmedLength(text);
	var max_length = 160;
	var remains = max_length - len;
	
	var id_to_update = "#countdown";
	var update_div = $(id_to_update)
	if (remains > 0) {
		update_div.removeClass("negative");
		update_div.removeClass("zero");
		update_div.addClass("positive");
		update_div.html(customize_text(positive_text,remains));
	} else if (remains == 0) {
		update_div.removeClass("positive");
		update_div.removeClass("negative");
		update_div.addClass("zero");
		update_div.html(zero_text);
	} else {
		update_div.removeClass("zero");
		update_div.removeClass("positive");
		update_div.addClass("negative");
		update_div.html(customize_text(negative_text,-remains))
	}
	
}

// When the page has loaded, update the countdown field with the correct
// count. This ensures the div message is correct after server-side validation.
$(function() {
	showcountfortext($("#countdownsource").text());
});


