var fadeid;
var current = 1;
var last = 5;
var timetofade = 8000;
var fadetransition = 3000;

$(document).ready(function(){
    $('#b1').show(); 	
    $('#b2').hide(); $('#b2').fadeTo(0,0); 
    $('#b3').hide(); $('#b3').fadeTo(0,0); 
    $('#b4').hide(); $('#b4').fadeTo(0,0); 
    $('#b5').hide(); $('#b5').fadeTo(0,0); 
        
    fadeid = setInterval("loopfade()", timetofade);
    
    $('.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('active');
            $('#f'+clicked).addClass('active');
            
            // fade out old
            $('#b'+old).animate({ opacity: .3 }, 10, function() {
                
               $('#b'+clicked).animate({ opacity: .5 }, 10, function() {
                    $('#b'+old).animate({ opacity: 0 }, 10, function() {
                        $('#b'+old).hide();
                        $('#b'+clicked).animate({ opacity: 1 }, 10, function() {
                            clearInterval(fadeid);
                            fadeid = setInterval("loopfade()", timetofade);
							$('#b'+clicked).fadeIn(250);
                        });
                    });
                });
            });
        }
    });
});


function loopfade() {
    if (current == 5) {
        current = 1;
        last = 5;
    } else {
        last = current;
        current++;
    }
    $('#f'+last).removeClass('active');
    $('#f'+current).addClass('active');
   
    $('#b'+last).animate({ opacity: 0 }, fadetransition, function() {
        $('#b'+last).hide();
    });    
    $('#b'+current).show();
    $('#b'+current).animate({ opacity: 1 }, fadetransition);
}


