﻿jQuery.fn.wordcount = function(opts) {

    return this.each(
        function()/*do it for each matched element*/
        {
            if (opts.styles != null) {
                $(this).after("<div class=\"wordcount\" style=\"" + opts.styles + "\"><div class=\"message\"></div></div>");
            }
            else {
                $(this).after("<div class=\"wordcount\"><div class=\"message\"></div></div>");
            }
            $(this).bind("keyup", function() { CountWords(this); });
            $(this).trigger('keyup');
            if (($.browser.msie) || ($.browser.safari)) {
                $(this).bind("cut", function() { setTimeout("CountWords('." + $(this).attr('class') + "')", 100); });
                $(this).bind("paste", function() { setTimeout("CountWords('." + $(this).attr('class') + "')", 100); });
            }
            else {
                $(this).bind("input", function() { CountWords(this); });
            }

            function CleanSpaces(text) {
                if (text.match('  ') != null) {
                    return CleanSpaces(text.replace(/  /g, ' '));
                }
                else {
                    return (text);
                }
            }

            function CountWords(obj) {
                var text = CleanSpaces($(obj).val());
                text = $.trim(text);
                var info = $(obj).next("div.wordcount").children("div.message");
                var words = (text.length == 0) ? 0 : text.split(' ').length;
                info.html('Words: ' + words);
            }

            CountWords(this);
        }
    );
}


