var maxHeight = 0;
var totalWidth = 0;
var position = [];
var pos = 0;
var currentImage = 0;
var busy = false;
	
$(function() {
	$('.post').each(function(i) {
		var width = $(this).find('img').attr('width') + 20;
		$(this).width(width);
		maxHeight = Math.max(maxHeight, $(this).height());
		totalWidth = totalWidth + $(this).width();
	}).css({
		'float': 'left',
		'cursor': 'pointer'
	});
	
	$('.posts').css({
		'position': 'absolute',
		'top': 150,
		'left': 0,
		'overflow': 'hidden',
		'height': maxHeight,
		'width': totalWidth	+ 500
	});
	
	$('.post').each(function(i) {
		pos = $(this).position();
		position[position.length] = pos.left;
	}).click(function(e) {
		move($('.post img').index(e.target));
		currentImage = $('.post img').index(e.target);
	});
	
	$('#prev').click(function(e) {
		if(currentImage > 0 && !busy) {
			move(currentImage-1);
			currentImage--;
		}
		return false;
	});
	
	$('#next').click(function(e) {
		if(currentImage < $('.post').length-1 && !busy) {
			move(currentImage+1);
			currentImage++;
		}
		return false;
	});
	
	$(window).resize(function() {
		positionArrows();
	}).keydown(function(e) {
		if(e.keyCode === 37) {
			e.preventDefault();
			$('#prev').click();
		}
		else if(e.keyCode === 39) {
			e.preventDefault();
			$('#next').click();
		}
	});
	
	positionArrows();
	
});

function move(targetIndex) {
	busy = true;
	$('.posts').animate({
		'left': -position[targetIndex]
	}, 'slow', function() {
		busy = false;
	});
}

function positionArrows() {
	if($(window).height() > 749) {
		$('#prev, #next').css({
			'top': '699px',
			'bottom': 'auto'	
		});
	} 
	else {
		$('#prev, #next').removeAttr('style');
	}		
}



