var mc1 = new MentionsCounter('mentionsCounter','mentionsFound');
var mc2 = new MentionsCounter('campaignCounter','campaignFound');

function MentionsCounter(id,type) {
	var mc = this;
	mc.id = id;
	mc.type = type;
	mc.num = 0;
	mc.max = 0;
	mc.timerId;
	mc.plus = 1;
	mc.timeout = 0;
	mc.firstAjax = true;
	mc.ajaxCounterTimer;
	mc.showCounter = function() {
		$('#'+mc.id).html(mc.addCommas(mc.num));
	}
	mc.getSumm = function(nnm, nnm2) {
		var rand;
		
		if (nnm2 < 10) { rand = nnm + 1; } 
		else if (nnm2 < 100) { rand = nnm + Math.floor((Math.random() * 9) + 1); } 
		else if (nnm2 < 1000) { rand = nnm + Math.floor((Math.random() * 91) + 10); } 
		else if (nnm2 < 10000) { rand = nnm + Math.floor((Math.random() * 901) + 100); } 
		else if (nnm2 < 100000) { rand = nnm + Math.floor((Math.random() * 2001) + 1000); } 
		else if (nnm2 < 1000000) { rand = nnm + Math.floor((Math.random() * 10001) + 1000); } 
		else if (nnm2 <= 100000000) { rand = nnm + Math.floor((Math.random() * 100000) + 10000); } 
		else { rand = nnm + Math.floor((Math.random() * 1000000) + 10000000); }
		
		timeout = 0; 
		
		return rand;
	}
	mc.startCounter = function() {
		var rand;
		if (mc.timerId) { clearTimeout(mc.timerId); }
		if (mc.num < mc.max) { 
			mc.showCounter(); rand = mc.getSumm(mc.num, mc.max);
			
			if (rand > mc.max) { var num2 = mc.max - mc.num; mc.num = mc.getSumm(mc.num, num2); } 
			else { mc.num = rand; }
			
			mc.timerId = setTimeout(mc.startCounter, timeout);
		} 
		else if (mc.firstAjax) { mc.ajaxCounter(); }
	}
	mc.addCommas = function(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;
	}
	mc.ajaxCounter = function() {
		if (mc.ajaxCounterTimer) { clearTimeout(mc.ajaxCounterTimer); }
		$.ajax( {
			url : '/ajaxmentions',
			dataType : 'json',
			type : 'POST',
			data : { type : mc.type },
			success : function(json) {
				if (json) { mc.max = json.total; }
				
				mc.firstAjax = false;
				mc.startCounter();
				mc.ajaxCounterTimer = setTimeout(mc.ajaxCounter, 2000);
			}
		});
	};
	
	return mc;
}
