var ifjCalendarInit = function() {

  function dateChanged(calendar) {
    if (calendar.dateClicked) {

      // get the date of the edition clicked on

      var editionDate = calendar.date;

      if (!editionDate)
          return;

      while (editionDate.getDay() != 4)
      {
          editionDate = new Date(editionDate.getTime() - (1000*60*60*24));
      }

      // don't do anything if edition is in the future

      var now = new Date();

      if (editionDate.getTime() > now.getTime())
      {
      	return;
      }

      // make the date a saturday

      editionDate = new Date(editionDate.getTime() + (1000*60*60*24*2));

      var y = editionDate.getFullYear();
      var m = editionDate.getMonth();     // integer, 0..11
      var d = editionDate.getDate();      // integer, 1..31

      m += 1;
      m = (m<10?"0"+m:m);
      d = (d<10?"0"+d:d);

      // get the section we're in

      var section = "";
      var matches = window.location.pathname.match(/\d\d\d\d\/\d\d\d\d\/(.*)/);

      if (matches)
      {
          section = matches[1];
      }
      else
      {
          section = "news/currentedition/";
      }

      // redirect...

      window.location = "http://www.farmersjournal.ie/" + y + "/" + m + d + "/" + section;
    }
  };

  Calendar.setup(
    {
      flat         : "ifj-calendar-container", // ID of the parent element
      flatCallback : dateChanged,           // our callback function
      firstDay     : 4,
      weekNumbers  : false,
      showOthers   : true
    }
  );
};

if (window.addEventListener){
      window.addEventListener('load', ifjCalendarInit, false); 
} else if (window.attachEvent){
      window.attachEvent('onload', ifjCalendarInit);
}

