(function( $ ){
    cpdSlideshow = function(imgList, imgContainer, fadeLength, fadeDelay){
        this.imgContainer = imgContainer;
        this.imgList = imgList;
        this.fadeLength = fadeLength;
        this.fadeDelay = fadeDelay;
        
        var currentImg = 0;
        var nextImg = 1;

        this.loadImages = function loadImages(){
            var imgPreloader = new Image();

            for(var i=0; i < this.imgList.length; i++){
                imgPreloader.src = this.imgList[i];
            }
        }
        this.play = function play(){
            $(this.imgContainer).append('<img id="slideImg1" src="'+this.imgList[currentImg]+'" />').
            append('<img id="slideImg2" src="'+this.imgList[nextImg]+'" />');
			$('#slideImg1').css({
				'position': 'absolute',
				'z-index': '5'
			});
			$('#slideImg2').css({
				'position': 'absolute',
				'z-index': '0'
			});
            doFade(this.fadeLength, this.fadeDelay);
        }

        function doFade(fLength, fDuration){
            $('#slideImg1').animate({opacity:0}, fLength, function(){
                addCurrent();
                addNext();
                onFade(fLength, fDuration);
            });
        }
        function onFade(fLength, fDuration){
            setTimeout(function(){
               onSlide(fLength, fDuration);
            }, fDuration);
            
        }

        function onSlide(fLength, fDuration){
            $('#slideImg1').attr('src', imgList[currentImg]);
            $('#slideImg2').attr('src', imgList[nextImg]);
            $('#slideImg1').animate({opacity:1}, 0);
            doFade(fLength, fDuration);
        }
        function addCurrent(){
            if(currentImg < (imgList.length - 1)){
               currentImg++;
            } else {
                currentImg = 0;
            }
        }

        function addNext(){
            if(nextImg < (imgList.length - 1)){
                nextImg++;
            } else {
                nextImg = 0;
            }
        }

    }
})( jQuery );
