﻿(function($) {
    var timer, width, obj, speed, step;

    function tick() {
        var o = obj.children('table');
        var x = o.position().left;
        var pos;
        if (x + width < 0) pos = obj.width();
        else pos = x - step;
        o.css('left', pos + 'px');
    }

    var methods = {
        init: function(options) {
            if (!options.items) $.error('jQuery.ticker must have items to scroll');
            var defaults = {
                speed: 10,
                step: 1,
                rtl: true,
                autostart: true
            };
            var options = $.extend(defaults, options);

            return this.each(function() {
                obj = $(this);

                if (timer) clearInterval(timer);
                else {  // we only want to bind the hover event once!
                    obj.hover(function(e) {
                        clearInterval(timer);
                    }, function(e) {
                        timer = setInterval(tick, options.speed);
                    });
                }
                obj.css({
                    width: obj.width() + 'px',
                    height: obj.height() + 'px',
                    overflow: 'hidden',
                    position: 'relative'
                });

                var html = '<table style="position:absolute; border-collapse: collapse"><tr>';
                for (var i = 0; i < options.items.length; i++) {
                    html += '<td style="white-space:nowrap">'
							+ options.items[i] + '</td>';
                }
                html += '</tr></table>';
                obj.html(html);

                width = obj.children('table').width();
                speed = options.speed;
                step = options.step;

                if (options.rtl) {
                    obj.children('table').css({
                        left: (obj.width() + 1) + 'px'
                    });
                }

                if (options.autostart) { timer = setInterval(tick, options.speed); }

            });
        },
        start: function() {
            return this.each(function() {
                timer = setInterval(tick, speed);
            });
        },
        stop: function() {
            return this.each(function() {
                clearInterval(timer);
            });
        }
    };
    $.fn.ticker = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ticker');
        }
    };
})(jQuery);
