var kSwapTimeout = 8000; /* 6*1000 = 6 seconds */
var kSwapRetry = 1000;
var kBlankImage = new Image();
var swapData = new Array();
var currentSwap = 0;
var swapCount = 0;
var inAnimation = false;

document.getNextSwap = function() {
	var nextSwap;

	if(currentSwap + 1 >= swapData.length) {
		nextSwap = 0;
	} else {
		nextSwap = currentSwap + 1;
	}
	
	return nextSwap;
}

document.loadNextImage = function(nextSwap) {
	if(!swapData[nextSwap]['image']) {
		swapData[nextSwap]['image'] = new Image();
		swapData[nextSwap]['image'].src = swapData[nextSwap]['path'];
	}
}

document.swapImage = function() {
	if(inAnimation || swapData.length < 2) {
		return;
	}

	var nextSwap = document.getNextSwap();
	
	if(!swapData[nextSwap]['image']) {
		setTimeout('document.swapImage();', kSwapRetry);
		return;
	}

	var nextImg = document.getElementById('swapImg'+((swapCount+1) % 2));
	
	nextImg.src = swapData[nextSwap]['path'];
	nextImg.setAttribute("title", swapData[nextSwap]['title']);
	nextImg.setAttribute("alt", swapData[nextSwap]['title']);
	
	if(swapData[nextSwap]['animation']) {
		swapData[nextSwap]['animation'].stop();
	}
	
	if(document.swapAnimation) {
		document.swapAnimation();
	}
	
	inAnimation = true;

	// finally, set up the swap container to open this new image as a large one, on click
	var swapContainer = document.getElementById('swapContainer');
	if (swapContainer) {
		swapContainer.onclick = function() { showMediaSlip(swapData[nextSwap]['width'], swapData[nextSwap]['height'], swapData[nextSwap]['path']); };
	}

}

document.swapImageFinish = function() {
	var nextSwap = document.getNextSwap();
	var currentDiv = document.getElementById('swapDiv'+(swapCount % 2));
	var nextDiv = document.getElementById('swapDiv'+((swapCount+1) % 2));
	var tempIndex;
	
	tempIndex = currentDiv.style.zIndex;
	currentDiv.style.zIndex = nextDiv.style.zIndex;
	nextDiv.style.zIndex = tempIndex;
	
	currentSwap = nextSwap;
	swapCount += 1;
	
	nextSwap = document.getNextSwap();
	document.loadNextImage(nextSwap);
	
	inAnimation = false;
}

if(document.initSwap) {
	document.initSwap();
	
	var nextSwap = document.getNextSwap();
	document.loadNextImage(nextSwap);
}