
jQuery.fn.characterCount = function(limit, updateFields)
{
	this.each(function()
	{
		var field = this;
		var updateTimer = null;
		var lastValue = $(field).val();

		function updateDescriptionCharacterCount()
		{
			var remaining = limit - $(field).val().length;
			$(updateFields).text(remaining);
			if(remaining >= 20)
				$(updateFields).removeClass('character-count-alert');
			else
				$(updateFields).addClass('character-count-alert');
		}

		function checkForUpdate()
		{
			var newValue = $(field).val();
			if(newValue != lastValue)
			{
				updateDescriptionCharacterCount();
				lastValue = newValue;
			}
			updateTimer = window.setTimeout(checkForUpdate, 50);
		}

		function endUpdateTimer()
		{
			window.clearTimeout(updateTimer);
		}

		$(field)
			.keypress(updateDescriptionCharacterCount)
			.focus(checkForUpdate)
			.blur(endUpdateTimer);

		updateDescriptionCharacterCount();
	});
};
