/*
 * 	Character Count Plugin - jQuery plugin
 * 	Dynamic character count for text areas and input fields
 *	written by Alen Grakalic	
 *	http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */
 
(function($) {

	$.fn.charCount = function(options, underOneRemainingListener, overOneRemainingListener){
	    var underOneCalled = false;
	    var overOneCalled = false;
		// default configuration properties
		var defaults = {	
			allowed: 140,
			counterElement: '.counter'
		}; 
			
		var options = $.extend(defaults, options); 
		
		function calculate(obj){
			var count = $(obj).val().length;
			var available = options.allowed - count;
			if(available <= 1 && !underOneCalled) {
			    underOneRemainingListener();
			    underOneCalled = true;
			    overOneCalled = false;
			} 
			if(available > 1 && !overOneCalled) {
			    overOneRemainingListener();
			    underOneCalled = false;
			    overOneCalled = true;
			}
			if(available < 0){
				$(obj).val($(obj).val().substring(0, options.allowed));
                                available = 0;
			}
			$(options.counterElement).html(available);
		};
				
		this.each(function() {
			calculate(this);
			$(this).keyup(function(){calculate(this)});
			$(this).change(function(){calculate(this)});
		});
	  
	};

})(jQuery);

