function getItemCount() {
	var count = 0;
	
	$('#bImages li').each(function() {			
		if($(this).parent().attr('id') == 'bImages') count++;			
	})
	
	return count;
}
	
function infoCycle() {
	var nextClass = '';
	var switched = false;
	var currentClass = $('#bImages li.on ul li.on').removeClass('on').attr('class');
			
	switch(currentClass) {
		case 'what' : nextClass = 'when'; break;
		case 'when' : nextClass = 'where'; break;
		//case 'where' : nextClass = 'who'; break;
		//case 'who' : nextClass = 'how'; break;
		// case 'how' : nextClass = 'what'; break;
		case 'where' : switched = true; nextClass = 'what'; break;
	}
	
	$('#bImages li.on ul li.'+currentClass).fadeOut('fast', function() {
		$('#bImages li.on ul li.'+nextClass).fadeIn('medium').addClass('on');
	});
	
	if(switched) {
		eventChange(1);
		infoInterval = setInterval(infoCycle, 5000);		
		switched = false;
	}
}

function eventChange(difference) {		
	var totalItems = getItemCount();
	
	var bubbleNavClass = $('#bubble-nav').attr('class');
	var currentItem = bubbleNavClass.substr(1);
	var nextItem = parseInt(currentItem) + difference;
	
	if(nextItem > totalItems) nextItem = 1;
	if(nextItem < 1) nextItem = totalItems;
	
	$('#i'+currentItem+' li.on').removeClass('on');
	$('#i'+currentItem+' img').stop().animate({ opacity: 0 }).parent().removeClass('on');
	$('#i'+currentItem+' ul').stop().animate({ opacity: 0 }).removeClass('on');
	$('#i'+nextItem+' img').stop().animate({ opacity: 1.0 }).parent().addClass('on');
	$('#i'+nextItem+' ul').stop().animate({ opacity: 1.0 }).addClass('on');
	$('#i'+nextItem+' li.what').addClass('on').fadeIn('fast');
	
	$('#bubble-nav').removeClass(bubbleNavClass).addClass('a'+nextItem);
	clearInterval(infoInterval);
}

function cycleUp() {
	eventChange(1);
	infoInterval = setInterval(cycleUp, 5000);		
}


$(document).ready(function() {
	$('#bImages li img').each(function() {
		if(!$(this).parent().hasClass('on')) $(this).css({ opacity: 0 });
	});
	
	$('#bImages li ul').each(function() {
		if(!$(this).hasClass('on')) $(this).css({ opacity: 0 });	
	});	
	
	$('#bImages li ul li').each(function() {
		if(!$(this).hasClass('on')) $(this).hide();
	})
		
	$('#b-prev, #b-next').click(function() {
		var difference = 0;
				
		switch($(this).attr('id')) {
			case 'b-prev' : difference = -1; break;
			case 'b-next' : difference = 1; break;
		}
		
		eventChange(difference);
		infoInterval = setInterval(infoCycle, 5000);		
	});
});