var PageLoadedOn;

$(function ()
{
  if (! DealSoldOut && ! DealEnded)
  {
    if (DealSeconds_Total)
    {
      var d = new Date();
      PageLoadedOn = d.getTime();
      UpdateSecondsTillDealEnd();
    }
    UpdateDealStateBox();
  }
  else
  {
    $('#Email').focus();
  }
});

function UpdateSecondsTillDealEnd()
{
  var d = new Date();
  var Now = d.getTime();
  var MillisecondsSincePageLoaded = Now - PageLoadedOn;
  var DealMilliseconds_TotalElapsed = DealSeconds_Elapsed * 1000 + MillisecondsSincePageLoaded;
  var DealMilliseconds_Left = DealSeconds_Total * 1000 - DealMilliseconds_TotalElapsed;
  if (DealMilliseconds_Left >= 1000)
  {
    var Minutes = Math.floor(DealMilliseconds_Left / 60000);
    var Seconds = Math.floor(DealMilliseconds_Left / 1000) - Minutes * 60;
    var Hours = Math.floor(Minutes / 60);
    Minutes -= Hours * 60;

    var CountdownTimerText = ZeroPadding(Hours, 2) + 'h ' + ZeroPadding(Minutes, 2) + 'm ' + ZeroPadding(Seconds, 2) + 's';

    $('.countdown').text(CountdownTimerText);
    
    setTimeout(UpdateSecondsTillDealEnd, 1000);
  }
  else
  {
    $('.dealCountdownTimer').hide();
    $('.dealEnded').show();
    $('.buyForFriend').hide();
    $('.buy').hide();
    $('.dealIsOff').show();
    $('.limitedQuantityAvailable').hide();
    $('.dealStatus').html('&nbsp;');
  }
}

function UpdateDealStateBox()
{
  var Refresh = true;
  var s;
  if (MaxNumberOfVouchers > 0 && PaidVoucherCount >= MaxNumberOfVouchers)
  {
    $('.dealSoldOut').show();
    $('.buyForFriend').hide();
    $('.buy').hide();
    $('.dealIsOff').show();
    $('.dealCountdownTimer').hide();
    $('.dealStatus').html('&nbsp;');
    
    s = 'Sold out ' + SoldOutDT;
    $('.limitedQuantityAvailable').text(s);
    Refresh = false;
  }
  
  $('.vouchersPurchased').text(addCommas(PaidVoucherCount) + ' purchased');
  
  if (Refresh)
  {
    setTimeout(RefreshDealStateBox, 300000);
  }
}

function RefreshDealStateBox()
{
  var url = '/misc/json-deal-state.php';
  var params = { 'DealID' : DealID };
  var callback = function (data, status, http)
  {
    if(! data['ErrorMsg'])
    {
      PaidVoucherCount = data['PaidVoucherCount'];
      TippingPointDT = data['TippingPointDT'];
      SoldOutDT = data['SoldOutDT'];
      UpdateDealStateBox();
    }
  };
  
  $.getJSON(url, params, callback);
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}
