/*
Author: Robert Hashemian
http://www.hashemian.com/
*/

function calcage(secs, num1, num2, dzero) {
  var LeadingZero = dzero;

  s = ((Math.floor(secs/num1))%num2).toString();
  if (LeadingZero && s.length < 2)
    s = "0" + s;
  return s;
}

function CountBack(id, secs) {
  var CountActive = true;
  var CountStepper = -1;
  var DisplayFormat = "%%D%%%%H%%:%%M%%:%%S%%";

  var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;

  if (secs < 0) {
    document.getElementById("cntdwn-" + id).innerHTML = wpcp_no_coupons;
    wpcp_isexpired = true;
    return;
  }
  
  var hour = calcage(secs,86400,100000,false);

  if(hour == '1') {
    DisplayStr = DisplayFormat.replace(/%%D%%/g, hour + ' <small>' + wpcp_countdown_day + '</small> ');
  } else if (hour == '0') {
    DisplayStr = DisplayFormat.replace(/%%D%%/g, '');
  } else {
    DisplayStr = DisplayFormat.replace(/%%D%%/g, hour + ' <small>' + wpcp_countdown_days +'</small> ');
  }
  
  DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24,true));
  DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60,true));
  DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60,true));

  document.getElementById("cntdwn-" + id).innerHTML = DisplayStr;

  if (CountActive)
    setTimeout("CountBack('" + id + "', " + (secs+CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(name) {
 document.write("<span id='cntdwn-" + name + "'></span>");
}

function startCountdown(id, tdate, edate) {
  var CountStepper = -1;

  if (CountStepper == 0)
    CountActive = false;

  putspan(id);

  var dthen = new Date(tdate);
  var dnow = new Date(edate);
  if(CountStepper>0)
    ddiff = new Date(dnow-dthen);
  else
    ddiff = new Date(dthen-dnow);
  gsecs = Math.floor(ddiff.valueOf()/1000);
  CountBack(id, gsecs);
}
