/*
Author: Robert Hashemian
http://www.hashemian.com/

You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
********************************************************

modified by Martin Wronski

*/

/**
 * array of counters data
 */
var CountDown = new Array();

function CCountDown(TargetDate, FinishMessage, DisplayFormat, LeadingZero, CountStepper) {
  if (typeof(TargetDate)=="undefined")  TargetDate = new Date();
  if (typeof(FinishMessage)=="undefined")  FinishMessage = "";
  if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
  if (typeof(CountStepper)!="number")  CountStepper = -1;     // update every 1 second
  if (typeof(LeadingZero)=="undefined")  LeadingZero = true;

  this.CountActive = true;
  this.DisplayFormat = DisplayFormat;
  this.TargetDate = TargetDate;
  this.FinishMessage = FinishMessage;
  this.LeadingZero = LeadingZero;

  CountStepper = Math.ceil(CountStepper);
  if (CountStepper == 0) this.CountActive = false;
  this.SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
  this.CountStepper = CountStepper;
}

function CountDownCalcage(sId, secs, num1, num2, LeadingZero, iOffset) {
  s = ((Math.floor(secs / num1)) % num2).toString();
  if (LeadingZero && s.length < 2) s = "0" + s;
  return s;
}

function CountBack(sId) {
  var dthen = new Date(CountDown[sId].TargetDate);
  var dnow = new Date();
  if (CountDown[sId].CountStepper > 0) {
    ddiff = new Date(dnow-dthen);
  } else {
    ddiff = new Date(dthen-dnow);
  }
  var secs = Math.floor(ddiff.valueOf() / 1000);

  if (secs < 0) {
    document.getElementById("cntdwn"+sId).innerHTML = CountDown[sId].FinishMessage;
    return;
  }
  var iDays = CountDownCalcage(sId, secs,86400,100000, false);
  DisplayStr = CountDown[sId].DisplayFormat.replace(/%%D%%/g, iDays);
  DisplayStr = DisplayStr.replace(/%%H%%/g, CountDownCalcage(sId, secs,3600,24, CountDown[sId].LeadingZero, iDays*24));
  DisplayStr = DisplayStr.replace(/%%M%%/g, CountDownCalcage(sId, secs,60,60, CountDown[sId].LeadingZero));
  DisplayStr = DisplayStr.replace(/%%S%%/g, CountDownCalcage(sId, secs,1,60, CountDown[sId].LeadingZero));

  document.getElementById("cntdwn"+sId).innerHTML = DisplayStr;
  if (CountDown[sId].CountActive) {
    setTimeout("CountBack('"+ sId +"')", CountDown[sId].SetTimeOutPeriod);
  }
}

function RunCountDown(sId, TargetDate, FinishMessage, sClass, sHint, DisplayFormat, LeadingZero, CountStepper) {
  if (typeof(sClass)=="undefined") sClass = "countdown";

  CountDown[sId] = new CCountDown(TargetDate, FinishMessage, DisplayFormat, LeadingZero, CountStepper);

  document.write("<span id='cntdwn"+sId+"' class='" + sClass +"' title='" + sHint +"'></span>");

  CountBack(sId);
}
