function nextGame()
{
	if (gameIndex >= numGames -1)
		gameIndex = 0;
	else		
		gameIndex++;

	document.getElementById('gameText').innerHTML = gameText[gameIndex];
	document.getElementById('gameName').innerHTML = gameName[gameIndex];
	
	Shadowbox.clearCache(); // <= clear Shadowbox's cache
	Shadowbox.setup(); // <= set up all Shadowbox links	
	return 0;
};

function prevGame()
{
	if (gameIndex <= 0)
		gameIndex = numGames-1;
	else		
		gameIndex--;

	document.getElementById('gameName').innerHTML = gameName[gameIndex];
	document.getElementById('gameText').innerHTML = gameText[gameIndex];

	Shadowbox.clearCache(); // <= clear Shadowbox's cache
	Shadowbox.setup(); // <= set up all Shadowbox links	
	
	return 0;
}; 

(function(){
  $.fn.infiniteCarousel = function(){
    function repeat(str, n){
      return new Array( n + 1 ).join(str);
    }

  return this.each(function(){
    var $wrapper = $('> div', this),
    $slider = $wrapper.find('> ul'),
    $items = $slider.find('> li'),
    $single = $items.filter(':first')

    singleWidth = $single.outerWidth(),
    visible = Math.ceil($wrapper.innerWidth() / singleWidth),
    currentPage = 1,
    pages = Math.ceil($items.length / visible);

    // pad with empty element if required
    if ($items.length % visible != 0){
      $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
      $items = $slider.find('> li');
    }

    // create carousel padding on left and right (cloned)
    $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
    $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
    $items = $slider.find('> li');

    // reset scroll
    $wrapper.scrollLeft(singleWidth * visible);

    // paging function
    function gotoPage(page){
      var dir = page < currentPage ? -1 : 1,
      n = Math.abs(currentPage - page),
      left = singleWidth * dir * visible * n;

      $wrapper.filter(':not(:animated)').animate({
        scrollLeft : '+=' + left
      }, 250, function(){
      // if page == last page - then reset position
      if (page > pages){
        $wrapper.scrollLeft(singleWidth * visible);
        page = 1;
      } else if (page == 0){
        page = pages;
        $wrapper.scrollLeft(singleWidth * visible * pages);
      }

      if (dir == 1)
      	nextGame();
      else
	prevGame();

      currentPage = page;
      });
    }

    // bind links
    $('li#games-nav-next a', this).click(function () {
      gotoPage(currentPage + 1);
      return false;
    });
    $('li#games-nav-prev a', this).click(function () {
      gotoPage(currentPage - 1);
      return false;
    });

    $(this).bind('goto', function (event, page) {
      gotoPage(page);
    });

  // automatic
      $(this).bind('next', function(){
        gotoPage(currentPage + 1);
      });
    });
  };
})(jQuery);
