$(function() {
	/* This code is executed after the DOM has been completely loaded */

	var totWidth = 0,
	positions = [],
	current = 1,
	changeEvery = 10,
	itvl = null;

	$('#slides li a img').each(function(i){

		/* Traverse through all the slides and store their accumulative widths in totWidth */
		var thisWidth = $(this).attr('width');

		positions[i] = totWidth;
		totWidth+= parseFloat(thisWidth);

	});

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

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

		// On a thumbnail click

		$('li.menuItem').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

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

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

		current = (pos + 1);
		if(current === (positions.length)){
			current = 0;
		}

		e.preventDefault();
		// Prevent the default action of the link


		// Stopping the auto-advance if an icon has been clicked:
		if(!keepScroll && itvl){
			clearInterval(itvl);

			itvl = setInterval(function(){
				autoAdvance()
			}, (changeEvery * 1000));
		}

	});

	$('ul#thumbs li.menuItem:first').addClass('act').siblings().addClass('inact');
	// On page load, mark the first thumbnail as active

	/*****
	 *
	 *	Enabling auto-advance.
	 *
	 ****/

	function autoAdvance(){

		if(current === -1){
			return false;
		}

		$('ul#thumbs li a').eq(current).trigger('click',[true]);

		// [true] will be passed as the keepScroll parameter of the click function on line 28
	}

	itvl = setInterval(function(){
		autoAdvance()
	}, (changeEvery * 1000));

});
