//Wait until ready to load then preload images and play slideshow
$(window).bind("load", function(){
	var imgArr = [];
	$('.img-link').each(function(){
		imgArr.push($(this).attr('href'));
	});

	imgArr.push("images/gallery/border.gif");
	
	$(document.createElement('img')).bind('load', function(){
		if(imgArr[0]) this.src = imgArr.shift();
	}).trigger('load');    
	
	playSlideshow = setInterval("rotateAuto()", 7000);
});
	
$(document).ready(function(){
	//When thumbs are clicked, stop slideshow and switch to clicked picture
	$(".image_thumb ul li").click(function () {
		clearInterval(playSlideshow);
		$active = $(this);
		rotate();
		return false;
	});
});

var counter = 0;	//Counter for max # of rotations
var maxRotate = 11;	//Max number of times to rotate.  One revolution is currently 6 images, so three cycles brings count to 18 

function rotateAuto(){
	$active = $('.image_thumb ul li.current').next();
	if ( $active.length == 0 ) $active = $('.image_thumb ul li:first'); //goes back to start when finishes
	rotate();
	
	counter++;

	//Set a maximum number of times to rotate
	if(counter > maxRotate){
		clearInterval(playSlideshow);
	}
}

function rotate() {
	var $prev = $('.image_thumb ul li.current');

	//Move the border to the next thumb nail
	$prev.removeClass('current');
	$('.thumb').remove();
	$active.addClass('current');
	$active.append('<img src="images/gallery/border.gif" class="thumb" />');

	var imgURL = $active.find('a').attr("href"); //Get main image location
	var imgDesc = $active.find('.block').html(); //Get caption HTML
	var imgLink = $active.find('.gallery-link').attr("href"); //Get link for full image 
	var imgHTML = '<a href="'+imgLink+'" class="gallery-link"><img src="'+imgURL+'" alt="" /></a>';	//Build the full image

	//Insert new caption
	$(".main_image .block").html(imgDesc);
	//Change the link for full image
	$(".main_image .gallery-link").attr({ href: imgLink});
	//Fade from the old image to the new one
	$(".main_image #slide").fadeTo(300, 0.1, function(){
		$(".main_image #slide").html(imgHTML).animate({opacity: 1.0}, 300);
	});

	return false;
}