var mastheadCycle = {

    imgs: new Array(),

    interval: 10000,

    currentIndex: 0,

    init: function(images) {

        mastheadCycle.imgs = images;

        if (mastheadCycle.imgs.length > 1) {

            // preload the first  image...
            mastheadCycle.preload(mastheadCycle._image(0));

        }

    },

    // Gives us a circular array.
    _image: function(index) {
        return mastheadCycle.imgs[index % mastheadCycle.imgs.length];
    },

    run: function() {

        var current = mastheadCycle._image(mastheadCycle.currentIndex + 1);

        // alternate fg and bg based on iteration mod 2

        toFadeIn = $('#home_masthead' + ((mastheadCycle.currentIndex + 1) % 2 != 0 ? '1' : '2'));
        toFadeOut = $('#home_masthead' + ((mastheadCycle.currentIndex + 1) % 2 == 0 ? '1' : '2'));

        $('#caption').fadeOut(500, function() {

            // set source of element to fade in

            toFadeIn.attr('src', current.src);
            toFadeIn.attr('alt', current.caption);
            toFadeIn.fadeIn(1500);

            toFadeOut.fadeOut(1500, function() {

                //                $('#caption').text(current.caption);
                //                $('#caption').fadeIn(500);

                mastheadCycle.currentIndex++;

                // preload next image to set the loop going again...
                var next = mastheadCycle._image(mastheadCycle.currentIndex + 1);

                mastheadCycle.preload(next);

            });

        });

    },

    preload: function(img) {

        // need to preload?

        if (img.preloaded) {
            setTimeout(mastheadCycle.run, mastheadCycle.interval);
            return;

        } else {

            image = jQuery("<img>").load(
                function() {
                    setTimeout(mastheadCycle.run, mastheadCycle.interval);
                    img.preloaded = true;
                }
            );

            image.attr("src", img.src);
            image.attr("alt", img.alt);

        }

    }
}

$(function() {
    mastheadCycle.init(mastheadGallery);
});
