﻿(function($) {
    $.fn.slideshow = function(options) {
        var defaults = {
            images: new Array(),
            minTimeout: 6500,
            maxTimeout: 15000,
            fadeTime: 2000
        };
        var opts = $.extend(defaults, options);
        var currentIndices = new Array();
        opts.images = jQuery.makeArray(opts.images);
        if (opts.images.length == 0) {
            return this.each(function(options) { });
        }
        $.preload(opts.images);
        return this.each(function(options) {
            var index = currentIndices.length;
            var $this = $(this);
            currentIndices[index] = jQuery.inArray($this.attr('src'), opts.images);
            $this.parent().css('background-image', "url('" + $this.attr('src') + "')");
            setTimeout(function() { swapImage($this, index); }, getRandomNumber(opts.minTimeout, opts.maxTimeout));
        });
        function getRandomNumber(min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        }
        function setImage(img, newImageIndex, callbackFunction) {
            img.fadeIn('slow', function() {
                $.preload(jQuery.makeArray(opts.images[newImageIndex]), {
                    onFinish: function() {
                        img.parent().css('background-image', "url('" + opts.images[newImageIndex] + "')");
                        img.fadeOut(opts.fadeTime, function() {
                            img.attr('src', opts.images[newImageIndex]);
                            callbackFunction();
                        });
                    }
                });
            });
        }
        function swapImage(img, index) {
            var rndNum = getRandomNumber(0, opts.images.length - 1);
            while (jQuery.inArray(rndNum, currentIndices) != -1 && currentIndices.length < opts.images.length) {
                rndNum = getRandomNumber(0, opts.images.length - 1);
            }
            currentIndices[index] = rndNum;
            setImage(img, rndNum, function() { setTimeout(function() { swapImage(img, index); }, getRandomNumber(opts.minTimeout, opts.maxTimeout)); });
        }
    }
})(jQuery);