var g = null;
var index = 1;
var delay = 0;
$(document).ready(function() {
	// var i = window.location.hash.substr(-1);
	// settab(i.length ? i-1 : 0);
	settab(0);
	$(".buttons").children().click(function(e){
		delay = 2;
	});
	var lock = 0;
	$(".buttons").children().hover(function() {
		settab(linkindex($(this)));
		lock = 1;
	}, function() {
		lock = 0;
	});
	setInterval(function() {
		if (lock)
		  return;
		if (delay) {
		  delay--;
		  return;
		}
		var index_ = (index + 1) % $(".tabcontent").length;
		settab(index_);
		// temps entre chaque changement en ms
	}, 7000);
});

function settab(i) {
  if(index!=i) {
  index = i;
  //$(".tabcontent").each(function() { $(this).hide(); });
  $(".tabcontent").fadeOut(100);
  // temps pour le fade in en ms
  $(".tabcontent").eq(i).fadeIn(100);

  // change buttons style
  var buttons = $(".buttons").children();
  buttons.removeClass("selected");
  buttons.eq(i).addClass("selected");
  }
}

function linkindex(element) {
  var i = 0, res = 0;
  $(".buttons").children().each(function() {
    if ($(this).attr("href") == element.attr("href"))
      res = i;
    i++;
  });
  return res;
}

function readdates(o) {
  if (typeof o != "object")
    return;
  for (var i in o)
    if (typeof o[i] == "object") {
      readdates(o[i]);
    } else {
      var a = (new Date(Date.parse(o[i])));
      if (!isNaN(a.getDate()))
	o[i] = a;
    }
  return o;
}


function cyclenews(id, list) {
  if (list.length == 0) return;
  var index = 0;
  var timeid = null;
  var display = function() {
    clearTimeout(timeid);
    $(id+" div").fadeOut(500, function() {
      var item = list[index];
      var content;
      if (typeof item.messagesoon == "undefined")
	content = (item.startdate.toLocaleDateString()+
		       " "+
		       item.title);
      else
	content = (item.startdate.toLocaleDateString()+
		       " "+
		       "<b>" + item.title + "</b><br>" +
		      item.messagesoon);
      $(id+" div").fadeIn(100).html(content);
      index = (index + 1) % list.length;
      timeid = setTimeout(display, 5000);
    });
  };
  $(id+" .previous").click(function() {
    index = (index - 2) % list.length;
    if (index < 0)
      index = list.length - 1;
  });
  $(id+" .next,"+id+" .previous").click(function() { display(); });
  display();
}
