function getWidth(items) {
	var width = 0;
	items.each(function() {
		width = $(this).width() + width;
	});
	return width;
}

function carouselAnimCallback(link) {
	link.removeClass('animated');
}

function moveCarousel() { 
	slideCarousel($('#carousel-canvas > div').width(), 'right')
}

function slideCarousel(limit, dir) {
	var movement = 440;
	var speed = 400;
	var slider = $('#carousel-canvas > div');
	var spot = $('#carousel-canvas').width() - slider.position().left;
	if (spot+movement < limit && !slider.is(':animated')) {
		//right arrow clicked
		if ( dir == 'right')
			slider.stop(true,true).clearQueue().animate({"left":"-="+movement+"px"},speed);
		//left arrow clicked
		if (dir == 'left')
			slider.stop(true,true).clearQueue().animate({"left":"-=-"+movement+" px"},speed );
		
	} else if ( spot+movement >= limit && !slider.is(':animated') ) {
		slider.stop(true,true).clearQueue().animate({"left":"-=" + ((movement * 2) - spot) + "px"},speed, carouselAnimCallback(slider) );
	}	
}

$(document).ready(function(){
	//Hero Stuff
	$('#tabs').width(getWidth($('#tabs div')));
	$('#hero li a').click(function(event) { event.preventDefault() });
	$('#hero li a').hoverIntent(function () {
		var current = $('#tabs');
		var dest = $($(this).attr('href'));
		var move = dest.position().left + current.position().left;
		$('#tabs').stop(true,false).animate({"left": "-="+move+"px"}, 400);
		$('#hero ul .current').removeClass('current');
		$(this).offsetParent().addClass('current');
		clearInterval(carouselTimerID);
	}, function(){
		carouselTimerID = setInterval(moveCarousel, 3000);
	});
	
	//Carousel Stuff
	$('#carousel-canvas > div').width(getWidth($('#carousel-canvas > div div.carousel-content')));
	var min =  $('#carousel-canvas').width()
	var max = $('#carousel-canvas > div').width();
		
	//var carouselTimerID = setInterval(moveCarousel, 1000);
	var carouselTimerID = setInterval(moveCarousel, 3000);
	$('#carousel .right-arrow').click(function(event) {
  		event.preventDefault();
		clearInterval(carouselTimerID);
		slideCarousel(max, 'right');
		carouselTimerID = setInterval(moveCarousel, 3400);
	});
	$('#carousel .left-arrow').click(function(event) {
  		event.preventDefault();
		clearInterval(carouselTimerID);
		slideCarousel(min, 'left')
		carouselTimerID = setInterval(moveCarousel, 3400);
	});
	$('#carousel .carousel-content').hoverIntent(function() {clearInterval(carouselTimerID);}, function(){ carouselTimerID = setInterval(moveCarousel, 3000);})			
});