var speed = 50;
var spacing = 15;
var pic, arrLeft, i, totalWidth, n, interval, prevLocation, currentSelection; 

$(window).load(function(){
	
	images = $('.scrolling').children('div');
	arrLeft = new Array(images.length);
	
	$.each(images, function(index, value){
		totalWidth = 0;
		for (n=0;n<index;n++) totalWidth += $(images[n]).width()+spacing;
		arrLeft[index] = totalWidth;
	});

	interval = setInterval("scroll()", speed);

	$('.scrolling').hover(
		function(){
			clearInterval(interval);
		}, function(){
			if ($('.scrolling').css('width') == '890px') interval = setInterval("scroll()", speed);
		}
	);
	
	$('.scrolling img').hover(
		function(){
			document.body.style.cursor = 'pointer';
		}, function(){
			document.body.style.cursor = 'auto';
		}
	);
	
	$('.scrolling img').click(function(){
		clearInterval(interval);
		$.each($(this).parent().siblings(), function(index, value){ $(value).fadeOut(); });
		prevLocation = $(this).parent().css('left');
		currentSelection = $(this);
		$(this).animate({width: '200px'}, 'slow');
		$(this).parent().animate({top: '22px', left: '18px', width: '204px'}, 'slow');
		$(this).next().fadeOut();
		$('#'+this.id+'-info').show();
		$('.scrolling').animate({width: '242px', height: '230px'}, 'slow', null, function(){ $('.popout').fadeIn(); });
	});
	
	$('.popout .item h2 a').click(function(){
		window.open(this.href);
		
		return false;
	});
	
	$('a.close').click(function(){
		if ($('.scrolling').css('width') == '890px') return false;
		$('.popout').fadeOut('slow', function(){
			$('.popout').children('div.item').hide();
			$.each(currentSelection.parent().siblings(), function(index, value){ $(value).fadeIn(); });
			currentSelection.animate({width: '165px'}, 'slow');
			currentSelection.parent().animate({top: 0, left: prevLocation, width: '165px'}, 'slow');
			currentSelection.next().fadeIn();
			$('.scrolling').animate({width: '890px', height: '190px'}, 'slow');
		});
		
		return false;
	});
	
})

function scroll(){
	$.each(images, function(index, value){
		arrLeft[index] -= 1;		

		if (arrLeft[index] == -($(images[index]).width()+spacing)){	
			totalWidth = 0;	
			for (n=0;n<images.length;n++) if (n != index) totalWidth += $(images[n]).width()+spacing;
			arrLeft[index] = totalWidth;
		}
						
		$(images[index]).css("left", arrLeft[index]);
	});
}