jQuery(document).ready(function($){

  function initCountdown($wrapper){
    var $countdown = $wrapper.find('.sifency-countdown');
    var $expireMsg = $wrapper.find('.sifency-countdown-expire-msg');
    if(!$countdown.length) return;

    if($countdown.data('interval-id')){
      clearInterval($countdown.data('interval-id'));
    }

    var settings = { date:"", action:"message", redirect_url:"" };
    try {
      var raw = $countdown.data('cd-settings');
      if(raw){ $.extend(settings, raw); }
    } catch(err){ return; }

    if(!settings.date) return;
    var target = new Date(settings.date.replace(/-/g,"/")).getTime();
    if(isNaN(target)) return;

    var $days    = $countdown.find('[data-unit="days"]'),
        $hours   = $countdown.find('[data-unit="hours"]'),
        $minutes = $countdown.find('[data-unit="minutes"]'),
        $seconds = $countdown.find('[data-unit="seconds"]');

    var inEditor = $('body').hasClass('elementor-editor-active');

    function tick(){
      var now = new Date().getTime();
      var diff = target - now;

      if(diff < 0){
        if($countdown.data('interval-id')){
          clearInterval($countdown.data('interval-id'));
        }
        $days.text("00");
        $hours.text("00");
        $minutes.text("00");
        $seconds.text("00");

        if(!inEditor){
          if(settings.action === "hide"){
            $countdown.slideUp();
          } else if(settings.action === "message"){
            $countdown.slideUp(function(){ $expireMsg.fadeIn(); });
          } else if(settings.action === "redirect" && settings.redirect_url){
            window.location.href = settings.redirect_url;
          }
        }
        return;
      }

      var d = Math.floor(diff / 86400000),
          h = Math.floor((diff % 86400000) / 3600000),
          m = Math.floor((diff % 3600000) / 60000),
          s = Math.floor((diff % 60000) / 1000);

      $days.text(d < 10 ? "0"+d : d);
      $hours.text(h < 10 ? "0"+h : h);
      $minutes.text(m < 10 ? "0"+m : m);
      $seconds.text(s < 10 ? "0"+s : s);
    }

    tick();
    var interval = setInterval(tick, 1000);
    $countdown.data('interval-id', interval);
  }

  $(document).on('mouseenter', '.sifency-countdown-wrapper', function(){
    initCountdown($(this));
  });

  $('.sifency-countdown-wrapper').each(function(){
    initCountdown($(this));
  });

});
