(function($) {

	$(document).ready(function() {

		var Slideshow = new function() {

	var timer = null,
	    index = 0,
	    wrapper = $('#slideshow-wrapper', '#slideshow'),
	    slides = $('div.slide', wrapper),
	    thumbs = $('a', '#slideshow-nav');

	var getSlidePositions = function() {

		var positions = [];
		slides.each(function(i) {

			var left = $(this).position().left;

			positions[i] = left;

		});

		return positions;

	};

	var addOffsetsToImages = function() {

		slides.each(function() {

			$(this).attr('position', $(this).position().left);

		});

	};

	var autoSlide = function() {

		var offsets = getSlidePositions();
		timer = setInterval(function() {

		    index++;

		    if(index == offsets.length) {

		    	index = 0;

		    }

			wrapper.animate({
				left: - offsets[index]
			}, 1000, function() {

				thumbs.eq(index).animate({
					opacity: 0.5
				}, 1000, function() {

					$(this).animate({
						opacity: 1
					}, 1000);

				});	

			});

		}, 4000);

	};

	var handleThumbLinks = function() {

		thumbs.each(function() {

			var $a = $(this);
			var imgId = $($a.attr('href'));
			var $offset = imgId.attr('position');

			$a.click(function(event) {

				clearInterval(timer);

				wrapper.animate({
					left: - $offset
				}, 1000, function() {

					autoSlide();

				});

				event.preventDefault();

			});

		});

	};

	this.init = function() {

		addOffsetsToImages();

		autoSlide();

		handleThumbLinks();	

	};
}();

  Slideshow.init(); 

	});

})(jQuery);
