
/**
 * Wyświetla zegar odliczający godziny, minuty i sekundy od daty (chwili)
 * bieżącej do daty docelowej.
 *
 * Po osiągnięciu daty docelowej zegar pokazuje zero.
 *
 * @param targetDate        {Date}        Data docelowa, reprezentująca chwilę czasu "0"
 * @param displayElement    {HTMLElement} Element, w którym będzie wyświetlane odliczanie
 * @param onCountdownFinish {function}    (Parametr opcjonalny) Funkcja, która zostanie
 *                                        wywołana gdy odliczanie się skończy. Jeśli
 *                                        jako data docelowa będzie podana chwila z przeszłości,
 *                                        to funkcja ta będzie wywołana od razu.
 *
 */
function countdown(targetDate, displayElement, onCountdownFinish/* = null*/) {
  if (!(targetDate && displayElement)) {
    return;
  }
  var formatTimeInterval = function(seconds) {
    var hrs = Math.round(seconds / 3600)
    var min = Math.round(seconds / 60) % 60;
    var sec = seconds % 60;
    return (hrs + ':' + min + ':' + sec).replace(/(^|:)(\d)(?=:|$)/g, '$10$2');
  };
  var refreshTimer = function() {
    var now = new Date();
    var diffMilliseconds = targetDate.getTime()  - now.getTime();
    var diffSeconds = Math.round(diffMilliseconds / 1000);
    if (diffSeconds < 0) {
      diffSeconds = 0;
    }
    var countdownHTML = formatTimeInterval(diffSeconds)
    if (countdownHTML != displayElement.innerHTML) {
      displayElement.innerHTML = countdownHTML;
    }
    if (diffSeconds === 0) {
      clearInterval(intervalId);
      if (typeof onCountdownFinish === 'function') {
        onCountdownFinish(targetDate);
      }
    }
  };
  var intervalId = setInterval(refreshTimer, 250);
  refreshTimer();
}

/* Właściwa inicjalizacja zegarów:
(function() {
  var now = new Date();

  // data docelowa: 3 marca 2010, godz. 20:48:10 (miesiące liczymy od zera, a dni od jeden... lol)
  countdown(new Date(2010, 2, 3, 20, 48, 10, 0), document.getElementById('counter1'));

  // data docelowa: teraz plus 2 h 12 min 41 sek
  countdown(new Date(now.getTime() + (2 * 3600 + 12 * 60 + 41) * 1000), document.getElementById('counter2'));

  // data docelowa: teraz plus 1 min 3 sek
  countdown(new Date(now.getTime() + (1 * 60 + 3) * 1000), document.getElementById('counter3'));

  // data docelowa: teraz + 5 sek
  countdown(new Date(now.getTime() + 5 * 1000),
            document.getElementById('counter_alert'),
            function() {
              alert('Licznik czwarty: czas minął!');
            }
  );

  
})();
*/

  var now = new Date();
