/**
 * @author Doug Daley
 */

/*
 * Javascript Slideshow
 * 
 * A simple javascript slideshow with seemless transitions and load complete checking prior to
 * transitions.
 * 
 * Uses the YAHOO! UI Toolkit.
 */

var	image = new Array();
var	loaded = new Array();
var	slides = new Array();
var	current_index = 0;
var	index_max;
var	first = true;
var	timer;
var	pause_time = 5000;
var set_loaded_fn_ref;

// slides...
slides[0] = 'fileadmin/templates/img/slide1.jpg';
slides[1] = 'fileadmin/templates/img/slide2.jpg';
slides[2] = 'fileadmin/templates/img/slide3.jpg';
slides[3] = 'fileadmin/templates/img/slide4.jpg';
slides[4] = 'fileadmin/templates/img/slide5.jpg';
slides[5] = 'fileadmin/templates/img/slide6.jpg';

/**
 * Call to begin slideshow.
 */
window.slideshow =
function()
{	
	if (first)
	{
		for (i in slides)
		{
			loaded[i] = false;
			index_max = i;
		}
		
		YAHOO.util.Dom.setStyle('slideshow_top', 'opacity', 0);
		YAHOO.util.Dom.setStyle('slideshow_top', 'background', 'url('+slides[0]+')');
		YAHOO.util.Dom.setStyle('slideshow_bottom', 'background', 'url('+slides[0]+')');
		
		preload_slides();
		
		previous_slide = slides[0];		
		first = false;
		
		timer = setTimeout(slideshow, (pause_time/2));
	}
	else
	{
		if (loaded[current_index])
		{
			slide = slides[current_index];
			
			transition(slide);
			
			if (current_index == index_max)
				current_index = 0;
			else
				current_index++;
				
			previous_slide = slide;
		}
		
		timer = setTimeout(slideshow, pause_time);
	}
	
	
};


/**
 * Ensure that slides a loaded before attempting to transition to them.
 * 
 * Sets loaded[index] when slides[index] has completed pre-loading.
 */
preload_slides =
function()
{
	var i;
	for (i in slides)
	{		
		image[i] = new Image();		
		image[i].loaded = loaded;
		image[i].i = i;
		image[i].onload = function(){this.loaded[this.i] = true;};		
		image[i].src = slides[i];
	}
};


/**
 * Create and perform a seemless transition by fading in the front div after setting the background of 
 * the bottom div to the previous slide, the opacity of the top div to 0, and the background of the top 
 * div to the new slide.
 * 
 * @param {Object} new_image
 */
transition =
function(new_image)
{
	YAHOO.util.Dom.setStyle('slideshow_bottom', 'background', "url("+previous_slide+")");
	YAHOO.util.Dom.setStyle('slideshow_top', 'opacity', 0);
	YAHOO.util.Dom.setStyle('slideshow_top', 'background', "url("+new_image+")");
	
	var fade_anim = new YAHOO.util.Anim('slideshow_top', { opacity: { to: 1 } }, 1, YAHOO.util.Easing.easeIn);
	fade_anim.animate(); 
};



// start the slideshow on window load
YAHOO.util.Event.addListener(window, 'load', window.slideshow);