/**
 * These two functions disable animations when the tab is inactive.
 * In theory, this will fix things...
 */
$(window).focus(function() {
    $.fx.off = false;
});
$(window).blur(function() {
    $.fx.off = true;
});

var slideInterval;

/**
 * Animate a colour image appearing over the b&w one
 */
function slideColourIn($slide, delay) {
	// Main colour slide
	var interval = setInterval(function(){
		$slide.children('.slide-colour').css({width:0, display:'block'})
			 .animate({width:'100%'}, 6000, 'linear');
		clearInterval(interval);
	}, delay);
	
	// Tell the opacity slides to move, one after the other
	var intervals = new Array();
	var opacity = 0.8;
	var opacities = new Array();
	$slide.children('.slide-colour-opacity').each(function(i, element){
		delay -= 70;
		opacities[i] = opacity;
		intervals[i] = setInterval(function(){
			$(element).css({width:0, display:'block', 'opacity':opacities[i]})
				 .animate({width:'100%'}, 6000, 'linear');
			clearInterval(intervals[i]);
		}, delay);
		opacity -= 0.15;
	});
}

/**
 * Show next slide
 */
function showNextSlide($container) {
	// Get current and next slide
	var $current = $container.children('.active');
	var $next = $current.next('.slide');
	if ($next.length == 0) {
		clearInterval(slideInterval);
		//$('#container').fadeOut(0,function(){
			$('#banner').fadeIn(200,function(){
				$('.navigation').delay(500).fadeIn(800,function(){
					$('.breadcrumbs').delay(500).fadeIn(800,function(){
						$('.description').delay(500).fadeIn(800,function(){
							$('#footer').delay(500).fadeIn(800,function(){
								$('#skip').fadeOut(500);
								$('body').load("home.htm #wrapper");
							});
						});
					});
				});
			});
		//});
		return; // Stop before fading out
		//$next = $container.children('.slide:first-child');
	}
	
	$next.children().css('width', 0);
	
	// Hide current
	$current.fadeOut(800).removeClass('active');
	// Show next
	$next.fadeIn(800, function(){
		$next.addClass('active');
		slideColourIn( $next, 1000 );
	});
}

$(function() {
	var $slider = $('#container');
	
	// Preload images
	$slider.children('.slide').css({top:'-9999px', display: 'block'})
					  .css({top:'auto', display:'none'});
	
	// Create opacity divs
	$slider.children('.slide').each(function(index,slide){
		for (var i=0; i<5; i++) {
			$(slide).append('<div class="slide-colour-opacity"></div>');
		}
	});
	
	// Run the slider
	showNextSlide($slider);
	slideInterval = setInterval(function(){
		showNextSlide($slider);
	}, 12000);
});

	 
	 
