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

  function initRadialProgress($wrapper){
    var globalSettings = $wrapper.data('rp-global') || {};
    var duration = globalSettings.duration || 1500;
    var stroke   = globalSettings.stroke || 10;
    var layout   = globalSettings.layout || 'standard';

    $wrapper.find('.sifency-rp-item').each(function(){
      var $item = $(this);
      var percent = parseFloat($item.data('percent')) || 0;

      var $svg   = $item.find('.sifency-rp-svg'),
          $bar   = $item.find('.sifency-rp-bar'),
          $track = $item.find('.sifency-rp-track'),
          $value = $item.find('.sifency-rp-value');

      var circumference = 2 * Math.PI * 90;
      $bar.attr('stroke-width', stroke);
      $track.attr('stroke-width', stroke);

      var offset = circumference - (percent/100 * circumference);

      if(layout === 'semi'){
        $svg.css('transform','rotate(-180deg)');
        var semiCirc = circumference/2;
        $track.css({'stroke-dasharray': semiCirc+' '+circumference, 'stroke-dashoffset':0});
        offset = semiCirc - (percent/100 * semiCirc);
        $bar.css('stroke-dasharray', semiCirc+' '+circumference);
      } else {
        $bar.css('stroke-dasharray', circumference);
        $track.css('stroke-dasharray', circumference);
      }

      var observer = new IntersectionObserver(function(entries){
        entries.forEach(function(entry){
          if(entry.isIntersecting){
            $bar.css({
              transition: 'stroke-dashoffset '+duration+'ms ease-out',
              'stroke-dashoffset': offset
            });
            if($value.length){
              $({Counter:0}).animate({Counter:percent},{
                duration: duration,
                easing: 'swing',
                step: function(){
                  $value.text(Math.ceil(this.Counter));
                }
              });
            }
            observer.unobserve(entry.target);
          }
        });
      }, { threshold:0.5 });

      observer.observe($item[0]);
    });
  }

  $(document).on('mouseenter', '.sifency-radial-progress-wrapper', function(){
    initRadialProgress($(this));
  });

  $('.sifency-radial-progress-wrapper').each(function(){
    initRadialProgress($(this));
  });

});
