﻿(function ($) {
    var that, textWidth, offset, width, css, marqueeCss, args, count, stop, dfd, timeout;
    $.fn.textWidth = function () {
        var calc = '<span style="display:none;white-space:nowrap;">' + $(this).text() + '</span>';
        $('body').append(calc);
        var width = $('body').find('span:last').width();
        $('body').find('span:last').remove();
        return width;
    };
    $.fn.marquee = function (_args) {
        that = $(this);
        textWidth = that.textWidth();
        offset = that.width();
        width = offset;
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        };
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        };
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, _args);
        count = 0;
        stop = textWidth * -1;
        dfd = $.Deferred();

        if (args.leftToRight) {
            width = textWidth * -1;
            width++;
            stop = offset;
        } else {
            width--;
        }

        that.css(marqueeCss);
        go();
        return dfd.promise();
    };
    $.fn.marqueePause = function () {
        clearTimeout(timeout);
        return dfd.promise();
    }
    $.fn.marqueePlay = function () {
        clearTimeout(timeout);
        go();
        return dfd.promise();
    }
    $.fn.marqueeSetPos = function (_width) {
        width = _width;
        that.css('text-indent', width + 'px');
        return dfd.promise();
    }
    function go() {
        if (!that.length) return dfd.reject();
        if (width == stop) {
            count++;
            if (count == args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width--;
        }
        timeout = setTimeout(go, args.speed);
    };
})(jQuery);