var img_interval;
var img_interval_time = 5000;
var fade_timeout;
var fade_time = 500;

$(document).ready(function() {
	// Setup a timer for the slideshow
	img_interval = setInterval(nextImage, img_interval_time);
	
	//Set the first image/control to active
	$('#slideshow .controls .button:first-child').addClass('active');
	$('#slideshow .frame').children(':first-child').addClass('active');
	
	// Hide the non active images
	$('#slideshow .frame > div:not(.active)').hide();
	
	// Change the slideshow image when someone clicks the button at the bottom
	$('#slideshow .controls .button:not(.active)').live('click', function(e){
		e.preventDefault(); // Disable the click action
	
		clearInterval(img_interval);
		clearTimeout(fade_timeout);
		old_index = $(this).siblings('.active').index();
		index = $(this).index();

		// Change which button is on
		$(this).siblings('.active').removeClass('active');
		$(this).addClass('active');

		//* Fade between the images
		$('#slideshow .frame').children().eq(old_index).siblings().hide();
		$('#slideshow .frame').children().removeClass('active');
		$('#slideshow .frame').children().eq(old_index).show();
		$('#slideshow .frame').children().eq(index).addClass('active');
		if($.support.opacity){
			$('#slideshow .frame').children().eq(index).fadeIn(fade_time);
			$('#slideshow .frame').children().eq(old_index).fadeOut(fade_time);
		}else{
			$('#slideshow .frame').children().eq(index).show();	
			$('#slideshow .frame').children().eq(old_index).hide();	
		}
		//*/
	})

	// Make the active button do nothing
	$('#slideshow .controls .button.active').live('click', function(e){e.preventDefault()});
	
	// Change to the next image in the slideshow when the timer fires
	function nextImage()
	{
		index = $('#slideshow .frame').children('.active').index();
		count = $('#slideshow .frame').children().size();

		if(index + 1 == count){
			next_index = 0;
		}else{
			next_index = index + 1;
		}

		// Change which button is active
		$('#slideshow .controls .button.active').removeClass('active');
		$('#slideshow .controls .button:eq('+next_index+')').addClass('active');

		// Fade between the images
		$('#slideshow .frame').children().eq(index).siblings().hide();
		$('#slideshow .frame').children().removeClass('active');
		$('#slideshow .frame').children().eq(index).show();
		$('#slideshow .frame').children().eq(next_index).addClass('active');
		if($.support.opacity){
			$('#slideshow .frame').children().eq(next_index).fadeIn(fade_time)
			$('#slideshow .frame').children().eq(index).fadeOut(fade_time);
		}else{
			$('#slideshow .frame').children().eq(next_index).show();
			$('#slideshow .frame').children().eq(index).hide();
		}
	}
});
