function fadeOut() {
    
    var alpha = document.getElementById('background1').style.opacity;
    alpha = alpha - 0.01;
    document.getElementById('background1').style.opacity = alpha;
    if (alpha > 0.01) {
        fadeOutId = setTimeout("fadeOut()",10);
    } else {
        clearTimeout(fadeOutId);
        document.getElementById('background1').style.opacity = 0;
        var randomNumber = Math.floor(1 + Math.random()*3);
        document.getElementById('background1').style.backgroundImage = 'url(/images/backgrounds/' + randomNumber + '.jpg)';
    }
}

function fadeIn() { 
    var alpha2 = parseFloat(document.getElementById('background1').style.opacity);
    alpha2 = alpha2 + 0.01;    
    document.getElementById('background1').style.opacity = alpha2;
    if (alpha2 < 0.99) {       
        fadeInId = setTimeout("fadeIn()",10);
    } else {
        clearTimeout(fadeInId);
        document.getElementById('background1').style.opacity = 1;
    }    
}

var cas = 1;

function wait() {
    cas = cas + 1;
    id = setTimeout("wait()",6000);
    if (cas == 3) {
        document.getElementById('background1').style.opacity = 0;
        fadeIn();
        clearTimeout(id);      
        cas = 1;
    }
}

var firstOpen = 1;

function setBackground() {  
    
    if (document.body) {
        if (firstOpen == 1) {
            document.getElementById('background1').style.opacity = 0;
            var randomNumber = Math.floor(1 + Math.random()*3);
            document.getElementById('background1').style.backgroundImage = 'url(/images/backgrounds/' + randomNumber + '.jpg)';
            fadeIn();
            firstOpen = 0;
        } else {
            document.getElementById('background1').style.opacity = 1;
            fadeOut();                       
            wait();    
        }
    }
    setTimeout("setBackground()",30000);
}
