$(document).ready( function() {
	
	var changeItem = function(carousel, item, itemIndex, action) {
		if ( action == 'init' ) return;
		
		var $li = $(item);
		
		if ( !$li.hasClass('active') ) {
			changeActive(item);
		}
	}
	
	var activePosition = 1;
	
	var prevFunc = function() {
		activePosition--;
		if ( activePosition < 1 ) {
			activePosition = 1;
			return true;
		}
		changeActive($('.p6 ul.carousel > li.active').prev()[0]);
		return false;
	}

	var nextFunc = function() {
		activePosition++;
		if ( activePosition > 3 ) {
			activePosition = 3;
			return true;
		}
		changeActive($('.p6 ul.carousel > li.active').next()[0]);
		return false;		
	}
	
	$('.p6 .carousel').jcarousel( {
				vertical: false,
				scroll: 1,
				animation: 'slow',
				itemVisibleInCallback: changeItem,
				buttonBeforeNextCallback: nextFunc,
				buttonBeforePrevCallback: prevFunc
	} );
	
	var changeActive = function(item) {
		// mark the clicked carousel item as 'active'
		$(item).parent().children('li.active').removeClass('active');
		$(item).addClass('active');
		
		// display the respective full media
		var index = $(item).parent().children('li').index(item);
		
		$('.item-foto > li:visible', $(item).parents('.p6')).hide();
		$('.item-foto > li:eq('+ index +')', $(item).parents('.p6')).fadeIn();
	}
			
	// make carousel items clickable
	// on click, show the respective full media item	
	$('.p6 ul.carousel > li').bind('click', function() {
		var list = $('.p6 ul.carousel');
		var indexClick = list.children('li').index(this);
		var indexActive = list.children('li').index(list.find('> li.active')[0]);
		activePosition += indexClick - indexActive;
		
		changeActive(this);
	} );

	// at the start, show the first item from the media gallery
	$('.p6 ul.carousel').find('li:first').addClass('active');
	$('.p6 ul.item-foto').find('li:first').show();
	
} );
