
var Cycle = {

    imgs: new Array(),

    interval: 4000,

    currentIndex: 0,

    init: function(images) {

        Cycle.imgs = images;

        if (Cycle.imgs.length > 1) {

            // preload the first  image...
            Cycle.preload(Cycle._image(0));

        }

    },

    // Gives us a circular array.
    _image: function(index) {
        return Cycle.imgs[index % Cycle.imgs.length];
    },

    run: function() {

        var current = Cycle._image(Cycle.currentIndex + 1);

        // alternate fg and bg based on iteration mod 2
        toFadeIn = $('#blend' + ((Cycle.currentIndex + 1) % 2 != 0 ? '1' : '2'));
        toFadeOut = $('#blend' + ((Cycle.currentIndex + 1) % 2 == 0 ? '1' : '2'));

        $('#caption').fadeOut(1000, 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);

                Cycle.currentIndex++;

                // preload next image to set the loop going again...
                var next = Cycle._image(Cycle.currentIndex + 1);

                Cycle.preload(next);

            });

        });

    },

    preload: function(img) {

        // need to preload?

        if (img.preloaded) {
            setTimeout(Cycle.run, Cycle.interval);
            return;

        } else {

            image = jQuery("<img>").load(
                function() {
                    setTimeout(Cycle.run, Cycle.interval);
                    img.preloaded = true;
                }
            );

            image.attr("src", img.src);
            image.attr("alt", img.alt);

        }

    }
}

$(function() {
    Cycle.init(Headers);
});

