﻿/*
    This needs to be called from $(window).load() or later.
    Safari and Chrome will not calculate the proper width and height of the image until then.
    Using $(document).ready() will result in a slideshow container of 0px by 0px.
    All other browsers did fine with document, but window worked for all of them.
    
    Markup required:
    
    <div id="slideshow">
        <img src="#" alt="" />
        <img src="#" alt="" style="display:none" />
        <img src="#" alt="" style="display:none" />
        <img src="#" alt="" style="display:none" />
    </div>
    
    Use display:none to play nice with javascript disabled.
    
    Script required:
    
    $(window.load(function() { $("slideshow").slideshow(); }
    
    You can pass { interval, fade } in milliseconds to adjust how long the images are shown.
    interval (default 5 seconds) is the time from completly visible to the next image starting to fade in.
    fade (default is 1.5 seconds) is the time it takes for the image to fade in.
*/

(function($) {
    $.fn.slideshow = function(options) {
        var defaults = {
            interval: 5000,
            fade: 1500
        };
        var options = $.extend(defaults, options);

        return this.each(function() {
            var $div = $(this);
            var $images = $div.find("img");
            var $lastImage = $($images[0]);
            var counter = 1;

            var rotate = function() {
                $lastImage.fadeOut(options.fade);
                $($images[counter]).fadeIn(options.fade, function() {
                    $lastImage = $($images[counter]);
                    counter++;
                    if (counter >= $images.length) { counter = 0; }
                    setTimeout(rotate, options.interval);
                });
            }

            $div.css({
                position: 'relative',
                width: $lastImage.width(),
                height: $lastImage.height()
            });

            $($images).hide().css({
                position: 'absolute', top: 0, left: 0
            });

            $lastImage.show();
            setTimeout(rotate, options.interval);
        });
    }
})(jQuery);
