// mjh-countdown.js
// Copyright Matthew J Heaton 2011

var dateCountdown=new Date(2011, 5 /*June*/, 10, 16 /*4pm*/, 0 ,0, 0);
var timerCountdown = null;
var szCountdownPre='';
var szCountdownPost=' to the festival.';
var szCountdownOver='The festival is on now.';

function ShowCountdown(id)
{
 var dateNow = new Date();
 var nSeconds = parseInt((dateCountdown.getTime() - dateNow.getTime()) / 1000);
 var szCountdown = szCountdownPre;
 if (nSeconds > 0)
 {
  var nMinutes = parseInt(nSeconds / 60);
  nSeconds -= nMinutes*60;
  var nHours = parseInt(nMinutes / 60);
  nMinutes -= nHours * 60;
  var nDays = parseInt(nHours / 24);
  nHours -= nDays * 24;
  var nWeeks = parseInt(nDays / 7);
  nDays -= nWeeks * 7;

  if (nWeeks)
   szCountdown += nWeeks + ' week' + (nWeeks>1?'s':'') + ', ';
  if (nDays)
   szCountdown += nDays + ' day' + (nDays>1?'s':'') + ', ';
  if (nHours)
   szCountdown += nHours + ' hour' + (nHours>1?'s':'') + ', ';
  if (nMinutes)
   szCountdown += nMinutes + ' minute' + (nMinutes>1?'s':'') + ', ';
  if (nSeconds)
   szCountdown += nSeconds + ' second' + (nSeconds>1?'s':'') + '';
  szCountdown = szCountdown.replace(/, $/, '');
  szCountdown += szCountdownPost
 }
 else
 {
   var dateFinish = new Date(2011, 5, 27, 0, 0, 0, 0);
   if (dateNow.getTime() > dateFinish.getTime())
    szCountdown = 'The 2011 festival has come and gone. The 2012 festival is next...';
   else
    szCountdown = szCountdownOver;
   if (timerCountdown) clearInterval( timerCountdown );
 }
 var textCountdown = document.getElementById(id);
 if (textCountdown) setTextContent( textCountdown, szCountdown );
 if (!timerCountdown) timerCountdown = setInterval( 'ShowCountdown("'+id+'");', 1000 );
}

function setTextContent(element, text)
{
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
}
