$(document).ready(function() {		
	
	//Execute the medbox, set 4 seconds for each images
	medbox(8000);

});

function medbox(speed) {


	//append a LI item to the UL list for displaying caption
	$('ul.medbox').append('<li id="medbox-caption" class="caption"><div class="medbox-caption-container"><h3></h3><p></p></div></li>');

	//Set the opacity of all images to 0
	$('ul.medbox li').css({opacity: 0.0});
	
	//Get the first image and display it (set it to full opacity)
	$('ul.medbox li:first').css({opacity: 1.0});
	
	//Get the caption of the first image from REL attribute and display it
	$('#medbox-caption h3').html($('ul.medbox a:first').find('img').attr('title'));
	$('#medbox-caption p').html($('ul.medbox a:first').find('img').attr('alt'));
		
	//Display the caption
	$('#medbox-caption').css({opacity: 0.7, bottom:0});
	
	//Call the gallery function to run the medbox	
	var timer = setInterval('medgallery()',speed);
	
	//pause the medbox on mouse over
/*	$('ul.medbox').hover(
		function () {
			clearInterval(timer);	
		}, 	
		function () {
			timer = setInterval('medgallery()',speed);			
		}
	);*/
	
}

function medgallery() {


	//if no IMGs have the medshow class, grab the first image
	var current = ($('ul.medbox li.medshow')?  $('ul.medbox li.medshow') : $('#ul.medbox li:first'));

	//Get next image, if it reached the end of the medbox, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().attr('id') == 'medbox-caption')? $('ul.medbox li:first') :current.next()) : $('ul.medbox li:first'));
		
	//Get next image caption
	var title = next.find('img').attr('title');	
	var desc = next.find('img').attr('alt');	

	//Set the fade in effect for the next image, medshow class has higher z-index
	next.css({opacity: 0.0}).addClass('medshow').animate({opacity: 1.0}, 2000);
	
	//Hide the caption first, and then set and display the caption
	$('#medbox-caption').slideToggle(300, function () { 
		$('#medbox-caption h3').html(title); 
		$('#medbox-caption p').html(desc); 
		$('#medbox-caption').slideToggle(1000); 
	});		

	//Hide the current image
	current.animate({opacity: 0.0}, 2000).removeClass('medshow');

}
