/*
 * hyCMS
 * Copyright(C)2008 by Friedrich Gräter
 * Published under the terms of the Lesser GNU General Public License v2
 *
 * AnimationKit backend: Switching a set of images
 *
 * Please Note: This module has to be clean from all dependencies to predicateJS!
 *				controller.jsh and opacity.js has to be included first.
 *
 */
 
/*
 * ak_switchImages(imageList, domImageA, domImageB, interval, speed)
 *
 * This method will crossfade the images "domImageA" and "domImageB". At
 * each fading, a random image from "imageList" will be selected. The crossfades
 * should happend in the given "interval" with a gievn "speed".
 *
 * Initially "containerA" will be set to a random image.
 *
 * Return value:
 *		The id of the controlling timer
 *
 */
function ak_switchImages(imageList, containerA, containerB, interval, speed)
{
	var unlocked = false;
	var lastImage;
	var images = []

	// Select a image
	function __selectImage(without)
	{
		var number = 0;
		do {
			number = Math.floor(Math.random() * 1000) % (imageList.length);
		} while ((without != null) && (number == without) && (imageList.length > 1))

		return number;
	}
	
	function __switchImages()
	{
		if (unlocked == false) return;
	
		var tmpContainer = containerA;

		lastImage = __selectImage(lastImage);
		containerB.src = imageList[lastImage];

		ak_setOpacity(containerB, 0);
		containerA.style.zIndex = 1;	
		containerB.style.zIndex = 2;

		ak_applyAnimation("opacity", containerB, {destOpacity: 1}, speed, false);

		containerA = containerB;
		containerB = tmpContainer;
	}
	
	// Preload all images first
	for (var idx = 0; idx < imageList.length; idx ++) {
		var image = new Image();
		image.src = imageList[idx];
		images.push(image);
	}
	
	// Set initial state
	lastImage = __selectImage();
	
	ak_setOpacity(containerA, 1);
	ak_setOpacity(containerB, 0);	

	// Wait until first image is inside cache
	var cache = setInterval(__waitCache, 1000);

	function __waitCache()
	{	
		if (images[lastImage].complete != true)
			return;
	
		unlocked = true;
				
		window.clearInterval(cache);
	
		containerA.src = imageList[lastImage];
	}
	
	// Start switching animation
	var timer = window.setInterval(__switchImages, interval);
	
	return timer;
}


