$(document).ready(function() {
    var z = 0;
    var inAnimation = false;

    $('#pictures img').each(function() { //set the initial z-index's
        z++; //at the end we have the highest z-index value stored in the z variable
        $(this).css('z-index', z); //apply increased z-index to <img>
    });

    function swapFirstLast(isFirst) {
        if (inAnimation) return false;
        else inAnimation = true;

        var processZindex, direction, newZindex, inDeCrease;

        if (isFirst) { processZindex = z; direction = '-'; newZindex = 1; inDeCrease = 1; } //set variables for "next" action
        else { processZindex = 1; direction = ''; newZindex = z; inDeCrease = -1; } //set variables for "previous" action

        $('#pictures img').each(function() {
            if ($(this).css('z-index') == processZindex) {
                $(this).animate({ 'top': direction + $(this).height() + 'px' }, 'slow', function() {
                    $(this).css('z-index', newZindex)
            .animate({ 'top': '0' }, 'slow', function() {
                inAnimation = false;
            });
                });
            } else { //not the image we need to process, only in/de-crease z-index
                $(this).animate({ 'top': '0' }, 'slow', function() { //make sure to wait swapping the z-index when image is above/under the gallery
                    $(this).css('z-index', parseInt($(this).css('z-index')) + inDeCrease); //in/de-crease the z-index by one
                });
            }
        });

        return false; //don't follow the clicked link
    }

    $('#next a').click(function() {
        return swapFirstLast(true); //swap first image to last position
    });

    $('#prev a').click(function() {
        return swapFirstLast(false); //swap last image to first position
    });
});