(function () {


    jQuery.fn.randomslideshow = function (config) {
    
        this.each(function (index) {
            jQuery.randomslideshow.instanceList.push(
                new RandomSlideshow(this)
            );
        });
    
    }


    jQuery.randomslideshow = {
        instanceList: []
    };


    var RandomSlideshow = function (containerElement) {
        this.container = jQuery(containerElement);
        this.fadeSlide = null;
        this.imageUrlList = [];
        this.currentImageIndex = null;
        this.minDelay = 2000;
        this.maxDelay = 8000;
        this.delayDifference = this.maxDelay - this.minDelay;
        var thisSlideshow = this;
        this.imageCount = this.container.find('img').each(function (i) {
            thisSlideshow.imageUrlList.push(this.src);
            var image = jQuery(this);
            if (image.is('.primary')) {
                thisSlideshow.currentImageIndex = i;
                thisSlideshow.fadeSlide = image;
            } else {
                image.remove();
            }
        }).length;
        this.switchAfterRandomDelay();
        thisSlideshow = null;
    }


    RandomSlideshow.prototype.switchAfterRandomDelay = function () {
        var thisSlideshow = this;
        var randomDelay = this.minDelay + Math.floor(Math.random() * this.delayDifference);
        setTimeout(function () {
            thisSlideshow._next();
            thisSlideshow.switchAfterRandomDelay();
        }, randomDelay);
    }


    RandomSlideshow.prototype._next = function () {
        this.container.css('backgroundImage', 'url("'+this.fadeSlide.attr('src')+'")');
        this.fadeSlide.hide();
        this.currentImageIndex++;
        if (this.currentImageIndex >= this.imageCount) {
            this.currentImageIndex = 0;
        }
        this.fadeSlide.attr('src', this.imageUrlList[this.currentImageIndex]);
        this.fadeSlide.fadeIn(2000);
    }


})();
