window.addEventListener ? window.addEventListener('load', initialise_crossfade, false) : window.attachEvent('onload', initialise_crossfade);

var images = new Array(), current=-1, next=0, time_between_steps = 100, time_between_images = 1500;

function initialise_crossfade() {
	css = document.createElement('link');
	css.setAttribute('href','slideshow2.css');
	css.setAttribute('rel','stylesheet');
	css.setAttribute('type','text/css');
	document.getElementsByTagName('head')[0].appendChild(css);
	if (document.getElementById('rotator') != null) {
		images = document.getElementById('rotator').getElementsByTagName('img');
		for(i=0;i<images.length;i++) {
			images[i].xOpacity = .00;
			images[i].style.display = i==0 ? 'block' : 'none';
		}
		setTimeout(advance_crossfade, time_between_steps);
	}
}

function advance_crossfade() {
	if (!isFirstImage()) {
		changeOpacity(images[current], -.05);
	}
	nextOpacity = changeOpacity(images[next], .05);

	if (nextOpacity >= 1) {
		setTimeout(new_crossfade, time_between_images);
	} else {
		setTimeout(advance_crossfade, time_between_steps);
	}
}

function new_crossfade() {
	if (!isFirstImage()) { 
		images[current].style.display = 'none';
	}
	current = nextIndex(current);
	next = nextIndex(current);
	setOpacity(images[next], 0);
	images[next].style.display = 'block';
	setTimeout(advance_crossfade, time_between_steps);
}

function changeOpacity(object, amount) {
	opacity = object.xOpacity;
	opacity+=amount;
	setOpacity(object, opacity);
	return opacity;
}

function setOpacity(object, opacity) {
	object.xOpacity = opacity > .99 ? .99 : opacity;
	object.style.opacity = object.xOpacity;
	object.style.MozOpacity = object.xOpacity;
	object.style.filter = 'alpha(opacity=' + (object.xOpacity*100) + ')';
}

function isFirstImage() {
	return current == -1;
}

function nextIndex(index) {
	return images[index+1] ? index+1 : 0;
}
