


$(window).load(function(){
	
	
	// Randomize the order of slides - comment out to go in order
	var $slides = $($('#frontandcenter ul li').sort(randomResult));
	$('#frontandcenter ul').html($slides);
	
	$('#frontandcenter').append('<div id="slideshow-nav"></div>'); // make navigation thumbnails	
	
	$('#slideshow-nav').html('<img src="images/left-arrow.png" alt="<" class="previous"/>'); // add previous
	
	$('#frontandcenter ul li').each(function() {
		$('#slideshow-nav').append('<img src="images/square.png" class="thumb" alt="[]" />'); // add slide thumbnail
	});	
	
	$('#slideshow-nav').append('<img src="images/right-arrow.png" alt=">" class="next" />'); // add next
	$('#slideshow-nav').append('<img src="images/pause.png" alt="=" class="pause" />'); // add pause
	
	displaySlide('#frontandcenter ul li:first');
	
	// when slideshow navigaiton is clicked
	$('#slideshow-nav').click(function(ev){
		clicked = $(ev.target);
		
		if (clicked.hasClass('thumb')) {
			index = $('#slideshow-nav img.thumb').index(clicked);
			gotoSlide(index); 
		} else if (clicked.hasClass('next')) {
			nextSlide();
		} else if (clicked.hasClass('previous')) {
			previousSlide();
		} else if (clicked.hasClass('pause')) {
			clearTimeout(slideShowTimer);
		}
	});
	
});


var randomResult = function() { return( Math.random() > 0.5 ? 1 : 0  ); }  
  



var slideShowTimer = null;

nextSlide = function() {
	
	slide = $('#frontandcenter ul li:visible');	 // get the current one	
		
	next = slide.next('li'); 					// find the next slide
		
	if (next.length == 0) { 					// move to first if there is no slide
		next = slide.siblings().first(); 
	} 
		
	displaySlide(next);						// display it
};

gotoSlide = function(num) {
	if (!num) { num = 0; }
	
						
	next = $($('#frontandcenter ul li').eq(num));	// find the numbered slide
		
	if (next.length == 0) { 					// move to first if there is no slide
		next = slide.siblings().first(); 
	} 
		
	displaySlide(next, 20000);					// display it; with longer wait time
	
};

previousSlide = function() {
	slide = $('#frontandcenter ul li:visible');	 // get the current one
		
	next = slide.prev("li"); 				// find the previous slide
		
	if (next.length == 0) { 					// move to first if there is no slide
		next = slide.siblings().first(); 
	} 
		
	displaySlide(next);						// display it
};

displaySlide = function(slide, timeout){
	if (slideShowTimer) clearTimeout(slideShowTimer);
	
	if (!timeout) { timeout = 6000 }
	
	slide = $(slide);		
	slide.fadeIn();
	slide.siblings().fadeOut();
	
	index = $('#frontandcenter ul li').index(slide);
	$('#slideshow-nav img.thumb').attr('src', 'images/square.png').eq(index).attr('src', 'images/square.current.png');
	
		
	slideShowTimer = setTimeout(nextSlide,timeout);
};
