(function () {


    jQuery.fn.slideshow = function (config) {
    
        this.each(function (index) {
            jQuery.slideshow.instanceList.push(
                new Slideshow(this, config.imageList)
            );
        });
    
    }


    jQuery.slideshow = {
        instanceList: []
    };


    var Slideshow = function (containerElement, imageList) {
        this.container = jQuery(containerElement);
        this.fadeSlide = this.container.find('img');
        this.imageList = [];
        this.imageIsLoaded = {};
        var thisSlideshow = this;
        for (var i=0; i < imageList.length; i++) {
            this.imageList[i] = document.createElement('img');
            this.imageList[i].onload = function () {
                thisSlideshow.imageIsLoaded[this.src] = true;
            };
            this.imageList[i].src = imageList[i];
        }
        this.currentImageIndex = 0;
        this.slideDelay = 2000;
        this.switchAfterDelay();
    }


    Slideshow.prototype.switchAfterDelay = function () {
        var thisSlideshow = this;
        setTimeout(function () {
            thisSlideshow._next();
            thisSlideshow.switchAfterDelay();
        }, this.slideDelay);
    }


    Slideshow.prototype._next = function () {
        var nextIndex = this.currentImageIndex + 1;
        if (nextIndex >= this.imageList.length) {
            nextIndex = 0;
        }
        if (! this._isImageLoaded(this.imageList[nextIndex].src)) {
            return;
        }
        this.container.css('backgroundImage', 'url("'+this.fadeSlide.attr('src')+'")');
        this.fadeSlide.css('left', this.fadeSlide.width()+"px");
        this.fadeSlide.attr('src', this.imageList[nextIndex].src);
        this.fadeSlide.animate({
            left : 0
        }, 500, 'easeOutExpo');
        this.currentImageIndex = nextIndex;
    }


    Slideshow.prototype._isImageLoaded  = function (index) {
        return this.imageIsLoaded[index];
    }

})();
