jQuery.fn.extend({
    imageSwap : function () {
        var images = $('img',this),
        zIndex = 4,
        duration = 1000,
        delay = 10000,
        cTime = new Date().getTime(),
        startDelay = cTime % delay,
        index = Math.floor((cTime) / delay) % images.length;;

        if (images.length == 0) {
            return $(this);
        }

        $(images)
            .each(function (i) {
                
                $(this).css({
                    zIndex : i==index ? zIndex : images.length - (i - index + images.length) % images.length
                });
                
            })
            .addClass('swap')
            .show();

        function swap(d) {
            var image = $(images[index]);

            image.delay(d).fadeOut(duration, function () {
                images.each(function () {
                    $(this).css('zIndex',parseInt($(this).css('zIndex'))+1);
                });
                $(this)
                    .css('zIndex',zIndex - images.length + 1)
                    .show();

                index++;
                if (index == images.length) {
                    index = 0;
                }

                
                swap(delay - duration);
            });
        }


        swap(delay - startDelay - duration);

        

    }
});

$(document).ready(function() {
    $('.tx-imageswap-pi1').imageSwap();
});
