(function($){
    var slide;
    $(document).ready(function() {
        slide   =   $('ul.slideshow');
        //Execute the slide, set 4 seconds for each images
        slideShow(3500);
    });
    function gallery(){
        //if no IMGs have the show class, grab the first image
        var show    =   slide.find('li.show'),
            first   =   slide.find('li:first'),
            current =   ( show ?  show : first),
            tryNext =   current.next();

        //Get next image, if it reached the end of the slide, rotate it back to the first image
        var next = ((tryNext.length) ? ((tryNext.attr('id') == 'slideshow-caption') ? first : tryNext) : first);

        //Get next image caption
        var title = next.find('img').attr('title');

        //Set the fade in effect for the next image, show class has higher z-index
        next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);

        //Hide the caption first, and then set and display the caption
        $('#slideshow-caption').animate({bottom:-70}, 300, function () {
            //Display the content
            $('#slideshow-caption h3').html(title);
            $('#slideshow-caption').animate({bottom:0}, 500);
        });

        //Hide the current image
        current.animate({opacity: 0.0}, 1000).removeClass('show');
    }
    function slideShow(speed){
        var first = slide.find('li:first');
        //append a LI item to the UL list for displaying caption
        slide.append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3></div></li>');

        //Set the opacity of all images to 0
        slide.find('li').css({opacity: 0.0});

        //Get the first image and display it (set it to full opacity)
        first.css({opacity: 1.0});

        //Get the caption of the first image from REL attribute and display it
        $('#slideshow-caption h3').html(first.find('img').attr('title'));

        //Display the caption
        $('#slideshow-caption').css({opacity: 0.7, bottom:0});

        //Call the gallery function to run the slide
        var timer = setInterval(function(){gallery();}, speed);

        //pause the slide on mouse over
        slide.hover(
            function () {
                clearInterval(timer);
            },
            function () {
                timer = setInterval(function(){gallery();}, speed);
            }
        );
    }
})(jQuery);
