/*
 * Nathan Reed, 20/09/08
 */
 
var CountUi = {
	init: function() {
		var minRate = 70;

		this.targetList = [
			{'target': 0, 'remaining':0, 'element':'cd-tweet-timer-1'},
			{'target': 0, 'remaining':0, 'element':'cd-tweet-timer-2'},
			{'target': 0, 'remaining':0, 'element':'cd-tweet-timer-3'}, 
			{'target': 0, 'remaining':0, 'element':'cd-tweet-timer-4'}
		];
		
		// tweet starting num, using the age of the data, and the current rate
		// we can estemate how many tweets to offest by
		this.tweetId = _cur_tweet + Math.round((_age*1000)/_cur_rate);
		
	
		// update the count by tweetfactor this much ever tweetdelay ms
		this.tweetFactor = Math.ceil(minRate/_cur_rate);
		this.tweetDelay  = Math.round(_cur_rate*this.tweetFactor);

		// loop through the target list, set the time remaining.
		var baseMagnitude = 10000000;
		var curMagnitude = baseMagnitude;
		for(var i=0; i < this.targetList.length; i++) {
			var curTarget = this.targetList[i];
			
			curTarget.target = this.generateTarget(this.tweetId, curMagnitude);
			curTarget.remaining = this.timeRemaining(curTarget.target);
			
			// also set the target element
			var timerElement = document.getElementById(curTarget.element+'-t');
			if(timerElement != null) {
				timerElement.innerHTML = addCommas(curTarget.target);
			}
			
			curMagnitude *= 10;
		} 
	
		setInterval("CountUi.updateCounter();", this.tweetDelay);
		setInterval("CountUi.updateTimer();", 1000);
		
		// update the timer now, so there is no delay
		CountUi.updateTimer();
	},
	
	updateCounter: function() {
		document.getElementById('cd-tweet-counter').innerHTML = addCommas(this.tweetId);
		this.tweetId+=this.tweetFactor;		
	},
	
	updateTimer: function() {
		// de-increment each timer. we have to hope that the setTimeout function is
		// accurate in terms of time...
		for(var i=0; i < this.targetList.length; i++) {
			var curTarget = this.targetList[i];
			curTarget.remaining--;
			
			//update the element as well, if it exists
			var timerElement = document.getElementById(curTarget.element);
			if(timerElement != null) {
				timerElement.innerHTML = longDateStr(curTarget.remaining);
			}
			
		} 

	},
	
	timeRemaining: function(targetTweet) {
		var shortRateThreshold = 6*3600;
		var timeLeft = Math.round(((targetTweet-this.tweetId) * _avg_rate)/1000);
		
		// is there less than 6 hrs remaining? Then use the short range rate. 
		// it will be more accurate
		if(timeLeft < shortRateThreshold) {
			timeLeft = Math.round(((targetTweet-this.tweetId) * _cur_rate)/1000);
		}
		
		return timeLeft;
	},
	
	generateTarget: function(curTweet, magnitude) {
		return Math.ceil(curTweet / magnitude) * magnitude;
	}	
		
}

/* from http://www.mredkj.com/javascript/nfbasic.html */
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;
}

// gets the long duration string from duration. duration has the number
// or seconds, and longDateStr returns something like 2 days 4 hours 5 minutes
function longDateStr(duration)
{
	
	MAX_UNITS = 3;
	var datestr = '';

	// time consts
	second = 1;
	minute = 60;
	hour = minute*60;
	day = hour*24;
	week = day*7;
	month = day*31;
	year = day*365;

	var timeconst = {
		len: [
			//year,
			//week,
			//month,
			day,
			hour,
			minute,
			second
		], 
		name: [
			//"year",
			//"week",
			//"month",
			" day",
			":",
			":",
			""			
		]
	};
	
	unitcount = 0; // count of the number of diff units used so far.
	for(i=0; i < timeconst.len.length; i++) {
		if(duration >= timeconst.len[i]) {
			unitcount++;

			curtime = Math.floor(duration/timeconst.len[i]);
			
			// add a leading zero to the time stuff
			if(timeconst.name[i].length <= 1 && curtime < 10) {
				curtime = ('0'+curtime);
			}
			
			datestr += (curtime+timeconst.name[i]);
			duration -= (curtime*timeconst.len[i]);

			// does date string need a plural
			if(timeconst.name[i] == " day") {
				if(curtime > 1) {
					datestr += 's ';
				} else {
					datestr += ' ';
				}
			}
			

			// too many units?
			//if(unitcount >= MAX_UNITS) {
			//	break;
			//}

		} else {
			if(timeconst.name[i] != " day") {
				datestr += ('00'+timeconst.name[i]);
			}
		}
	}

	return datestr;
}
