/*
 * Fade header images in and out
 */

var current = 1;
var count = 0;
var loaded = 0;

//fade the images in succession
var fadeHeader = function(){
    var fadeOut = {
        node: dojo.byId("header_image" + current),
        duration: 5000
    };

    var next;
    if(current == count){
        current = 1;
        next = 1;
    }
    else{
        next = current + 1;
        current ++;
    }

    var fadeIn = {
        node: dojo.byId("header_image" + next),
        duration: 5000
    }

    dojo.fadeOut(fadeOut).play();
    dojo.fadeIn(fadeIn).play();

    window.setTimeout(fadeHeader, 8000);
};

function setupHeader(){
    //remove the static header image and show the first image
    dojo.style(dojo.byId("slideshow"), "background", "none");
    dojo.style(dojo.byId("header_image1"), "display", "block");

    //set the opacity to 0 on all but the first image and show them
    for(var i = 2; i <= count; i++){
        dojo.style(dojo.byId("header_image" + i), "opacity", "0");
        dojo.style(dojo.byId("header_image" + i), "display", "block");
    }

    //start the fading
    fadeHeader();
}

var checkloaded = function(){
    if(loaded == count){
        setupHeader();
    }
    else{
        window.setTimeout(checkloaded, 500);
    }
}

dojo.addOnLoad(function(){
    //count the images
    count = dojo.query('.slide').length;

    //preload the images
    var preloader = [];
    for(var i = 1; i <= count; i++){
        preloader[i] = new Image();
        preloader[i].onload = function(){
            loaded++;
        };
        preloader[i].src = '/images/header/1.jpg';
    }

    //wait for the images to load
    checkloaded();
});
