jQuery(document).ready(function() {
    var zoom = jQuery('#content .event-zoomfront');
	
    var timer_diapo,
        current = 0,
		diapoStoped = false,
        diaporama = zoom.find('.courousel-blocs li'),
		navigation = zoom.find('.courousel-navigation li'),
		ssMenu = jQuery('#menu .ss-menu'),
		taille = 755,
		taille_nav = 160;

    var stopDiaporama = function() {
        window.clearTimeout(timer_diapo);
		timer_diapo = undefined;
		diapoStoped = true;
    };

    var slideDiaporama = function() {
		var n = (current+1 == diaporama.length) ? 0 : current+1;

		diapoFadeTo(n);
    };

	var strcat = function(el, tai, maxHeight) {
		var index = -1;
		var text = el.html();
		var words = text.substring(0, tai).split(' ');
		while(el.height() > maxHeight) {
			var smallText = words.slice(0, words.length + index).join(' ')+'...';
			el.html(smallText);
			index--;
			if(index < -50) {
				break;
			}
		}
		el.parent().css({'width': tai});
	}

	var diapoFadeTo = function(n) {
		var next = diaporama.eq(n);
		var e = diaporama.eq(current);
        next.css('z-index', 1);

		var nav_next = navigation.find('.slice').eq(n);
		var nav_e = navigation.find('.slice').eq(current);
		nav_next.stop(true, true).slideDown();
		nav_e.stop(true, true).slideUp();

		ssMenu.css({'backgroundImage': 'url('+next.find('img').attr('src')+')'});
		
		e.animate({
           'opacity': 0
        },
        '3000',
        function() {
			next.css('z-index', 2).addClass('diapo_current');
            e.css({
                'opacity': 1,
                'z-index': 0
            })
			.removeClass('diapo_current');
        });

		current = n;
		if(!diapoStoped) {
			timer_diapo = window.setTimeout(slideDiaporama, 3000);
		}
	}

    diaporama.eq(0).css('z-index', 2);
	navigation.find('.slice').eq(0).show();
	ssMenu.css({'backgroundImage': 'url('+ diaporama.eq(0).find('img').attr('src')+')'});
	
	diaporama.find('.courousel-acroche span').each(function(){
		strcat(jQuery(this), taille, 16);
	});
	
	navigation.find('span').each(function(){
		strcat(jQuery(this), taille_nav, 30);
	});

    var startDiaporama = function() {
        timer_diapo = window.setTimeout(slideDiaporama, 3000);
		diapoStoped = false;
    };

    diaporama.hover(function() {
        stopDiaporama();
    }, function () {
		startDiaporama();
	});

	navigation.hover(function() {
		stopDiaporama();
		diapoFadeTo(navigation.index(this));
	}, function () {
		startDiaporama();
	});

    //diaporama.find('a').fancybox();

    startDiaporama();
});

