$(document).ready(function(){
	setMaxLength();     
	$('textarea[maxlength].checkMaxLength').bind('click mouseover keyup keypress change', function(){checkMaxLength(this.id); } )
});

function setMaxLength() {
	$('textarea[maxlength].checkMaxLength').each(function(i){
		var maxLength = $(this).attr('maxlength');
		$(this).after('<p class="hint"><span id="' + this.id + 'Counter">' + maxLength + '</span> ' + __('characters remaining') + '</p>');
	});
}

function checkMaxLength(textareaId){
	var numChars = $('#'+textareaId).val().length;
	var maxLength = $('#'+textareaId).attr('maxlength');
	var textareaCounterId = '#' + textareaId + 'Counter';
	$(textareaCounterId).text(parseInt(maxLength) - parseInt(numChars));
	//good
	if(numChars < (maxLength * .8)){
		$(textareaCounterId).css('color', '#006600'); 
	}
	//warning at 80%
	if(numChars > (maxLength * .8)){
		$(textareaCounterId).css('color', '#FF9933');
	}
	//over
	if(numChars > maxLength){
		$(textareaCounterId).text(0).css('color', '#990000');
		var truncated = $('#'+textareaId).val().substr(0, maxLength);
		$('#'+textareaId).val(truncated);
	}
 }