/*jslint browser:true*/
/*global jQuery:false*/
(function ($) {

    var preloadImages = [],
        preloadComplete = false,
        imageUrls = [],
        rotateInterval = 5000,
        imageElem,
        altImageElem,

        getScriptUrl = function () {
            var imagelistUrl = '@@image-carousel-urls',
                // Replace the possible trailing slash from the path.
                pathname = document.location.pathname.replace(/\/$/, '');
            return pathname + '/' + imagelistUrl;
        },

        rotateImages = function (index, isAlt) {

            var img = isAlt ? altImageElem : imageElem,
                otherImg = isAlt ? imageElem : altImageElem;

            img.attr('src', imageUrls[index]);

            otherImg.fadeOut(1500);
            img.fadeIn(1500);

            setTimeout(function () {
                // Set the next index in the array. If it is the
                // last index already, set it to zero.
                var newIndex = (index >= imageUrls.length - 1) ? 0 : index + 1,
                    preloadImage;

                // Mark the preload complete if the index is 0 again.
                if (newIndex === 0) {
                    preloadComplete = true;
                } else if (!preloadComplete) {
                    // Preload next image.
                    preloadImage = new Image();
                    preloadImage.src = imageUrls[newIndex];
                    preloadImages.push(preloadImage);
                }

                rotateImages(newIndex, !isAlt);
            }, rotateInterval);

        };

    $(document).ready(function () {

        // Stop executing if there is no front page image
        // (i.e. the page is not the front page).
        if ($('#front-page-image-wrapper').length === 0) {
            return;
        }

        imageElem = $('#front-page-image-wrapper img');
        altImageElem = $('<img id="alt-image" src="" alt="" style="display: none;" />');
        $('#front-page-image-wrapper').append(altImageElem);

        $.getJSON(getScriptUrl(), function (data) {

            var preloadImage;

            if (data && data.images && data.images.length > 0) {
                imageUrls = data.images;

                // Preload the first image.
                preloadImage = new Image();
                preloadImage.src = imageUrls[0];
                preloadImages.push(preloadImage);

                // Start rotating from the first image after a timeout.
                setTimeout(function () {
                    rotateImages(0, true);
                }, rotateInterval);
            }
        });
    });
}(jQuery));

