/**
 * Slideshow
 *
 * Creates a timer based slideshow using prototype v1.6.1 and scriptaculous v1.8.3
 *
 * @author Brendan Smith <brendan@ology.com.au>
 * @version 2.0
 */

var slideshows = [];
var slides = [];
var slideshow_count = 0;
var current_slideshow = 0;
var current_slide = [];
var interval = -1;
var initial_timeout = 1000;
var timeout = 3500;
var transition = 1.0;
var changing_event = null;

function init_slideshow(container) {
	slideshows = $$('.' + container);
	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',
				right : '0px',
				zIndex : '1'
			}

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

	generate_timeout();

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

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

	current_slide[current_slideshow] = get_next_slide();

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

	if (typeof(changing_event) == 'function') {
		changing_event(current_slide);
	}

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

	//update hero link
	$$('div.control a').each(function (element, i) {
		if (i == current_slide) {
			element.className = 'activeLink';
		} else {
			element.className = '';
		}
	});

	//now.style.display = 'none';
	new Effect.Fade(now, {duration: transition});
	new Effect.Appear(next, {from: 0.25, to: 1.0, 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];
}

function set_next_slideshow() {
	if (slideshow_count > 1) {
		var temp = current_slideshow;

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

function show_hero(value){
	var size = $$('.ol_slideshow')[0].children.length;
	for (var i = 0; i < size; i++) {
		if ((value != i)&&($('img_'+i).visible())){
			$('img_'+i).hide();
		} else if ((value == i)&&(!$('img_'+i).visible())){
			Effect.Appear('img_'+i, {from: 0.25, to: 1.0});
		}
	}

	if (typeof(changing_event) == 'function') {
		changing_event(value);
	}

	//update hero link
	$$('div.control a').each(function (element, i) {
		if (i == value) {
			element.className = 'activeLink';
		} else {
			element.className = '';
		}
	});

	restart_slideshow(value);
}

function restart_slideshow(slide) {
	clearTimeout(interval);
	interval = setTimeout('rotate()', timeout);
	current_slide[current_slideshow] = slide;
}

function generate_timeout() {
	timeout += (Math.random() * 1000);
}
