var it = {
	tocItemColor: '#bab0c0',
	tocItemHoverColor: '#e5e1e7',
	tocHoverDelay: 200,
	emptyFn: function() {},
	caretTimer: null
};

it.moveCaret = function(target, instant) {
	if (!instant) instant = false;
	var targetWidth = $(target).width();
	var targetX = $(target).position().left;
	var caretX = $('#caret').position().left;
	var caretWidth = $('#caret').width();
	var newCaretX = (targetX + (targetWidth / 2)) - (caretWidth / 2);
	$('#caret').css('left', caretX);
	if (instant)
		$('#caret').css('left', newCaretX + 510);
	else
		$('#caret').animate({'left': newCaretX + 510}, 500);
};

it.tocHover = function(target) {
	it.caretTimer = null;
	var hoverItem = $('#toc li.hover a');
	var selItem = $('#toc li.current_page_item a');
	var thisItem = $(target);
	if (hoverItem != selItem)
		hoverItem.animate({color: it.tocItemColor}, 500);
	hoverItem.parent().removeClass('hover');
	thisItem.parent().addClass('hover');
	if (thisItem != selItem)
		thisItem.animate({color: it.tocItemHoverColor}, 500);
	it.moveCaret(target);
};

it.tocOut = function() {
	it.caretTimer = null;
	var hoverItem = $('#toc li.hover a');
	if (!hoverItem.parent().hasClass('current_page_item')) {
		$('#toc li.hover a').animate({color: it.tocItemColor}, 500);
		it.moveCaret('#toc li.current_page_item a');
	}
	hoverItem.parent().removeClass('hover');
};

$(document).ready(function() {
	if (!$('#toc li.current_page_item').length)
		$('#toc li:first').addClass('current_page_item');
	it.moveCaret('#toc li.current_page_item a', true);
	$('#caret').fadeIn(500);
	
	$('#toc a').hover(
		function() {
			var that = this;
			if (it.caretTimer) window.clearTimeout(it.caretTimer);
			it.caretTimer = window.setTimeout(function() { it.tocHover(that) }, it.tocHoverDelay);
		},
		it.emptyFn
	);
	$('#toc').hover(
		it.emptyFn,
		function() {
			if (it.caretTimer) window.clearTimeout(it.caretTimer);
			it.caretTimer = window.setTimeout(it.tocOut, it.tocHoverDelay);
		}
	);
	
});