// Set counter parameter defaults
var additionalActions = 2472931;
var msecToActionTotal = 3000;
var startActionTotal = 2000000;
// ******************************

jQuery(document).ready(function(){

	if (jQuery('#actionCount2').length > 0) {

		var actions = 0;
		var interval;
		var incrementBy;

		//Load the live counter
		jQuery.get('http://www.38degrees.org.uk/utils/cons_counter/signup_counter.ajax.php', function(data, status){
			jQuery('#actionCount2').removeClass('loading');
			//Add manual actions that aren't included in the total count automatically
			actions = parseInt(data) + additionalActions;
			//Calculate the value by which the counter increments with each 'tick',
			//such that the counter hits the final target roughly within the time defined by 'msecToActionTotal'
			incrementBy = parseInt((actions-startActionTotal)/(msecToActionTotal/10));

			if (actions < startActionTotal) {
				startActionTotal = actions;
			}

			var i = startActionTotal;
			interval = setInterval(function(){
				//If we've overshot, just set the value to the final target and stop the ticker
				if (i > Math.round(actions/incrementBy)*incrementBy) {
					jQuery('#actionCount2 span').html(commarise(actions));
					clearInterval(interval);
				//Otherwise increment by one tick
				} else {
					i += incrementBy;
					jQuery('#actionCount2 span').html(commarise(i));
				}
			}, 10);

		});

	}
});

function commarise(nStr) {
	// Returns the 'number' nStr formatted with comma separators
	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;
}