/*
A twiiter like character counter plugin for jQuery.

===========
Supported class names, .character-count, .word-count

How to use:
1) Place either character-count or word-count inside a input element - text or a textarea.
2) Specify a maxlength 
3) Create an elemenet to write inside. The element ID must be inputID + '-counter'
 
Uses:
Counts the characters inside a input/textarea element and displays the limit inside corresponding element.


*/

$(document).ready(function() {
	$('.character-count, .word-count').each(function(){
		var length = $(this).val().length;
		var type = 'characters';
		if ($(this).hasClass("word-count")){
			length = $(this).val().split(' ').length;
			type = 'keywords';
		}
		var max = $(this).attr('maxlength');
		var id = $(this).attr('id');
		var counter = '#' + id + '-counter';
		var remaining = max - length;
		$(counter).html('<strong>' + remaining + '</strong> '+type+' remaining');
		$(this).keydown(function(event){

			length = $(this).val().length;
			
			if ($(this).hasClass("word-count")){
				length = $(this).val().split(' ').length;
			}
			
			remaining = max - length;

			if(length > max) {
				$(this).val($(this).val().substr(0, max));
				return false;
			}
			
			$(counter).html('<strong>' + remaining + '</strong> '+type+' left');

			if (remaining > 10) {
				$(counter).css({color:'#000'});
			}
			
			if (remaining <= 5) {
				$(counter)
				.css({color:'#cc0000'})
				.animate({color:'#666666'}, 1000);
			}
		});
		$(this).keyup(function(event){
			length = $(this).val().length;
			
			if ($(this).hasClass("word-count")){
				length = $(this).val().split(' ').length;
			}

			remaining = max - length;
			$(counter).html('<strong>' + remaining + '</strong> '+type+' left');
		});
	});
});