// Hook into the onload event listener
if (window.addEventListener) {
	window.addEventListener('load', xfade_init, false);
} else {
	window.attachEvent('onload', xfade_init);
}

// Configure the image xfade script
var delaySeconds = 3;
var fadeDelay = 50;
var fadeRate = 0.05;
function xfade_init() {
	// Maximize browser compatibility
	if(!document.getElementById || !document.createElement) return;
	
	// Validate that the image loader is used
	if (!document.getElementById('imageContainer')) return;
	
	// Set the opacity of the images for the page
	var imgs = document.getElementById('imageContainer').getElementsByTagName('img');
	for(var i = 1; i < imgs.length; i++)
		imgs[i].xOpacity = 0;
	imgs[0].style.display = 'block';
	imgs[0].xOpacity = .99;
	
	// Start the fade timer
	setTimeout(xfade_execute, delaySeconds * 1000);
}

// Fade the images
var current = 0, zInterval = null, pause = false;
function xfade_execute() {
	// Load the images in the container
	var imgs = document.getElementById('imageContainer').getElementsByTagName('img');
	
	// Get the current and next opacities
	cOpacity = imgs[current].xOpacity;
	nIndex = imgs[current+1] ? current + 1 : 0;
	nOpacity = imgs[nIndex].xOpacity;
	
	// Calculate the opacity to continue the fade
	cOpacity -= fadeRate; 
	nOpacity += fadeRate;
	imgs[nIndex].style.display = 'block';
	imgs[current].xOpacity = cOpacity;
	imgs[nIndex].xOpacity = nOpacity;
	
	// Set the new capacity for the images
	setOpacity(imgs[current]); 
	setOpacity(imgs[nIndex]);
	
	// Set the timeout to start the next fade
	if(cOpacity <= 0) {
		imgs[current].style.display = 'none';
		current = nIndex;
		setTimeout(xfade_execute, delaySeconds * 1000);
	} else {
		setTimeout(xfade_execute, fadeDelay);
	}
}

// Set the opacity of the object
function setOpacity(obj) {
	if (obj.xOpacity > .99) {
		obj.xOpacity = .99; // Opacity cannot be more than .99
	} else {
		obj.style.opacity = obj.xOpacity;
		obj.style.MozOpacity = obj.xOpacity;
		obj.style.filter = 'alpha(opacity=' + (obj.xOpacity * 100) + ')';
	}
}