// Shuffle
$('document').ready(function(){
    var
    speed = 800,
    width = 463,
    height = 332,
    timeout,
    scale = 0.88,
    offset = 218.5,
    margin = (height - height*scale)/2,
    stack,
    active,
    callback = function(){
        $(this).find('p').slideDown('slow');
    },
    timer,
    timeOut = 5500;
    
    function auto(){
        clearTimeout(timer);
        timer = setTimeout(shuffleNext, timeOut);
    }
    
    function setStack(){
        $stack = $('#shuffle').children().each(function(i){
            $(this).css({zIndex:-i});
        });
        
        $stack.first().css({left:offset}).nextAll().css({left:offset+275}).last().css({left:0});
        
        active = false;
        
        $('#shufflePrev').click(function(){
            if(!active){
                shufflePrev();
            }
            return false;
        });
        
        $('#shuffleNext').click(function(){
            if(!active){
                shuffleNext();
            }
            return false;
        });   
    }
    
    setStack();
    
    auto();
    
    $stack.not(':first').css({top:margin, width:width*scale, height:height*scale});
    $stack.first().find('p').show();
    
    function shuffleNext(){
        auto();
        
        active = true;
        $stack.first().animate({left:0, width:width*scale, height:height*scale, top:margin},speed).find('p').slideUp('fast');
        setTimeout(function(){
            $stack
            .first()
            .next()
            .css({zIndex:0})
            .animate({left:offset, width:width, height:height, top:0}, speed, function(){
                $stack.first().appendTo($('#shuffle'));
                setStack();
                callback.call(this);
            });
        }, speed * 0.7);
    }
    
    function shufflePrev(){
        auto();
        
        active = true;
        $stack.last().prev().css({left:0, zIndex:-99});
        
        $stack.first().animate({left:offset+275, width:width*scale, height:height*scale, top:margin},speed).find('p').slideUp('fast');
        
        setTimeout(function(){
            $stack
            .first()
            
            $stack
            .last()
            .css({zIndex:0})
            .animate({left:offset, width:width, height:height, top:0}, speed, function(){
                $stack.last().prependTo($('#shuffle'));
                setStack();
                callback.call(this);
            });
        }, speed * 0.7);
    }
});
