var fadeid;
var current = 1;
var last = 4;

function loopfade() {
    if (current == 4) {
        current = 1;
        last = 4;
    } else {
        last = current;
        current++;
    }
    
    $('#f'+last).removeClass('f-active');
    $('#f'+current).addClass('f-active');
    
    $('#b'+last).animate({ opacity: 0 }, 1000, function() {
        $('#b'+last).hide();
    });
    
    $('#b'+current).show();
    $('#b'+current).animate({ opacity: 1 }, 1000);
}

$(document).ready(function() {
    $.get( "products/session.php", function (data) {
        $("#items-in-cart").html(data);
    });
    
    $('#b2').hide(); $('#b2').fadeTo(0,0);
    $('#b3').hide(); $('#b3').fadeTo(0,0);
    $('#b4').hide(); $('#b4').fadeTo(0,0);
    fadeid = setInterval("loopfade()", 8000);
    
    $('.f').click(function() {
        var clicked = $(this).attr('id').substr(1,1);
        var old = current;
        current = clicked;
        
        if (old != clicked) {
            // stop animations
            clearInterval(fadeid);
            
            $('#f'+old).removeClass('f-active');
            $('#f'+clicked).addClass('f-active');
            
            // fade out old
            $('#b'+old).animate({ opacity: .3 }, 325, function() {
                
                $('#b'+clicked).show();
                $('#b'+clicked).animate({ opacity: .5 }, 325, function() {
                    $('#b'+old).animate({ opacity: 0 }, 1, function() {
                        $('#b'+old).hide();
                        $('#b'+clicked).animate({ opacity: 1 }, 1, function() {
                            clearInterval(fadeid);
                            fadeid = setInterval("loopfade()", 8000);
                        });
                    });
                });
            });
        }
    });
});
