/**
 * Script de Crossfade reescrito para implementar mais funcionalidades.
 **/

function get(id) { return d.getElementById(id) }

window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var d = document,		// Apenas comodismo por aqui.
	imgs = new Array(), // imagens no div
	zInterval = null,   // lolwut?
	current=0,			// o que está sendo exibido
	next = 0,			// proximo
	animando=false,		// está animando?
	pause=false,		// está pausado? (??)
	tAtivo=false,
	fDelay = 6000,
	fTimer=null;		// timer a ser usado

function pausa(st) {
	if (animando) {
		//setTimeout(pausa, 50);
		return;
	}
	tAtivo = false;
	pause = st;
	clearTimeout(fTimer);
	if (!pause) { timer("so_xfade", fDelay/2); }
}

function avanca(force) {
	if (!animando) {
		tAtivo = false;
		clearTimeout(fTimer);
		timer("so_xfade", 1);
		return true;
	}
	return false;
}

function volta(force) {
	if (!animando) {
		next = current==0?imgs.length-1:current-1;
		tAtivo = false;
		clearTimeout(fTimer);
		timer("so_xfade", 1);
		return true;
	}
	return false;
}

function so_init() {
	if (!d.getElementById || !d.createElement)
		return;

	// Pega as imagens no container
	imgs = d.getElementById("fadeContainer").getElementsByTagName("img");
	
	// Deixa todas 0% visiveis
	for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0;
	
	// Deixa a primeira visível
	imgs[0].style.display = "block";
	imgs[0].xOpacity = 1;
	
	next = imgs[current+1]?current+1:0;
	
	// Inicia o timer
	animando = false;
	timer("so_xfade", fDelay);
}

function so_xfade() {
	if (!pause && imgs.length > 1) {
		animando = true;
		
		cOpacity = imgs[current].xOpacity;
		nIndex = next;
		
		nOpacity = imgs[nIndex].xOpacity;
		
		//return;
		cOpacity -= parseFloat(.05);
		nOpacity = parseFloat(1)-parseFloat(cOpacity);
		
		imgs[nIndex].style.display = "block";
		imgs[current].xOpacity = cOpacity;
		imgs[nIndex].xOpacity = nOpacity;
		
		setOpacity(imgs[current]); 
		setOpacity(imgs[nIndex]);
		
		if (cOpacity <= 0) {
			imgs[current].style.display = "none";
			current = nIndex;
			next = imgs[current+1]?current+1:0;
			timer("so_xfade", fDelay);
			animando = false;
		} else {
			timer("so_xfade",50);
		}
	}
}

function setOpacity(obj) {
	if(obj.xOpacity>.99) {
		obj.xOpacity = 1;
		return;
	}
	obj.style.opacity = obj.xOpacity;
	obj.style.MozOpacity = obj.xOpacity;
	obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
}

function timer(func, time) {
	if (!tAtivo) {
		tAtivo = true;
		clearTimeout(fTimer);
		fTimer = setTimeout("tAtivo = false; "+func+"();", time);
		tAtivo = true;
	}
}