/*****

Image Cross Fade Redux
Version 1.0
Last revision: 02.15.2006
steve@slayeroffice.com

Please leave this notice intact. 

Rewrite of old code found here: http://slayeroffice.com/code/imageCrossFade/index.html


*****/

window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var d=document, imgs = new Array(), zInterval = null, current=0, pause=false;

var timer;
var pausa = false;
var first = true;

// durata della foto
var tout = 4500;

// durata della transizione
var fout = 50;

// direzione dell'"animazione": 0: destra, 1: sinistra
var direction = 0;

function so_init() {
	if(!d.getElementById || !d.createElement)return;

	imgs = d.getElementById("imageContainer").getElementsByTagName("img");

	current = direction != 0 ? imgs.length - 1 : direction;
	
	for (i = 1; i < imgs.length; i++) 
		imgs[i].xOpacity = 0;
	imgs[current].style.display = "block";
	imgs[current].xOpacity = .99;

	loop();		
}
	
	function setOpacity(obj) {
		if(obj.xOpacity>.99) {
			obj.xOpacity = .99;
			return;
		}
		obj.style.opacity = obj.xOpacity;
		obj.style.MozOpacity = obj.xOpacity;
		obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
	}

function fade(){
		cOpacity = imgs[current].xOpacity;
		if (direction == 0) {
			nIndex = imgs[current + 1] ? current + 1 : 0;
		}
		else {
			nIndex = current > 0 ? current - 1 : imgs.length - 1;
		}
		
		nOpacity = imgs[nIndex].xOpacity;
		
		cOpacity -= .05;
		nOpacity += .05;
		
		imgs[nIndex].style.display = "block";
		imgs[current].xOpacity = cOpacity;
		imgs[nIndex].xOpacity = nOpacity;
		
		setOpacity(imgs[current]);
		setOpacity(imgs[nIndex]);
		
		
		

if (current == 1 && first){
	first = false;
	tmp = Array();
	t = 0;
	for(i = 0; i < imgs.length; i++){
		if (i > 0){
			tmp[t] = imgs[i];
			t = t + 1;
		}
	}
	imgs = tmp;
	tmp = null;
	current = current - 1;
}



	
// se è finita la transazione lascia l'immagine visibile per tout 
		if (cOpacity <= 0) {
			imgs[current].style.display = "none";
			current = nIndex;
//			timer = setTimeout(function(){
//				so_xfade(false);
//			}, tout);
		}
// altrimenti esegue la transazione per un timeout di fout
		else {
//			setTimeout(function(){
//				so_xfade(false);
//			}, fout);
			setTimeout(fade, fout);
		}

}

//function loop(s){
function loop(){
	if (!pausa){
		play();
		timer = setTimeout(function(){
		loop();
		}, tout);
	}else{
		clearTimeout(timer);
	}
}

function play(){
	fade();
}

function next(){
	pausa = true;
	clearTimeout(timer);
	direction = 0;
	play();
}

function prev(){
	pausa = true;
	clearTimeout(timer);
	direction = 1;
	play();	
}

