var slideshows = []; //stores the slides holders (e.g. divs). this is populated by the init_slideshow function
var slides = []; //stores the slides for each slideshow (i.e. slides[0] will store the slides for the first slideshow). this is populated by the init_slideshow function
var slideshow_count = 0; //number of slideshows
var current_slideshow = 0; //the current slideshow. this is used when there are more than one slideshows
var current_slide = []; //stores the current slide for each slideshow. this is populated and manipulated by the init_slideshow and rotate function respectively
var interval = -1; //stores the setTimeout incase we need to terminate it
var timeout = 5000; //the minimum pause between transitions in milliseconds
var transition = 3.0; //the duration of the transition in seconds

//initialised the slideshow, a call to this function should be done when the page load (i.e. in the body tag)
function init_slideshow() {

	//use prototype to select all slideshows on the page. ol_slideshow is the default class name given
	//to each slideshow
	slideshows = $$('.ol_slideshow');
	slideshow_count = slideshows.size();

	for (var i = 0; i < slideshow_count; i++) {
		slides[i] = [];
		slideshows[i].select('img').each(function (item, j) {
			var styles = {
				position : 'absolute',
				top : '0px',
				left : '0px',
				width : '100%',
				height : '100%'
			}

			item.setStyle(styles);
			slides[i][j] = item;
		});
		current_slide[i] = 0;
	}

	//add a random number to the timeout
	generate_timeout();

	interval = setTimeout('rotate()', timeout);
}

function rotate() {
	//current slide
	var now = slides[current_slideshow][current_slide[current_slideshow]];

	current_slide[current_slideshow] = get_next_slide();

	//next slide
	var next = slides[current_slideshow][current_slide[current_slideshow]];

	//bring the current image to the front
	now.setStyle({'zIndex' : parseInt(now.getStyle('zIndex')) - 1});
	next.setStyle({'zIndex' : parseInt(next.getStyle('zIndex')) + 1});

	//scriptaculous effects used to fade in the new image and fade out the old
	new Effect.Fade(now, {duration: transition});
	new Effect.Appear(next, {duration: transition});

	set_next_slideshow();

	interval = setTimeout('rotate()', timeout);
}

function get_next_slide() {
	current_slide[current_slideshow]++;

	if (slides[current_slideshow][current_slide[current_slideshow]] == undefined) {
		return 0;
	}

	return current_slide[current_slideshow];
}


//if we have more than 1 slideshow on the page, we change one image, then move to the next slideshow and repeat
function set_next_slideshow() {
	if (slideshow_count > 1) {
		var temp = current_slideshow;

		while (temp == current_slideshow) {
			current_slideshow = Math.floor(Math.random() * slideshow_count);
		}
	}
}


//generates a random timeout number in milliseconds
function generate_timeout() {
	timeout += (Math.random() * 1000);
}