jQuery(document).ready(function() {
    (function($) {
	var viewport_height	= $('.content-actus').height();
	var ll	= new LinkedList.Circular();
	$( '.content-actus .content-actu' ).each(function() {
	    ll.append( new LinkedList.Node( $(this) ) );
	});
	var delay	= 11000;
	var start_y	= 0;
	ll.each(function(node, i) {
	    node.data.css({
		position: 'absolute',
		top: start_y
	    });
	    start_y	+= node.data.height();
	});
	if (start_y < viewport_height) {
	    return false;
	}

	var clone	= function(idx, y) {
	    var node	= ll.at(idx).data.clone();
	    node.css({
		position: 'absolute',
		top: y
	    });
	    ll.last.data.parent().append(node);
	    ll.append( new LinkedList.Node(node) );
	    return node;
	}
	var prepare	= function() {
	    var h	= 0;
	    ll.each(function(node, i) {
		h	+= node.data.height();
	    });
	    var j	= 0;
	    while(h < viewport_height + ll.first.data.height()) {
		var node    = clone(j, h);
		h   += node.height();
		j++;
	    }
	}
	var stop	= function() {
	    var killed  = [];
	    ll.each(function(node, i) {
		if (parseInt(node.data.css('top'), 10) + node.data.height() <= 0) {
		    killed.push(i);
		}
	    });

	    for(var i=0; i<killed.length; i++) {
		var node    = ll.at(killed[i]);
		if (node.data.text() != ll.last.data.text()) {
		    clone(killed[i], parseInt(ll.last.data.css('top'), 10) + ll.last.data.height());
		}
		node.data.remove();
		ll.remove(node);
	    }

	    animate();
	}
	var animate	= function() {
	    prepare();
	    ll.each(function(node, i) {
		node.data.animate({
		    top:    '-='    + ll.first.data.height()
		}, delay, function() {
		    if (i == ll.length-1) {
			stop();
		    }
		});
	    });
	}

	animate();
    })(jQuery);
});

