// Slideshow animation on the home page

// Adapted from http://tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/ 
// and the modifications from http://www.devseo.co.uk/examples/jquery-slider-example/

$(document).ready(function(){

	var totWidth=0;
	var positions = new Array();
	var current = 1;
    var changeEvery = 5;
	var itvl = null;

	// Loop through all the slides and store their accumulative widths in totWidth
	$('#slides .slide').each(function(i){
		positions[i]= totWidth; 
		totWidth += 960;
		// The positions array contains each slide's commulutative offset from the left part of the container
	});

	// Change the container div's width to the exact width of all the slides combined 
	$('#slides').css('width', totWidth+'px');

	// Loop through the slide nav and add click event
	$('#slidesnav ul li a').click(function(e, keepScroll){

		// On a thumbnail click
		$('li.item').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

		var pos = $(this).parent().prevAll('.item').length;

		// Start the sliding animation
		$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},450);

		current = (pos + 1);
		if (current === (positions.length)) {
			current = 0;
		}
		
		// Prevent the default action of the link
		e.preventDefault();

		// Stopping the auto-advance if an icon has been clicked:
        if(!keepScroll && itvl) {
			clearInterval(itvl);
			itvl = setInterval(function() { autoAdvance() }, (changeEvery*1000));
		}
	});

	// On page load, mark the first thumbnail as active 
	$('#slidesnav ul li.item:first').addClass('act').siblings().addClass('inact');
	
	// Enable automated slideshow
	
    function autoAdvance() {
        if (current == -1) {
			return false;
		}
        
		// [true] will be passed as the keepScroll parameter of the click function on line 39        
		$('#slidesnav ul li a').eq(current).trigger('click',[true]);   
    }

    // The number of seconds that the slider will auto-advance in:
	itvl = setInterval(function() { autoAdvance() }, (changeEvery*1000));
});
