$(document).ready(function() {	
    //Pause and resume the carousel when the user hovers over the main carousel.
    $('#main-carousel').hover(pauseCarousel, resumeCarousel);
    
    //Setup the hover actions on the carousel page controls.
	$('.navi a').hover(
    	function(){
    		//in
    		displayCarouselTooltip($(this));		
    		pauseCarousel();
    	},
    	function(){
    		//out
    		hideCarouselTooltip($(this));		
    		resumeCarousel();
    	}
	);
	
	//Setup the carousel.
	$('#main-carousel').jcarousel({
		initCallback: onCarouselInitialized,
        auto: CAROUSEL_AUTOSCROLL_DELAY,
		scroll: 1,
		wrap: "both",
		// This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null,
		itemVisibleInCallback: onCarouselItemDisplayed
    });
    
    var jqNavItems = $(".navi A");
    var navWidth = 14;
    $(".navi").width(navWidth * jqNavItems.length + 'px');
});

/** Displays the paging control tooltip.
 * @param jqCarouselPageControl: The paging control the user moused over. 
 */
function displayCarouselTooltip(jqCarouselPageControl){
    var toolTipID = jqCarouselPageControl.attr('cpos');
    var jqToolTip = $('#naviTooltip'+toolTipID);
    var jqNaviParent = $('#navi'+toolTipID);
    jqToolTip.show().position({my: "left bottom", at: "center top", of: jqNaviParent, offset: "-36 -2"});
    //To workaround some jq bug, set the position again.
    jqToolTip.position({my: "left bottom", at: "center top", of: jqNaviParent, offset: "-36 -2"});
}

/** Hides the tooltip the user moused off of. */
function hideCarouselTooltip(jqCarouselPageControl){
    var toolTipID = jqCarouselPageControl.attr('cpos');
    $('#naviTooltip'+toolTipID).hide();
}

/** Pauses the carousel from advancing.*/
function pauseCarousel(){
    $('#main-carousel').jcarousel({auto: 3600});
};

/** Resumes the carousel auto advancing.*/
function resumeCarousel(){
    $('#main-carousel').jcarousel({auto: CAROUSEL_AUTOSCROLL_DELAY});
}

/**
 * Fires when a new carousel item is displayed and updates the state of the paging controls.
 * @param index: The 1 based index of the newly displayed item.
 */
function onCarouselItemDisplayed(carousel, li, index){
	var jqNavItems = $('.navi a');
	var zeroIndex = index - 1;
	$.each(jqNavItems, function(navIndex, item){
		if(zeroIndex % jqNavItems.length == navIndex )
			$(item).addClass('active');
		else
			$(item).removeClass('active');
	});
};

/**
 * Fires when the carousel is initialized and binds the carousel paging controls.
 */
function onCarouselInitialized(carousel) {
    $('.navi a').bind('click', function() {
        //Stop the carousel so it wont start again.
        carousel.autoStopped = true;
        carousel.scroll($.jcarousel.intval($(this).attr('cpos')));
        return false;
    });
};
