// The span or div where we put the countdown timer.
// This is global so we don't have to look it up every single tick.   
//var countdownspan = document.getElementById('countdown');     

function doCountdown( targetDate, autoCount ) {         // Countdown timer.
   // targetDate is a string representing the destination date.
   // if autoCount is true the timer will automatically update every second.
   // if autoCount is false the function will display the remaining time
   // once and then terminate.

   function padZero(val) {
      // This sub-function accepts a number (val) and if less than 10
      // will return '0'+val so 5 becomes 05, 9 becomes 09, etc.
   
      if (val < 10) {                                   // Is val less than 10?
         return '0'+val;                                // Yes, insert a zero
      } else {                                          // val is not less than 10
         return val;                                    // so just return the number
      }                                                 // without doing anything 
   }                                                    

   var Today = new Date();                              // Get current time/date
   var NewYear = new Date(targetDate);                  // Get target time/date
   var Countdown = NewYear.getTime()-Today.getTime();   // Calculate Difference

   if (Countdown >= 0) {
      // We still have some time left before we reach the target date
      
//      var scratch=Math.floor(Countdown/1000);           // Discard milliseconds
//      var seconds=scratch % 60;                         // Get modulus 60 for seconds

      var scratch=Math.floor(Countdown/1000);          // Discard seconds
      var seconds=scratch % 60;                         // Get modulus 60 for seconds
      scratch = Math.floor((scratch-seconds)/60);       // Discard seconds.
      var minutes=scratch % 60;                         // Get modulus 60 for minutes
      scratch = Math.floor((scratch-minutes)/60);       // Discard minutes.
      var hours=scratch%24;                             // Get modulus 24 for hours
      scratch = Math.floor((scratch-hours)/24);         // Discard Hours
      var days=scratch;                                 // Only days remain.

      // Put the result into the div/span
//      countdownspan.innerHTML = days+' days, ' + hours+':'+padZero(minutes)+':'+padZero(seconds)+':'+tseconds+hseconds;
      countdownspan.innerHTML = days+' days, ' + hours+':'+padZero(minutes)+':'+padZero(seconds);
   } else {
      // Today's date is already past the target date.
      countdownspan.innerHTML = "It's started!";
   }            

   if (autoCount) {
      // If true was passed for autoCount, call this function again in 1 second.
      setTimeout( "doCountdown('"+targetDate+"',true)", 1000);
   }            
}
