jQuery(document).ready(function($) {
    $('.gallery').each(function() {
        var TIMEOUT = 3000,
            TRANSITION_TIME = 250,
            gallery = $(this),
            galleryItems = $('.gallery-item', this),
            currentItem = 0;

        if (galleryItems.length < 2) {
            return;
        }
        $('.gallery-item:not(:first)', this).hide();

        var nextImage = function() {

            var oldImg = galleryItems.eq(currentItem),
                newImg = galleryItems.eq(currentItem + 1);

            currentItem += 1;

            oldImg.fadeOut(TRANSITION_TIME, function() {
                oldImg.hide();
                newImg.fadeIn(TRANSITION_TIME, function() {
                    if (currentItem >= galleryItems.length - 1) {
                        gallery.find('.restart-slideshow').fadeIn('fast');
                        return;
                    }
                    setTimeout(nextImage, TIMEOUT);
                });
            });
        };

        var startSlideshow = function() {
            gallery.find('.restart-slideshow').hide();
            currentItem = 0;
            setTimeout(nextImage, TIMEOUT);
        };

        $(this).append($('<a href="#" class="restart-slideshow">restart slideshow</a>').click(function() {
            galleryItems.hide().eq(0).show();
            startSlideshow();
            return false;
        }));

        startSlideshow();

    });
});

