$( document ).ready( function(){
	start_slides( '#slides img', 4500 );
	
	$('#nav li').hover(
		function(){ $(this).find('.sub-nav').show(); $(this).find('a:eq(0)').addClass('active'); },
		function(){ $(this).find('.sub-nav').hide(); $(this).find('a:eq(0)').removeClass('active'); }		
	);
	
	$('.content-slider').jcarousel({
    	easing: null,
    	scroll: 1,
    	wrap: 'both',
    	itemVisibleInCallback: {
    		onBeforeAnimation: callback1,
    		onAfterAnimation: callback2,
    	}
    });
	
    $('.img-slider').jcarousel({
    	easing: null,
    	scroll: 1,
    	initCallback: double_slider_initCallback,
    	buttonNextHTML: null,
		buttonPrevHTML: null,
		wrap: 'both'
    });

});

function callback1(carousel, item) {
	$('.content-slider .jcarousel-item').css('visibility', 'hidden');
}

function callback2(carousel, item) {
	$(item).css({
		'display' : 'none',
		'visibility': 'visible'
	}).fadeIn(500);
}

function double_slider_initCallback(carousel) { 
	$('.main-slider .jcarousel-next').live('click', function() {
		carousel.next();
		return false;
	}); 
	
	$('.main-slider .jcarousel-prev').live('click', function() {
		carousel.prev()
		return false;
	}); 
}

function start_slides( item, time, callback ) {
	var all_items = $( item ).length;
	if ( all_items < 1 ) return;
	var zindex = all_items;
	var i=0;
	$( item ).each( function(){
		$( this ).css( { 'z-index': zindex } );
		if ( i > 0 ) $( this ).hide();
		zindex--;
		i++;
		var img = new Image();
		img.src = $( this ).attr('src');
	});
	
	var index = 0;
	var next;
	var time = time || 5000;
	var callback = callback || function(){};
	
	var interval = window.setInterval( function(){
		if ( index == all_items ) index = 0;
		next = index + 1;
		
		if ( next == all_items ) next = 0;
		
		$( item + ":eq(" + index + ")" ).fadeOut(1200);
		$( item + ":eq(" + next + ")" ).fadeIn(1200, function(){
			callback( next );
		});
		
		index++;
	}, time);
}
