var t;
var limit = 3
var speed = 4000

$(document).ready(function(){
	autoSwitchCarousel();
	$('#carouselControl li a').hover(function(){
		clearInterval(t);
		var elements = $("#carouselControl li a");
		var newIndex = elements.index(this);
		switchCarousel(newIndex,elements)
		return false;
	}, function(){
		autoSwitchCarousel();
	});
	$('#carousel').hover(function(){
		clearInterval(t);
	}, function(){
		autoSwitchCarousel();
	});
});

function autoSwitchCarousel(){
	var elements = $("#carouselControl li a");
	var nextIndex = getActiveIndex(elements)+1;
	t = self.setInterval(function(){
		if(nextIndex > limit){
			nextIndex = 0;
		} 
		switchCarousel(nextIndex++,elements);
	},speed);	
}

function switchCarousel(btnIndex,set){
	if(btnIndex > limit){
		btnIndex = 0;
	} else if (btnIndex == -1){
		btnIndex = limit;
	}
	var oldIndex = getActiveIndex(set);
	var target = btnIndex*173;
	var sTarget = btnIndex*690;
	var difference = Math.abs(btnIndex-oldIndex);
	var animationSpeed = difference*100;
	$('#slideMarker').stop(true, true);
	$('#carousel').stop(true);
	set.removeClass('active').eq(btnIndex).addClass('active');
	$('#slideMarker').animate({
    	left: target
  	}, animationSpeed, function() {
    	set.removeClass('active').eq(btnIndex).addClass('active');
  	});
	$('#carousel').animate({
	   	left: -sTarget
	}, animationSpeed);	
}

function getActiveIndex(indexSet){
	var getIndex = -1;
	for(var i =0; i < indexSet.length; i ++) {
		if($(indexSet[i]).hasClass('active')) {
			getIndex = i;
			break;
		}			
	}
	return getIndex;
}
