jQuery.fn.wordCount = function(params)
{
	var p =  {
		counterElement:"display_count",
		max: false
	};
	
	var total_words;

	if(params)
	{
		jQuery.extend(p, params);
	}

	var counter = jQuery('#'+p.counterElement);
	//for each keypress function on text areas
	this.bind('keyup click blur focus change paste', function()
	{
		var count = 0;
		var ccode;
		var v = jQuery.trim($(this).val());

		var buffer = $(this).data('buffer');
		if (buffer == v)
		{
			return;
		}

		var charlen = v.length;
		var lastIsChar=false;

		$(this).data('buffer', v);
		
		if (charlen > 0)
		{
			for (var i=0; i<charlen; i++)
			{
				ccode = v.charCodeAt(i);
				if ((ccode >= 65 && ccode <= 90) || (ccode >= 97 && ccode <= 122) || (ccode >= 48 && ccode <= 57) || ccode >= 256)
				{
					if (ccode <= 256)
					{
						if (!lastIsChar)
							count++;
						lastIsChar = true;
					}
					else
					{
						count++;
						lastIsChar = false;
					}
				}
				else
				{
					lastIsChar = false;
				}
			}
		}

		var total_words = count;
		counter.html(total_words);

		if (p.max && total_words > p.max)
		{
			$(this).addClass('wordlimit_exceed');
			counter.addClass('wordlimit_exceed');
		}
		else
		{
			$(this).removeClass('wordlimit_exceed');
			counter.removeClass('wordlimit_exceed');
		}
	});

	$(this).trigger('keyup');
};

