var UPDATE_RATE = 10; //get msg-count.txt from server every 10 seconds
var REFRESH_RATE = 250; //milliseconds (update counters every half a minute)

$("document").ready(function() {
   var msg_counter = new Counter("msg-count", '<!--#include virtual="/msg-count.txt" -->');
});


function Counter(render_to, init_values)
{
  var _this = this;

  this.render_to = render_to;

  this.set_update(init_values);
  window.setInterval(function() {
    $.get('msg-count.txt?nocache=' + Math.random(), function(data) {
      _this.set_update(data);
    });
  }, UPDATE_RATE * 1000); //milliseconds

  window.setInterval(function(){_this.increment();}, REFRESH_RATE);
}

Counter.prototype = {

  increment: function() {
    this.delta += this.speed;
    var count = this.start  + Math.ceil(this.delta);
    if (count > this.end) count = this.end;

    $("#counters").css("display", isNaN(count) ? "none" : "block");

    $("#" + this.render_to).html(this.format(count));
  },

  set_update: function(counters_txt) 
  {
    var counts = counters_txt.split(",");
    var start = parseInt(counts[0]);
    var end = parseInt(counts[1]);
  
    if (isNaN(start) || isNaN(end) || end < start) { //invalid or absent counters file on server
      this.speed = 0;
      return;
    }

    if (this.end == end) { //counters weren't updated
      start = end; //don't re-count last delta
    }

    this.start = start;
    this.end  = end;
    var ips = (this.end - this.start) / (UPDATE_RATE + 2); // + 2 seconds for request
    this.speed = ips * REFRESH_RATE / 1000;
    this.delta = 0;
  },

  format: function(num) {
    num += ''; //make it strval
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(num)) {
      num = num.replace(rgx, '$1' + ',' + '$2');
    }
    return num;
  }
};