var currentImage = 0;

var NB_ICON = 16;

var gjImg, gjImgBg, select;

function nextImage() {
	// Set foreground image to the same as the background one
	gjImg[0].src = gjImgBg[0].src;
	// and make the foreground image opaque.
	gjImg.css("opacity", 1.0);
	gjImg.css("display", "block");
	
	// Set the background image to the next one
	currentImage = (currentImage + 1) % NB_ICON;
	var icon = document.getElementById("icon" + currentImage);

	gjImgBg[0].src = icon.src.replace("ico", "gj");
	
	var left = ((currentImage % 4))*60;
	var top = Math.floor(currentImage /4)*60
	
	$(select).animate({left:left+"px", top:top+"px"}, 1000);
	gjImg.fadeOut(1000, function() {
		window.setTimeout(nextImage, 3000);
	});
	window.setTimeout(swapIcons, 2000);
}

function random(max) {
	return Math.floor(Math.random() * max);
}

function swapIcons() {
	// Swap a random icon, avoiding the ones in the current transition
	var swapIdx = random(NB_ICON-2);
	if (swapIdx >= currentImage-1) {
		swapIdx += 2;
		swapIdx %= NB_ICON;
    }

    // Edge case when we're rotating back to the start
    if (currentImage == 0 && swapIdx == 11) {
	    swapIdx = 1;
	}

	var swappedIcon = document.getElementById("icon" + swapIdx);
	if (swappedIcon == null) {
		alert("swap " + swapIdx);
	}
	
	var newSrcIdx = random(moreGoojets.length);
	var oldSrc = swappedIcon.src;
	swappedIcon.src = moreGoojets[newSrcIdx];
	moreGoojets[newSrcIdx] = oldSrc;
}