(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        var _this = this,
            loopCount = 0,
            value = 0,
            increment = 0,
            loops = Math.ceil(options.speed / options.refreshInterval),
            interval = setInterval(updateTimer, options.refreshInterval);

        updateCounter();

        function updateTimer() {
            value += increment;
            loopCount++;
            $(_this).html(addCommas(value.toFixed(0)));

            if (loopCount >= loops) {
              value = options.to;
              updateCounter();
            }
        }

        function updateCounter() {
          options.from = value;
          loopCount = 0;

          query = {unit: options.unit};
          if(options.program_id != 0) {
            query.program = options.program_id;
          }

          if(options.date_from != 0 && options.date_to != 0) {
            query.from = options.date_from;
            query.to = options.date_to;
          }

          $.ajax({
            url: options.url,
            data: query,
            type: 'GET',
            dataType: 'jsonp',
            success: function(response) {
                    options.to = response.data;
                    
                    // first load
                    if(options.from == 0) {
                      options.from = options.to;
                      value = options.from;
                    }

                    increment = (options.to - options.from) / loops;
                  }
          });


        }

        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;
        }

    };

    $.fn.countTo.defaults = {
        url: 'http://secure.tomypath.com/generic/stats/all',
        program_id: 0,
        date_from: 0,
        date_to: 0,
        unit: 'steps',
        speed: 30000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        from: 0
    };
})(jQuery);
