/**
*
* Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
* http://www.tomdeater.com/jquery/character_counter/
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* MM changes
*   remove span tags at startup
*   added code to unbind event listeners
*   namespaced event listeners, so that unbind only removes these listeners
*/



(function($)
{
    /**
    * attaches a character counter to each textarea element in the jQuery object
    * usage: $("#myTextArea").charCounter(max, settings);
    */

    $.fn.charCounter = function(max, settings)
    {
        if (max == 0) return;
        max = max || 100;
        settings = $.extend({
            container: "<span></span>",
            containerID: null,
            classname: "charcounter",
            classnameOver: "charcounterOver",
            format: "&nbsp;(%1)",
            pulse: true,
            delay: 0
        }, settings);
        var p, timeout;

        function count(element, container, event)
        {
            el = $(element);
            container.html(settings.format.replace(/%1/, (max - el.val().length)));

            if (event.charCode == 0)
                return true;

            if (event.ctrlKey)
                return true;

            if (event.charCode == 8)
                return true;

            if (document.selection)
            {
                var range = document.selection.createRange();
                var stored_range = range.duplicate();
                stored_range.expand("textedit");
                stored_range.setEndPoint('EndToEnd', range);
                element.selectionStart = stored_range.text.length - range.text.length;
                element.selectionEnd = element.selectionStart + range.text.length;
            }

            var selectionStart = element.selectionStart;
            var selectionEnd = element.selectionEnd;

            if (selectionEnd != selectionStart)
                return true;

            var returnVal = true;

            if (el.val().length > max - 1)
            {
                returnVal = false;
                if (settings.pulse && !p)
                {
                    pulse(container, true);
                };
            };

            if (el.val().length > max - 1)
            {
                container.removeClass(settings.classname);
                container.addClass(settings.classnameOver);
            }
            else
            {
                container.removeClass(settings.classnameOver);
                container.addClass(settings.classname);
            }

            if (settings.delay > 0)
            {
                if (timeout)
                {
                    window.clearTimeout(timeout);
                }
                timeout = window.setTimeout(function()
                {
                    setCharacterCount(el, container);
                }, settings.delay);
            } else
            {
                setCharacterCount(el, container);
            }
            return returnVal;
        };

        function setCharacterCount(el, container)
        {
            container.html(settings.format.replace(/%1/, (max - $(el).val().length)));
        }

        function countPaste(el, container)
        {
            $(el).val($(el).val().substring(0, max));
            container.html(settings.format.replace(/%1/, (max - $(el).val().length)));
        }

        function pulse(el, again)
        {
            if (p)
            {
                window.clearTimeout(p);
                p = null;
            };
            el.animate({ opacity: 0.1 }, 100, function()
            {
                $(this).animate({ opacity: 1.0 }, 100);
            });
            if (again)
            {
                p = window.setTimeout(function() { pulse(el) }, 200);
            };
        };

        return this.each(function()
        {
            $('.charcounter, .charcounterOver', this.parentNode).remove();

            var container;
            if (settings.containerID == null)
            {
                container = (!settings.container.match(/^<.+>$/))
				? $(settings.container)
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
            }
            else
            {
                container = $('#' + settings.containerID);
            }

            $(this)
				.unbind(".charCounter")
				.bind("keydown.charCounter", function(event) { count(this, container, event); })
				.bind("keypress.charCounter", function(event) { return count(this, container, event); })
				.bind("keyup.charCounter", function(event) { count(this, container, event); })
				.bind("paste.charCounter", function(event) { var me = this; setTimeout(function() { countPaste(me, container); }, 10); });

            setCharacterCount(this, container);
        });


    };

    $.fn.collectionMaxLength = function()
    {
        maxLength = 0;
        this.each(function()
        {
            var thisLength = $(this).val().length;
            if (thisLength > maxLength)
                maxLength = thisLength;
        });
        return maxLength;
    };

})(jQuery);
