// Script originally from http://demo.tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/demo.html and http://www.devseo.co.uk/examples/jquery-slider-example

$(function() {
	/* This code is executed after the DOM has been completely loaded */
	var totWidth = 0,
	positions = [],
	current = 1,
	runOnce = 0,
	changeEvery = 6.5,
	slideSpeed = .45,
	pos,
	timeOut = null;

	$('#slides .slide').each(function(i){

		/* Traverse through all the slides and store their accumulative widths in totWidth */
		var thisWidth = $(this).width();
		
		positions[i] = totWidth;
		totWidth += parseFloat(thisWidth);
	});

	// Change the cotnainer div's width to the exact width of all the slides combined
	$('#slides').width(totWidth);

	// Loop through thumbs and add click event
	$('#menu ul li a').click(function(e,simulated){

		// On a thumbnail click
		$('li.menuItem').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

		pos = $(this).parent().prevAll('.menuItem').length;		
		
		$('#slides').stop().animate({"marginLeft": -positions[pos]+'px'},(slideSpeed*1000));

		// Start the sliding animation
		current = (pos + 1);
		if(current === (positions.length)){
			current = 0;
		}
		
		e.preventDefault();
		
		if(!simulated){
			clearTimeout(timeOut);
		}

	});
	// On page load, mark the first thumbnail as active
	$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');

	// A self executing named function expression:
	(function autoAdvance(){
		if(runOnce != 0){
			$('#menu ul li a').eq(current).trigger('click',[true]);
		}
		else{
			runOnce = 1;
		}
		// Schedulling a time out in 5 seconds.
		timeOut = setTimeout(autoAdvance,(changeEvery*1000));
	})();

});
