// I hacked this together from a tutorial from
// http://www.nitinh.com/2010/03/how-to-create-a-simple-slideshow-using-mootools-jquery/
// so all of the credit goes to him, OK?

var currentImage;
var currentIndex = -1;
var interval;
function showImage(index){
	//if(index < $('#main-image img').length){
		var indexImage = $('#main-image img')[index]
		if(currentImage){   
			if(currentImage != indexImage ){
				$(currentImage).css('z-index',2);
				clearTimeout(myTimer);
				$(currentImage).fadeOut(250, function() {
					myTimer = setTimeout("showNext()", 6000);
					$(this).css({'display':'none','z-index':1})
				});
			}
		}
		$(indexImage).css({'display':'block', 'opacity':1});
		currentImage = indexImage;
		currentIndex = index;
		$('#thumbs li').removeClass('active');
		$($('#thumbs li')[index]).addClass('active');
	//}
}

function showPrev(){
	var len = $('#main-image img').length;
	var prev = currentIndex < (1) ? len-1 : currentIndex - 1;
	clearTimeout(myTimer);
	showImage(prev);
}

function showNext(){
	var len = $('#main-image img').length;
	var next = currentIndex < (len-1) ? currentIndex + 1 : 0;
	clearTimeout(myTimer);
	showImage(next);
}

var myTimer;

jQuery(document).ready(function($) {
	
   	showNext(); //loads first image
    myTimer = setTimeout("showNext()", 6000);
	
	$('#thumbs li').bind('click',function(e){
		var count = $(this).attr('rel');
		showImage(parseInt(count)-1);
	});
	$("#prev-btn").click(function(){
		showPrev();
		return false;
	});
	$("#next-btn").click(function(){
		showNext();
		return false;
	});
   
});
