﻿var DAYS = new Array("dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi");
var MONTHS = new Array("janv.", "fév.", "mars", "avril", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc.");
var MONTHS_FULL = new Array("janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre");
var ECHIROLLES_DAY = 2; // tuesday
var ECHIROLLES_WEEK = 0; // 1st week
var VOIRON_DAY = 4; // thursday
var VOIRON_WEEK = 1; // 2nd week

// Function called at init on agenda.html page
function updateDatesOnAgenda() {
  updateDates();
  updateText('agenda_echirolles', buildNextDateFull(ECHIROLLES_DAY, ECHIROLLES_WEEK));
  updateText('agenda_voiron', buildNextDateFull(VOIRON_DAY, VOIRON_WEEK));  
}

// Function called at init
function updateDates() {
  updateText('echirolles', buildNextDate(ECHIROLLES_DAY, ECHIROLLES_WEEK));
  updateText('voiron', buildNextDate(VOIRON_DAY, VOIRON_WEEK));
}


function updateText(id, text) {
  var newNode = document.createTextNode(text);
  var prevNode = document.getElementById(id).firstChild; 
  document.getElementById(id).replaceChild(newNode, prevNode);
}

function buildNextDate(expectedDay, expectedWeek) {
  var nextDate = findNextDate(expectedDay, expectedWeek);
  var month = nextDate.getMonth();
  var day = nextDate.getDate();
  return day + " " + MONTHS[month];
}


function buildNextDateFull(expectedDay, expectedWeek) {
  var nextDate = findNextDate(expectedDay, expectedWeek);
  var month = nextDate.getMonth();
  var day = nextDate.getDate();
  return day + " " + MONTHS_FULL[month];
}

// Returns a Date object
function findNextDate(expectedDay, expectedWeek) {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth();
  var today = now.getDate();
  
  var nextDay = findDayNumber(year, month, expectedDay, expectedWeek);
  if (nextDay < today) {
    // Day is past ; go to next month
	month = (month + 1) % 12;
	nextDay = findDayNumber(year, month, expectedDay, expectedWeek);
  }

  return new Date(year, month, nextDay, 0, 0, 0, 0);;
}


// Returns the expected day of the month for a given month and year and the expected day index
// For instance:
// - when is the first monday of january 2011: findDayNumber(2011, 1, 1, 0)
// - when is the second thursday of march 2011: findDayNumber(2011, 3, 4, 1)
//
// Parameters
// year: year of calculation
// month: month of calculation
// day: expected day: 0 = sunday, 1 = monday, ..., 6 = saturday
// weekNb: 0 = first week, 1 = second week, etc...
function findDayNumber(year, month, expectedDay, expectedWeek) {
  var date = new Date(year, month, 1, 0, 0, 0, 0);
  var dayOfWeek = date.getDay();
  
  return ((7 + expectedDay - dayOfWeek) % 7) + 1 + expectedWeek*7;
}


