/*

US Debt Clock

Put the following <span> where you want the clock to display:

	$<span id="debt-clock"></span>

Then call this javascript function after the page loads:

	startDebtClock(CPS) //where CPS is the update rate (between .1 and 100; 8 is about right)

*/

// The following three vars need to be updated periodically...
// Data source: http://www.treasurydirect.gov/NP/BPDLogin?application=np
var GNDwhen	= "2010:06:22:00";		// Start time (in Washington DC time)
var GND		= 13088552647591.81;    // Start amount
var GNDrate = 1623;					// Change in $ billion / year

var GMT_offset	= 4; // GMT offset from DC time, 5 winter, 4 summer
var timeStart	= (new Date ())/1000; // Returns # of secs between 1970 GMT (=UTC) and JavaSript (client) start time
var GNDps 		= GNDrate*1000000000/(365*24*60*60);
var GNDstart	= GND + GNDps*(timeStart - str2date(GNDwhen,GMT_offset));

function startDebtClock(CPS) {

	 // param: CPS - clicks per sec, try 8
	 
	if (CPS < 0.1)
		cps05 = CPS;
	else if (CPS > 100)
		cps05 = 100;
	else
		cps05 = CPS;

	updateClock();
	
}

function updateClock() {
	var secs = (new Date ())/1000 - timeStart;
	document.getElementById('debt-clock').innerHTML = num2strC(GNDstart + GNDps*secs);
	setTimeout('updateClock();', 1000/cps05);
	}

function str2date(str,GMT_offset) {

	/*
	
	Converts 'y:m:d:h:m:s' to (y, m, d, h, m, s) and then to seconds since 1970 GMT
	Less significant parts can be dropped, but sting must not end with ':'
	2004:4 is the beggining of March 31.
	2004:4:1 is the beginning of April 1.
	GMT_offset gives GMT offset in hours from local str time. DC is 4 (daylight) or 5 (winter)
	
	*/

	var s = str;
	var dA = new Array(7);
	
	for (i=1; i<7; i++) {
		if (s.length) {
			ndx = s.indexOf(':');
			if (ndx==-1)
				{
				s0 = s;
				s = '';
				}
			else
				s0 = s.substring(0, ndx);
			}
		else
			s0 = 0;
			
		if (i==2) s0 -= 1;  // Months go from 0 to 11 in JS
		
		dA[i] = s0;
		s = s.substring(ndx+1);
	
	}
	
	dA[4] =dA[4]*1 + GMT_offset;
	
	return (Date.UTC(dA[1], dA[2], dA[3], dA[4], dA[5], dA[6]))/1000	// date in secs since 1970

}

function num2strC(xNum) {

	// convert xNum to a string with commas, in style N
	
	var sign = "";
	
	if (xNum < 0) {
		xNum = -xNum;
		sign = "-";
		}			// conver to positve and save sign
		
	xDols = Math.floor(xNum); // xF is the "dollar" value
	
	var sDols = xDols.toString ();
	
	DLen = sDols.length;
	
	dCom = "";
	
	while (DLen > 3){
		digits3 = sDols.substr(DLen-3, 3);  // take last 3 digits.
		sDols = sDols.substr(0, DLen-3);  // take all but last 3 digits.
	 	DLen = DLen -3;
	 	dCom = "," + digits3 + dCom;
		}
		
	dCom = sDols + dCom;
	return sign + dCom;
	
}