(function($){"use strict";

$('.sp-widget-scoreboard').live('registered', function() {
    var $widget = $(this);
    var $left = $('.sp-scoreboard-control-left', $widget);
    var $right = $('.sp-scoreboard-control-right', $widget);
    var $scoreboard = $('.sp-scoreboard', $widget);

    var gameWidth = $('li:first', $scoreboard).width();
    var scoreboardWidth = $scoreboard.width();
    var games = $('li', $scoreboard).length;
    var finalGames = $('li.sp-game-final', $scoreboard).length;
    var scheduledGames = games - finalGames;
    var allGamesWidth = games * gameWidth;
    var gamesToMove = 2;

    $right.click(function() {
        var cur = parseInt($scoreboard.css("margin-left"));
        var n = cur - (gameWidth * gamesToMove);

        if (allGamesWidth + n < scoreboardWidth) {
            n = -allGamesWidth + scoreboardWidth;
        }

        $scoreboard.stop().animate({ marginLeft: n + "px" });
    });

    $left.click(function() {
        var cur = parseInt($scoreboard.css("margin-left"));
        var n = cur + (gameWidth * gamesToMove);

        if (n > 0) {
            n = 0;
        }

        $scoreboard.stop().animate({ marginLeft: n + "px" });
    });

    // start so there are three final games visible
    var hideGames = finalGames - 3;
    if (scheduledGames < 3) {
        hideGames -= 2 - scheduledGames;
    }
    $scoreboard.css({ marginLeft: "-" + ( hideGames * gameWidth ) + "px" });
});

})(jQuery);

