// date.js - a bunch of hacking which should eventually lead to
// automatically-updating ride calendar links.

var days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

var month_name = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

// naive -- doesn't handle 100-, 400-year exceptions (which won't affect us
// anyway)
function isLeapYear(y) { return y%4 == 0; }

// Returns a date representing the first date of the next month (i.e. month
// and year are valid, date -- not so much).
function nextMonth() {
  var d = new Date()
  d.setDate(1);
  d.setMonth(d.getMonth()+1); // automatically handles rollover
  return d;
}

// Does d represent one of the last n days of the month?
function lastN(d, n) {
  var year = d.getFullYear(); // 4-digit
  var date = d.getDate();     // 1-based
  var month = d.getMonth();   // 0-based
  var ndays = days_in_month[month];
  if (month == 1 && isLeapYear(year)) ndays = 29;
  return ndays-date+1 <= n;
}

function getIntValueFromTextInput(name) {
  return parseInt(document.getElementsByName(name)[0].value);
}

// Return a string representation of x, truncated to 2 digits, padded with
// leading 0s if necessary
function format2(x) {
  x = x%100;
  return (x < 10 ? '0' : '') + x;
}

// If text is undefined, innerHTML is not altered.
function setRideCalendarLink(a, month, year) {
  a.href = doc_base + '/ride_calendar/' + year + '/' +
           format2(month+1) + '.pdf';
}

function set_ride_calendar_section(id, alt_id) {
  d = new Date();
  nmd = nextMonth();
  if (lastN(d, 5)) {
    id = alt_id;
  }
  var e = document.getElementById(id);

  // set links
  var a = e.getElementsByTagName('a');
  for (var i = 0; i < a.length; ++i) {
    var anchor = a[i];
    if (anchor.className == 'this_month') {
      setRideCalendarLink(anchor, d.getMonth(), d.getFullYear());
    } else if (anchor.className == 'next_month') {
      setRideCalendarLink(anchor, nmd.getMonth(), nmd.getFullYear());
    }
  }

  // set month names
  var s = e.getElementsByTagName('span');
  for (var i = 0; i < s.length; ++i) {
    var span = s[i];
    if (span.className == 'this_month') {
      span.innerHTML = month_name[d.getMonth()];
    } else if (span.className == 'next_month') {
      span.innerHTML = month_name[nmd.getMonth()];
    }
  }

  e.style.display = '';
}

// used to set href for main ride calendar link; switches at noon on the last
// day of the month
function set_ride_calendar_link(id) {
  var d = new Date();
  if (lastN(d, 1) && d.getHours() >= 12) {
    d = nextMonth();
  }
  var a = document.getElementById(id);
  setRideCalendarLink(a, d.getMonth(), d.getFullYear());
}
