$(document).ready(function() {
    var images = [];
    var currentIndex = 0;
    var timer = 5000;

    $('#slideshow').css('position', 'relative');
    //hide all but first image
    $('#slideshow li').each(function(i, val){
        images.push(this);

        $(this).css('position', 'absolute');
        if (i != 0){
            $(this).hide();
        } else {
            $(this).css('z-index', 2);
        }
    });

    function changeImage(){
       
        var nextIndex = currentIndex + 1;

        //wrap
        if (nextIndex > images.length - 1) {
            nextIndex = 0;
        }

        $(images[nextIndex]).show();
        $(images[currentIndex]).fadeOut(2000, function(){
            $(images[nextIndex]).css('z-index', 2);
            $(images[currentIndex]).css('z-index', 1);
            $(images[currentIndex]).hide();
            currentIndex = nextIndex;
        });

        setTimeout(function(){
            changeImage();
        }, timer);
    }

    setTimeout(function(){
        changeImage();
    }, timer);
});
