(function($, undefined){
	var FILMSTRIP = {
		init: function() {
			this.$filmstripWrapper = $('div.filmstrip');
			
			if (this.$filmstripWrapper.length === 0) return;
			
			// Elements
			this.$filmstrip = this.$filmstripWrapper.children();
			
			// Collections
			this.$images = this.$filmstrip.find('div.image');
			
			this.startSlideshow();
			this.handleEvents();
		},
		startSlideshow: function() {
			var repetitions = this.$images.length < 20 ? 10 : 3,
				randomIndex = Math.ceil(Math.random()*this.$images.length) - 1 + (this.$images.length * repetitions);
			
			// Add images either side of main set -- bit of a hack, but keeps things simple
			for (var i = 0; i < repetitions; i++) {
				this.$filmstrip.prepend(this.$images.clone());
			}
			for (var i = 0; i < repetitions; i++) {
				this.$filmstrip.append(this.$images.clone());
			}
			
			this.activateImage(randomIndex, true);			
			this.slideshow = setInterval($.proxy(this.next, this), 3500);
		},
		next: function() {
			var $next = this.$activeImage.next();
			
			if ($next.length === 0) {
				$next = this.$filmstrip.children().eq(0);
			}
			
			this.activateImage($next.index());
		},
		prev: function() {
			var $prev = this.$activeImage.prev();
			
			if ($prev.length === 0) {
				$prev = this.$filmstrip.children().last();
			}
			
			this.activateImage($prev.index());
		},
		activateImage: function(index, skipAnimation) {
			var $newImage = this.$filmstrip.find('div.image').eq(index);
			
			if (this.$activeImage !== undefined) {
				this.$activeImage.removeClass('image-large').addClass('image-small').find('img.hover').stop(true,true).fadeOut();
			}
			
			this.$activeImage = $newImage.addClass('image-large').removeClass('image-small');
			
			this.$filmstrip.stop().animate({
				left: ($newImage.position().left * -1) + ($(window).width() / 2) - ($newImage.outerWidth() / 2)
			}, (skipAnimation === true ? 0 : 750), 'easeInOutExpo');
		},
		handleEvents: function() {
			var self = this;
			
			this.$filmstrip
				.delegate('div.image-small', 'mouseenter', function(){
					var $this = $(this);
					$this.find('img.hover').stop(true,true).fadeIn();
				}).delegate('div.image-small', 'mouseleave', function(){
					var $this = $(this);
					$this.find('img.hover').stop(true,true).fadeOut();
				}).delegate('div.image-small', 'click', function(){
					var $this = $(this);
					clearInterval(self.slideshow);
					self.activateImage($this.index());
				}).delegate('div.image-large', 'click', function(){
					var $this = $(this);
					window.location.href = $this.data('href');
				});
			
			$(document).keydown(function(e) {
				var key = e.which;
				
				if (key === 37) {
					self.prev();
					clearInterval(self.slideshow);
				} else if (key === 39) {
					self.next();
					clearInterval(self.slideshow);
				}
			})
		}
	};
	
	$(function() {
		FILMSTRIP.init();
	});
})(jQuery);
