var selectedElement;
var isHover = false;
var animation = false;

function carouselIn(event){
	hoverLogic(event.currentTarget);
	isHover = true;
}

function carouselOut(event){
	isHover = false;
}

function hoverLogic(element){
	selectedElement = $(element);
	if($(element).hasClass('firstItem')){
		$('.leftScroll a').click();
	}else if($(element).hasClass('secondItem')){
		$('.rightScroll a').click();
	}
	var id = $(element).children('.articleId').first().html();
	$('.carouselItems').removeClass('selected');
	$(element).addClass('selected');

	$('.editorsChoice .article').hide();
	$('.editorsChoice .ratingContainer').hide();

	$('#article'+id).show();
	$('#ratingContainer'+id).show();
}

$(function(){
	selectedElement = $('.carouselItems.selected');
	var selectedId = $('.carouselItems.selected span.articleId').html();
//	$('.editorsChoice .article').hide();
//	$('.editorsChoice .ratingContainer').hide();

	$('#article'+selectedId).show();
	$('#ratingContainer'+selectedId).show();

	var config = {
		 over: carouselIn, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: carouselOut // function = onMouseOut callback (REQUIRED)    
	};

	$('.carouselItems').hoverIntent(config);

	setInterval(function(){
		if(!isHover){
			var nextTarget = selectedElement.next();
			if(!nextTarget.length){
				nextTarget = $('.carouselItems').first();
			}

			hoverLogic(nextTarget);
		}
	}, 10000);

	$('.leftScroll a').click(function(event){
		event.preventDefault();
		if(!animation){
			var oldLeft = $('.innerCarousel').css('left');
			oldLeft = parseInt(oldLeft);
			var newLeft = oldLeft + 615;
			
			if(oldLeft == 0){
				return false;
			}
			
			animation = true;
			$('.innerCarousel').animate({left: newLeft}, 2000, function(){
				animation = false;
				$('#startPic').html(parseInt($('#startPic').html())-5);
				if(parseInt($('#startPic').html()) == 1){
					$('#endPic').html('5');
				}else{
					$('#endPic').html(parseInt($('#endPic').html())-5);
				}
			});
		}
	});

	$('.rightScroll a').click(function(event){
		event.preventDefault();
		if(!animation){
			var oldLeft = $('.innerCarousel').css('left');
			oldLeft = parseInt(oldLeft);
			var newLeft = oldLeft - 615;

			if(newLeft*-1 >= Math.ceil($('.innerCarousel').width()/615)*615){
				return false;
			}

			animation = true;
			$('.innerCarousel').animate({left: newLeft}, 2000, function(){
				animation = false;
				$('#startPic').html(parseInt($('#startPic').html())+5);
				if(parseInt($('#endPic').html())+5 < parseInt($('#allPic').html())){
					$('#endPic').html(parseInt($('#endPic').html())+5);
				}else{
					$('#endPic').html($('#allPic').html());
				}
			});
		}
	});

});
