var anterior;
var proximo;
var timerFade;
var timerPlay;

function setOpacity(obj, valor) {
    if(obj.xOpacity>.99) {
        obj.xOpacity = .99;
        return;
    }

    obj.style.opacity = valor;
    obj.style.MozOpacity = valor;
    obj.style.filter = "alpha(opacity=" + (valor*100) + ")";
}

function mudarImagem(id) {
    proximo = document.getElementById("img" + id);

    for(i = 1; (document.getElementById("img" + i)) != null; i++) {
        document.getElementById("img" + i).style.display = 'block';
    }

    for(i = 1; (document.getElementById("img" + i)) != null; i++) {
        if(document.getElementById("img" + i).style.opacity == 1) {
            anterior = document.getElementById("img" + i);
            document.getElementById("label" + i).setAttribute("class", " ");
            break;

        } else {
            //vou limpar colocando todos com zero
            document.getElementById("img" + i).style.opacity = 0;
        }
    }

    document.getElementById("label" + id).setAttribute("class", "marcado");

    if(proximo != null) {
        proximo.style.opacity = 0;
        setTimeout(fade,100);
    }
}

function fade() {
    var anteriorOpacity = parseFloat(anterior.style.opacity);
    var proximoOpacity = parseFloat(proximo.style.opacity);

    if(anteriorOpacity <= 0 || proximoOpacity >= 0.9) {
        anterior.style.opacity = 0;
        proximo.style.opacity = 1;

        for(i = 1; (document.getElementById("img" + i)) != null; i++) {
            if(document.getElementById("img" + i).style.opacity != 1) {
                document.getElementById("img" + i).style.display = 'none';
            }
        }

        clearTimeout(timerPlay);
        timerPlay = setTimeout(play,5000);

    } else {
        anteriorOpacity = anteriorOpacity - 0.1;
        proximoOpacity = proximoOpacity + 0.1;

        setOpacity(anterior, anteriorOpacity);
        setOpacity(proximo, proximoOpacity);

        clearTimeout(timerFade);
        timerFade = setTimeout(fade,100);
    }
}

//vai rodar automaticamente
function play() {
    //vai ter o index do atual
    var atual = 0;

    //verifica qual é o está sendo exibido
    for(i = 1; (document.getElementById("img" + i)) != null; i++) {
        if(document.getElementById("img" + i).style.opacity == 1) {
            anterior = document.getElementById("img" + i);
            atual = i;
            break;
        }
    }

    //pega qual é o proximo a ser exibido
    atual = atual + 1;
    if((document.getElementById("img" + atual)) != null) {
        mudarImagem(atual);
    } else {
        mudarImagem(1);
    }
}

