$(function () {
  var stoped  = false;
  var timeout = 4000;
  var games   = $('#games_gallery .game-show');
  var curr    = games[0];
  var next    = next_game();

  function next_game() {
    index = (games.index(curr) + 1) % games.length;
    return games[index];
  }

  function go_to_next_game() {
    next = next_game();
    $(curr).fadeOut('slow', function() {
      $('div[index=' + $(this).attr('index') + '] a.game_small_img').removeClass('active');
      $('div[index=' + $(next).attr('index') + '] a.game_small_img').addClass('active');
      $(next).fadeIn('slow');
    });
    curr = next;
    return false;
  }

  function go_to_game(game) {
    $(curr).fadeOut('slow', function() {
      $(game).fadeIn('slow');
    });
    curr = game;
    return false;
  }

  var setAutoAdvance;

  var advancer = function() {
    setAutoAdvance = setTimeout(function() {
      if (!stoped) {
        go_to_next_game();
        advancer();
      }
    }, timeout);
  };
  
  advancer();

  if (typeof(manual_select_gallery) != 'undefined') {
    $('.img_block a.game_small_img').click(function() {
      stoped = true;
      $('a.game_small_img.active').removeClass('active');
      game = $('div.game-show[index=' + $(this).parent().attr('index') + ']');
      go_to_game( game );
      $(this).addClass('active');
      return false;
    });
  }
});
