var LochaberCycle = {

    imgs: new Array(),

    interval: 5000,

    currentIndex: 0,

    init: function(images) {

        LochaberCycle.imgs = images;

        if (LochaberCycle.imgs.length > 1) {

            // preload the first  image...
            LochaberCycle.preload(LochaberCycle._image(0));

        }

    },

    // Gives us a circular array.
    _image: function(index) {
        return LochaberCycle.imgs[index % LochaberCycle.imgs.length];
    },

    run: function() {

        var current = LochaberCycle._image(LochaberCycle.currentIndex + 1);

        // alternate fg and bg based on iteration mod 2

        toFadeIn = $('#LochaberHeading' + ((LochaberCycle.currentIndex + 1) % 2 != 0 ? '1' : '2'));
        toFadeOut = $('#LochaberHeading' + ((LochaberCycle.currentIndex + 1) % 2 == 0 ? '1' : '2'));

     

            // 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);

                LochaberCycle.currentIndex++;

                // preload next image to set the loop going again...
                var next = LochaberCycle._image(LochaberCycle.currentIndex + 1);

                LochaberCycle.preload(next);

            });

 

    },

    preload: function(img) {

        // need to preload?

        if (img.preloaded) {
            setTimeout(LochaberCycle.run, LochaberCycle.interval);
            return;

        } else {

            image = jQuery("<img>").load(
                function() {
                    setTimeout(LochaberCycle.run, LochaberCycle.interval);
                    img.preloaded = true;
                }
            );

            image.attr("src", img.src);
            image.attr("alt", img.alt);

        }

    }
}

$(function() {
    LochaberCycle.init(LochaberHeaders);
});

