$(function() {
    (function ($) {
        var rollContainer = jQuery('.roll-container')
            , rollContent = rollContainer.find('.roll-content')
            , numberImages = rollContent.children().length
            , rollController = rollContainer.find('.roll-control')
            , controllers = null
            , currentStatus = 0
            , toStatus = 0
            , waitTimer = null
            , stand = 4000;
  
        function getStatus() {
            currentStatus = Number(rollContent.attr('class').match(/\b\d+\b/)[0]);
            toStatus = currentStatus + 1 > numberImages - 1 ? 0 : currentStatus + 1;
        }

        function animate() {
            var position = rollContent.position().left;
            $(rollContent).animate({left: toStatus * -644}, 625, function () {
                rollContent.removeClass(String(currentStatus)).addClass(String(toStatus));

                controllers.removeClass('active');
                rollController.find('.' + String(toStatus)).addClass('active');
  
                getStatus();

                waitTimer = window.setTimeout(animate, stand);
            });
        }
  
        function createControllers() {
            var controls = []
                , node = ''
                , width = numberImages * 14 + (numberImages - 1) * 5;

            for (var i = 0; i < numberImages; i += 1) {
                node = '<div class="';
                node += 'control ' + i;
                if (i === 0) node += ' active first';
                node += '">&nbsp;</div>';
                controls.push(node);
            }

            rollController.width(width);
            rollController.append(controls.join(''));
            controllers = rollController.find('.control');

            rollController.delegate('.control', 'click', function () {
                toStatus = Number(this.className.match(/\b\d+\b/)[0]);
                window.clearTimeout(waitTimer);
                waitTimer = null;
                animate();
            });
        }
  
        rollContent.css({width: 644 * numberImages});
        createControllers();
        getStatus();
        waitTimer = window.setTimeout(animate, stand);
  
    }(jQuery));
});
