var CountActive      = true;
var CountStepper     = -1;
var DisplayFormat    = "%%H%%:%%M%%:%%S%%";
var FinishMessage    = "<span class=\"lt4 icon_only\" title=\"Ein oder mehrere Artikel in Ihrem Warenkorb k&#246;nnen nicht mehr zum gew&#252;nschten Liefertermin ausgeliefert werden. Bitte w&#228;hlen Sie f&#252;r diese Artikel einen alternativen Liefertermin aus - Warenkorb aufteilen.\"></span>";
var SetTimeOutPeriod = 0;
var currentTimer     = null;
var lastDeadlineStr;

// Do not change.
function calcage(secs, num1, num2)
{
   s = ((Math.floor(secs/num1))%num2).toString();      
   if (s.length <2)
   {
      s = "0" + s;
   }        
   return "<b>" + s + "</b>";
}

function CountBack(secs)
{
   if (secs <= 0)
   {
      document.getElementById("cntdwn").innerHTML = FinishMessage;
      return;
   }
   
   //DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
   DisplayStr = DisplayFormat.replace(/%%H%%/g, calcage(secs,3600,24));
   DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
   DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

   document.getElementById("cntdwn").innerHTML = "Restzeit: "+DisplayStr;
   if (CountActive)
   {
       currentTimer = setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);
   }
}

function startCountDown(deadlineStr, currentSrvTime)
{
   //jsTrace.send( "Calculated deadline: "+ deadlineStr );
   //jsTrace.send( "Current server time: "+ new Date(currentSrvTime));
   //jsTrace.send( "Current client time: "+ new Date());

   CountStepper = Math.ceil(CountStepper);
   if (CountStepper == 0)
   {
     CountActive = false;
   }
   
   SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
   
   var dthen = new Date(deadlineStr);
   //var dnow  = new Date();  // get the client current time.
   var dnow  = new Date(currentSrvTime);
   
   if(CountStepper>0)
     ddiff = new Date(dnow-dthen);
   else
     ddiff = new Date(dthen-dnow);
     
   gsecs = Math.floor(ddiff.valueOf()/1000);
   //jsTrace.send( "Diffs in second: "+ gsecs);   
   
   if (isNaN(gsecs))
   {
       return;
   }

   // If diff is great then 4 hrs (14400 secs), no display.
   if (gsecs > 14400 )
   {
       return;
   }

   // If the new coming in deadline is as same as the old one,
   // no new counter is necessary.
   if (lastDeadlineStr == deadlineStr && gsecs > 0)
   {
      return;
   }   
   // If the new coming in deadline is different than the old one,
   // Stop the still running timer first,
   // and then create a new timmer for the new deadlinestr.
   lastDeadlineStr = deadlineStr;
   cancelOldTimer();

   CountBack(gsecs);
}

function cancelOldTimer()
{
   if (currentTimer != null)
   {
	   clearTimeout(currentTimer);
   }
}