$(document).ready( function () {
	var Slider = ( function () {
		var current = 1,
		old = 0,
		total = 0,
		delay = 6000,
		auto = true,
		duration = 600,
		reg = /[0-9]$/,
		timer = null;

		function show() {
			$('#bloc-actu-' + current).css("display", "block");
			$('#bloc-actu-' + current).animate({
				opacity : "1"
			}, duration, onShow);
		}

		function hide() {
			$('#bloc-actu-' + old).animate({
				opacity : "0"
			}, duration, onHide);
		}

		function onShow() {
			timer = window.setTimeout(autorun, delay);
		}

		function changeMenu() {

			$("a.puce-nav-actus").each( function () {
				var matches = this.id.match(reg);
				if (matches !== null && matches.length > 0) {
					var num = parseInt(matches[0], 10);
					if (num === current) {
						if (!$(this).hasClass("selected")) {
							$(this).addClass("selected");
						}
					}
					else {
						if ($(this).hasClass("selected")) {
							$(this).removeClass("selected");
						}
					}
				}
			});
		}

		function onHide() {
			$('#bloc-actu-' + old).css("display", "none");
			changeMenu();
			show();
		}

		function change(num) {
			if (num !== current) {
				old = current;
				current = num;
				hide();
			}
		}

		function autorun() {
			if (auto) {
				var num = current + 1;
				if (num > total) {
					num = 1;
				}
				change(num);
			}
		}

		function click(e) {

			var num;
			var matches = e.currentTarget.id.match(reg);
			if (matches !== null && matches.length > 0) {
				num = parseInt(matches[0], 10);
				if (!isNaN(num)) {
					auto = false;
					window.clearTimeout(timer);
					change(num);

				}
			}
		}

		function init() {

			total = $("div.actu").length;
			timer = window.setTimeout(autorun, delay);

			$("div.actu").each( function () {
				if (!/-1$/.test(this.id)) {
					$(this).css("opacity", "0").css("display", "none");
				}
			});
			$("a.puce-nav-actus").each( function () {
				$(this).click(click);
			});
		}

		init();
	}());
});
