function mycarousel_initCallback(carousel) {
    jQuery('.promo_carousel_control a').bind('click', function() {
        carousel.scroll(jQuery('.promo_carousel_control a').index(this)+1);
        return false;
    });

    jQuery('#promo_carousel a.next').bind('click', function() {
        carousel.next();
		carousel.startAuto(0);
        return false;
    });

    jQuery('#promo_carousel a.prev').bind('click', function() {
        carousel.prev();
		carousel.startAuto(0);
        return false;
    });
	
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
	
};

function mycarousel_itemVisibleInCallbackBeforeAnimation(carousel, item, idx, state) {
    // No animation on first load of the carousel
    if (state == 'init')
        return;
    jQuery('img', item).fadeIn('slow');
};


function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
	var l = jQuery('.promo_carousel_control a').length;
	var i = (idx % l) - 1;
	if (i < 0) i += l;
    jQuery('.promo_carousel_control a').removeClass('active');
	jQuery('.promo_carousel_control a').eq(i).addClass('active');
};

$(document).ready(function() {

	jQuery("#promo_carousel").jcarousel({
        scroll: 1,
		auto: 7,
		wrap: 'circular',
        initCallback: mycarousel_initCallback,
		itemVisibleInCallback: {
            onBeforeAnimation: mycarousel_itemVisibleInCallbackBeforeAnimation,
            onAfterAnimation:  mycarousel_itemVisibleInCallbackAfterAnimation
        },
		// This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
	
	jQuery('.promo_carousel_control a').eq(0).addClass('active');
	
	function megaHoverOver(){
		$(this).find(".sub_menu").stop().fadeTo('fast', 1).show();
		$(this).addClass('hovered');
			
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = $(this).find("table").width();
			};
		})(jQuery); 
		
		$(this).calcSubWidth();
		$(this).find(".sub_menu").css({'width' : rowWidth});
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub_menu").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	  $(this).removeClass('hovered');
	}

	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 200, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$(".topmenu li .sub_menu").css({'opacity':'0'});
	$(".topmenu li").hoverIntent(config);
	
});
