$(document).ready(function() {
	var currentSlide = 3;
	$('#slideshow .menu li:eq(' + currentSlide + ')').addClass('active');
	$('#slideshow .slides div:eq(' + currentSlide + ')').addClass('active').show();

	// On a thumbnail click.
	$('#slideshow .menu ul li a').click(function(e, autoAdvance) {
		
		// Prevent default action.
		e.preventDefault();
		
		// Do nothing if it's already active.
		if ($(this).parent().hasClass('active')) {
			return;
		}
		
		// Fade out current slide.
		$('#slideshow .menu ul li.active').removeClass('active');
		$('#slideshow .slides div.active').removeClass('active').fadeOut();
		
		// Fade in slide of clicked thumbnail.
		if ((autoAdvance) && ($('#slideshow .slides div').eq(currentSlide).has('object').length)) {
			++currentSlide;
		}
		$(this).parent().addClass('active');
		currentSlide = $(this).parent().prevAll().length;
		$('#slideshow .slides div:eq(' + currentSlide + ')').addClass('active').fadeIn();
		
		// Handle auto advance interval.
		if ($('#slideshow .slides div:eq(' + currentSlide + ')').has('object').length) {
			clearInterval(interval);
		} else if (!autoAdvance) {
			clearInterval(interval);
			interval = setInterval(function() {advance()}, 8000);
		}
		
	});
	
	// Advance by one slide.
	function advance() {
		
		// Don't advance to videos.
		do {
			++currentSlide;
			if (currentSlide >= $('#slideshow .menu ul li a').length) {
				currentSlide -= $('#slideshow .menu ul li a').length;
			}
		} while ($('#slideshow .slides div:eq(' + currentSlide + ')').has('object').length)
		
		// Simulate click on the next thumbnail.
		$('#slideshow .menu ul li a:eq(' + currentSlide + ')').trigger('click', [true]);	
		
	}

	// The number of ms that the slider will auto-advance in.
	var interval = setInterval(function() {advance()}, 8000);
	
});
