( function( $ ) {

  $(document).ready(function(){

    window.et_pb_jt_counter_init = function(){

      var is_frontend_builder = $('body').hasClass('et-fb');
      var $et_pb_jt_counter  = $( '.et_pb_jt_counter' );


      if ( $et_pb_jt_counter.length || is_frontend_builder ) {

        function et_pb_jt_counter_decimal_places(num) {
          var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
          if (!match) { return 0; }
          return Math.max( 0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
        }

        function et_pb_jt_counter_decimal_round(number, precision) {
            if (number == 0 ) return 0;
            var factor = Math.pow(10, precision);
            var tempNumber = number * factor;
            var roundedTempNumber = Math.round(tempNumber);
            return roundedTempNumber / factor;
        };

        function et_pb_jt_format_number( number_value, separator ) {
          return number_value.toString().replace( /\B(?=(\d{3})+(?!\d))/g, separator );
        }

        window.et_pb_reinit_et_pb_jt_counter = function( $et_pb_jt_counter ) {

          $et_pb_jt_counter.each(function(){

            var $this_counter   = $(this); //.children('et_pb_jt_counter_counter').first();
            var count_duration  = $this_counter.data('count-duration') ? $this_counter.data('count-duration') : 2000;
            var count_to        = $this_counter.data('count-to') ? $this_counter.data('count-to') : 0;
            var count_from      = $this_counter.data('count-from') ? $this_counter.data('count-from') : 0;
            var decimal_places  = $this_counter.data('decimal-places') ? $this_counter.data('decimal-places') : Math.max(et_pb_jt_counter_decimal_places(count_to), et_pb_jt_counter_decimal_places(count_from));
            var show_decimals   = count_to % 1 !== 0 || count_from % 1 !== 0 || $this_counter.data('force-decimal-places');
            var counter_type    = $this_counter.data('counter-type') ? $this_counter.data('counter-type') : 'number';
            var circle_percent  = $this_counter.data('circle-percent') ? $this_counter.data('circle-percent') : 100;
            var separator       = $this_counter.data('number-separator'); 

            var size = 0;
            var trackColor = false;
            var lineWidth = 0;
            var barColor = false;
            var trackAlpha = false;
            var lineCap = false;
            var scaleColor = false;
            var scaleLength = 0;
            var rotate = 0;

            //Setup Circular counter if necessary
            if ('circle' === counter_type) {

              size        = $this_counter.data('circle-size') ? $this_counter.data('circle-size') : $et_pb_jt_counter.width();
              trackColor  = $this_counter.data('circle-track-color');
              lineWidth   = Math.min($this_counter.data('circle-line-width'), size);
              barColor    = $this_counter.data('circle-bar-color');
              // trackAlpha  = $this_counter.data('circle-track-alpha');
              lineCap     = $this_counter.data('circle-line-cap');
              scaleColor  = $this_counter.data('circle-scale-color') ? $this_counter.data('circle-scale-color') : false;
              scaleLength = $this_counter.data('circle-scale-length');
              if (scaleLength) {
                lineWidth   = Math.min($this_counter.data('circle-line-width'), size - (2*scaleLength) - 4);
              }
              rotate      = $this_counter.data('circle-rotate');

              //Enable responsive circle size if no size is set
              if(!$this_counter.data('circle-size')) {
                new ResizeSensor($this_counter, function() {
                    $this_counter.find('canvas').css('width', $this_counter.width());
                    $this_counter.find('canvas').css('height', $this_counter.width());
                });
              }
            }

            $this_counter.easyPieChart({
              animate:     { duration: count_duration, enabled: true },
              easing:      'easeOutBounce',
              size:        size,
              barColor:    barColor,
							trackColor:  trackColor,
              // trackAlpha:  trackAlpha,
							lineWidth:   lineWidth,
              lineCap:     lineCap,
              scaleColor:  scaleColor,
              scaleLength: scaleLength,
              rotate: rotate,
							onStart: function() {},
							onStep: function(from, to, percent) {
                //Normalize percent
                if ('circle' === counter_type) {
                  percent = percent * 100 / circle_percent
                }

                var number = count_from - (count_from - count_to) * (percent / 100);
                number = !show_decimals ? Math.round( parseInt( number ) ) : et_pb_jt_counter_decimal_round( number, decimal_places ).toFixed(decimal_places);

                //TODO separator formattierung
                number = et_pb_jt_format_number(number, separator);

                $(this.el).find('.et_pb_jt_counter_number_number').text( number );
							},
							onStop: function(from, to) {
                var number = !show_decimals ? Math.round( parseInt( count_to ) ) : et_pb_jt_counter_decimal_round( count_to, decimal_places ).toFixed(decimal_places);

                //TODO separator formattierung
                number = et_pb_jt_format_number(number, separator);

								$(this.el).find('.et_pb_jt_counter_number_number').text( number );
							}
            });

          });
        }
        window.et_pb_reinit_et_pb_jt_counter( $et_pb_jt_counter );
      }



      if ( $.fn.waypoint && 'yes' !== et_pb_custom.ignore_waypoints ) {
        if ( $et_pb_jt_counter.length ) {
          $et_pb_jt_counter.each(function(){
            var $this_counter = $(this);

            et_waypoint( $this_counter, {
              offset: '75%',
              handler: function() {
                jt_update_counter($this_counter);
              }
            });

            et_waypoint( $this_counter, {
              offset: 'bottom-in-view',
              handler: function() {
                jt_update_counter($this_counter);
              }
            });
          });
        }

        function jt_update_counter($counter) {
          var counter_type    = $counter.data('counter-type') ? $counter.data('counter-type') : 'number';
          if ( 'number' === counter_type ) {
            $counter.data('easyPieChart').update( 100 );
          } else if ( 'circle' === counter_type ) {
            var circle_percent      = $counter.data('circle-percent') ? $counter.data('circle-percent') : 100;
            var count_to        = $counter.data('count-to') ? $counter.data('count-to') : 0;
            $counter.data('easyPieChart').update( circle_percent );
          }
        }

        function et_waypoint( $element, options ) {
          if ( ! $element.data( 'et_waypoint' ) ) {
            var instances = $element.waypoint( options );

            if ( instances && instances.length > 0 ) {
              $element.data( 'et_waypoint', instances[0] );
            }
          } else {
            // Reinit existing
            $element.data( 'et_waypoint' ).context.refresh();
          }
        }

      } else {
        // alert("das ist nicht so gut, jaa?");
      }
    }

    if ( window.et_load_event_fired ) {
      // alert("window.et_load_event_fired");
      window.et_pb_jt_counter_init();
    } else {
      $(window).load(function(){
        // alert("window.et_load_event_fired false. $(window).load() fired.");
        window.et_pb_jt_counter_init();
      }); // End $(window).load()
    }

  }); //End of $(document).ready()

} )( jQuery );
