/*
 * Fades images in and out from the list of images given
 * Written by Jack Franklin
 */

(function($) {
        
    $.extend({

        fadeImages: function(elem) {
            var parent = $(elem),
                images = parent.children(),
                imageCount = images.length,
                currentImage = 0;
            
            images.each(function(i, item) {
                $(item).css("z-index", 10-i);
            });
            images.eq(0).clone().css("z-index", 1).appendTo(parent);

            function fadeImageOut() {
                images.eq(currentImage).fadeOut(1000, function() {
                    currentImage+= 1;
                    if(currentImage === imageCount) {
                        resetFader();
                    } else {
                        setTimeout(function() {
                            fadeImageOut();
                        }, 2000);
                    }
                });

            }

            function resetFader() {
                images.css("display", "inline");
                currentImage = 0;
                setTimeout(function() {
                    fadeImageOut();
                }, 2000);
            } 

            setTimeout(function() {
                fadeImageOut();
            }, 2000);
        }
    });
})(jQuery);


