/**
*
* jquery.charcounter.js version 1.3 Milou (Besd on jquery.charcounter.js version 1.2 by Tom Deater)
* requires jQuery version 1.2 or higher
* Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
* Modified by Frans Andersson @ Milou Communication AB
* NOTE: Mikz version!
*
*/

(function ($) {
    /**
    * attaches a character counter to each textarea element in the jQuery object
    * usage: $("#myTextArea").charCounter(max, settings);
    */

    $.fn.charCounter = function (max, settings) {
        max = max || 100;
        settings = $.extend({
            container: "<span></span>",
            classname: "charcounter",
            format: "%1",
            //format: "Meddelandet får max vara "+max+" tecken långt (%1 tecken kvar att skriva)",
            pulse: true,
            warn: true,
            delay: 0,
            lineBreakCheck: false,
            failcallback: null,
            onSplit: null
        }, settings);
        var p, timeout;

        function lineBreakCount(str) {
            //return str.split(/\s?\r?\n|\s?\r/).length
            return str.replace('\r\n', '\n').split('\n').length;
        }

        function count(el, container) {
            el = $(el);
            split = "";


            if (settings.splitInto != undefined) {
                if (el.val().length == 0) {
                    split = " / 0 " + settings.type;
                }
                else if (el.val().length <= 120) {
                    split = " / 1 " + settings.type;
                }
                else {
                    split = " / " + (Math.floor((el.val().length - 121) / settings.splitInto) + 2) + " " + settings.type;
                }
            }

            if (settings.lineBreakCheck && lineBreakCount(el.val()) > settings.maxLineBreak) {
                var rows = el.val().replace('\r\n', '\n').split('\n');
                el.val(rows.splice(0, settings.maxLineBreak).join('\n'));
                openMessage(Mikz.Texts.InputMaxLines, Mikz.Texts.Error);
            }

            if (el.val().length > max) {
                el.val(el.val().substring(0, max));
                if (settings.pulse && !p) {
                    pulse(container, true);
                };
                
                if (settings.onSplit != null) {
                    settings.onSplit();
                };
            };

            var charOffset = 0;

            if (settings.delay > 0) {
                if (timeout) {
                    window.clearTimeout(timeout);
                }
                timeout = window.setTimeout(function () {
                    container.html(settings.format.replace(/%1/, (max - el.val().length - charOffset)) + split);
                }, settings.delay);
            } else {
                container.html(settings.format.replace(/%1/, (max - el.val().length - charOffset)) + split);
            }
        };

        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 () {
            var el = $(this);
            var ExLen = (settings.warn && (el.val().length > max));
            var ExLine = (settings.lineBreakCheck && lineBreakCount(el.val()) > settings.maxLineBreak);
            var warnlentext = "Warning: Text will be truncated!";
            var warnlinetext = "Warning: Max " + settings.maxLineBreak + " lines, Text was truncated!";

            if (ExLen || ExLine) {
                var answer = confirm(ExLine ? warnlinetext : warnlentext)

                if (answer) {
                    if (ExLen) {
                        el.val(el.val().substring(0, max));
                    }
                    var rows = el.val().replace('\r\n', '\n').split('\n');
                    if (rows.length > (settings.maxLineBreak)) {
                        el.val(rows.splice(0, settings.maxLineBreak).join('\n'));
                    }
                }
                else if (settings.event && settings.old_max && settings.limit_holder) {
                    settings.event.preventDefault();
                    $(settings.limit_holder).html(settings.old_max);
                    if (settings.failcallback != null && typeof (settings.failcallback) == 'function')
                        settings.failcallback();
                    return false;
                }
            }

            var container;
            if (!settings.container.match(/^<.+>$/)) {
                // use existing element to hold counter message
                container = $(settings.container);
            } else {
                // append element to hold counter message (clean up old element first)
                el.next("." + settings.classname).remove();
                container = $(settings.container)
								.insertAfter(this)
								.addClass(settings.classname);
            }
            el.unbind(".charCounter");

            el.bind("keydown.charCounter", function () { count(this, container); })
				.bind("keypress.charCounter", function () { count(this, container); })
				.bind("keyup.charCounter", function () { count(this, container); })
				.bind("focus.charCounter", function () { count(this, container); })
				.bind("mouseover.charCounter", function () { count(this, container); })
				.bind("mouseout.charCounter", function () { count(this, container); })
				.bind("paste.charCounter", function () {
				    var me = this;
				    setTimeout(function () { count(me, container); }, 10);
				});

            // 20101101 Frans: The code below prevents reconfigure an existing counter (Works without it as far as i can se!!)
            //if (this.addEventListener) {
            //	this.addEventListener('input', function() { count(this, container); }, false);
            //};
            count(this, container);
        });
    };

})(jQuery);

