var filmstrip;
$(function() {
	function Filmstrip() {   
		var container = '#filmstrip';
		var blocks = [] ;
		var pos = 0;
		var animating = false;
		var self = this;
		var duration = 2000;
		this.autoplay = true;
		var pause = 3000;

		this.load = function () {
			$(container + ' p').each(function() {
				blocks[blocks.length] = '<p>' + $(this).html() + '</p>';
			});
			this.clear();
			for (var i = 0;i<2 ;i++ ) {
				$(blocks[i]).appendTo(container);
			}
			if (this.autoplay) {
				setTimeout(function() {
					filmstrip.right();
				}, pause);
			}
		}

		this.clear = function() {
			$(container).html('');
		}

		this.left = function() {
			if (animating) {
				return;
			}
			animating = true;
			pos --;
			if (pos < 0) {
				pos = blocks.length - 1;
			}
			//alert(pos + ' ' + scrollTo + ' ' + blocks.length);
			$(blocks[pos]).prependTo(container);
			$(container + ' p:first').css('margin-left', -264);

			$(container + ' p:first').animate({
					marginLeft: '+=264'
				}, 
				duration, 
				function() {
					$(container + ' p:last').remove();
					animating = false;
				}
			);
		}

		function run() {
			self.right();
		}

		this.right = function() {
			if (animating) {
				return;
			}
			animating = true;
			pos++;
			var scrollTo = pos + 1;
			if (scrollTo == blocks.length) {
				scrollTo = 0;
			}
			else if (scrollTo > blocks.length) {
				scrollTo = 1;
			}
			$(blocks[scrollTo]).appendTo(container);
			$(container + ' p:first').animate({
					marginLeft: '-=264'
				}, 
				duration, 
				function() {
					$(container + ' p:first').remove();
					animating = false;
					//setTimeout('run()', 3000);
				}
			);
			if (this.autoplay) {
				setTimeout(function() {
					filmstrip.right();
				}, pause + duration);
			}
			
			if (pos >= blocks.length) {
				pos = 0;
			}
		}
	}

	filmstrip = new Filmstrip;
	filmstrip.load();
	$('#filmstrip-left').click(function() { 
		filmstrip.autoplay = false;
		filmstrip.left();
	});
	$('#filmstrip-right').click(function() { 
		filmstrip.autoplay = false;
		filmstrip.right();
	});
});
