/* jQuery.charlimit
 * 
 * Purpose: For fields with an upper character count bound, will update
 *          an element with the number of remaining characters on init
 *          and changes to the targeted field
 *
 * Usage: $('input#field_id').charcount(int_limit, target_element)
 *        $("input[name='inputname']").charcount(50, $('#inputname_count'));
 *
 * Morgan Massena - 2008-12-25 Modified from charlimit.js by Ryan Aker 01-07-10
 */

(function($) {
	
	$.fn.charcount = function(target, limit) {
		
		// update initial character count
		target.html(this.val().length);
		
		// update count when value changes
		this.bind('keyup', function() {
			var remain = $(this).val().length;
			
		if(limit != null)
		{
			// if they've gone over the limit, truncate the value
			if (remain > limit) {
				$(this).val($(this).val().substr(0, limit));
				alert("This field is limited to " + limit + " characters. Please shorten it");
			}
		
			// update remaining char count to alert user
			target.html(String(Math.min(limit, remain)));
		}
		else
		{
			// update remaining char count to alert user
			target.html(String(Math.max(0, remain)));	
		}
		
		});
		
		return this;
	};
})(jQuery);