/*	Tim Wood & Steve Stoft - December 15, 2006
	Displays cumulative CO2 emissions in or without an iFrame.  Help = zfacts.com/p/640.html
*/
// modify when changing location of this gizmo. Contains all location/time sensitive values. '<==Data/' is a marker for progAct/gizDatUp.PHP
function locate_16(what) {			
	var co2when = "2007:01:00";	//<==Data. Updated periodically by zFacts. Starting time. Interpretted as Washington DC time.
	var co2 = 2580000000000;		//<==Data. Updated. Starting amount. Tonnes of CO2
	var co2ps = 1240;					//<==Data. Updated. Rate of Change in tonnes/sec
	switch (what) {
		case	'gizSite':	return 'metapager.com/';
		case	'udatProg':	return 'zfacts.com/giz/udat/rec.php';
		case	'gizName':	return 'G16co2';			// '&' not allowed in name
		case	'co2when':	return co2when;
		case	'co2':	return co2;
		case	'co2ps':	return co2ps;
	}		
}
// <a rel="year;US;cps=8;u=tons;iFrame;color=red;size=16;bold;font=times,roman" id="zF16" href="http://zfacts.com/p/396.html">energy policy</a> 
// <script type="text/javascript" src="http://zfacts.com/giz/G16co2.js"></script>
// Parameter	Default	Meaning and range of values
// Name			Value
// year					Count from Jan. 1. (present/absent)
// US						Just US emissions. (presnet/abslent)
// cps			5			clicks per second: 0.01 -- 100
// u				pounds	units: tons, kg, tonnes
// iFrame					put in an iFrame, (presnet/abslent).
// color		black		font color: #HHH, red, green ...
// size			14			font-size in pixels: 10 -- 50
// bold						font-weight no value, (presnet/abslent)
// font			arial,sans-serif			font-family

startAll();
function startAll() {
	my = startAll;
// --------------------------------------------------------- Setting of unique Gizmo #s, and clockSite definition ===== START
	var c, IDn, ID = 'zF16';
	if (typeof(my.i) == 'undefined') my.i = 0; else my.i++;			// static loop counter, for testing ID sequence
	c='.'+my.i; if (my.i==0) c=''; IDn = ID+c;		// IDn = zF16, zF16.1, zF16.2, ...
	var zLink = document.getElementById(IDn);			// User link to zFacts. If link found try starting clock. 
	if (zLink != null) start_16(IDn);					// startAll() will be called again by by ticker.js after this clock is running.
	else if (my.i<5) startAll();							// If ID missing, try another, up throug zF16.4
}
function nowCallTickLoop_16()	{ tickLoop_16("start_16"); } 			// called from ticker.js to be sure tickLoop() is loaded.
function start_16(ID) {
	var Site = locate_16('gizSite');			// <== Site. Just change this to switch sites, eg metapager to zFacts
	var clockSite = Site + "giz/G16/";		// Controls which site it's for. Used here and in link at bottom of clock.html
	var my = start_16;							// Used to make static variables
//	All Giz #s from here on are in function names and preceded by an '_', eg, _16.  Check also in ticker.js and clock.html 
// --------------------------------------------------------- zFacts CO2 Parameters =================== Start
	var defaults = "year=0; US=0; cps=5; u=pounds; iFrame=0; color=black; size=14; bold=0; width=0; height=0; font=arial,sans-serif";
	var co2when = locate_16('co2when');
	var co2		= locate_16('co2');
	var co2ps	= locate_16('co2ps');
	var rPage="http://zfacts.com/p/396.html";	// required link page
	var hPage="http://zfacts.com/p/640.html";	// help page for gizmo
	var iFhtmURL	= 'http://' +clockSite+ 'clock.html';	//	contents of iFrame
	var tickerURL	= 'http://' +clockSite+ 'ticker.js';	// clock mecanism
	var keyWord = 'energy policy';
	if ( ! valid_16(ID, rPage, hPage, keyWord, Site) )	return;		// check for z-link
// --------------------------------------------------------- zFacts CO2 Parameters =================== End
	var zLink = document.getElementById(ID);			// User link to zFact
	var now = (new Date ())/1000; // in seconds
	var co2start	= co2 + co2ps*(now - str2date_16(co2when)); 		// Date/1000 = secs from 1970
// --------------------------------------------------------- USER CO2 Parameters =================== Start
	var year, US, cps, u, iFrame, fColor, fSize, fBold, fWidth, fHeight, fFamily;		// User Parameters
	var paramList, uv, nChars;
	loadPrams_16(defaults);						// load parameter default values into pram_16().
	paramList = zLink.getAttribute("rel");
	if ( typeof(paramList)!='undefined' && paramList && (paramList.length > 2) )
		loadPrams_16(paramList);				// load user parameters. Stores them in pram_16().
	year	= pram_16('get', 'year');
	US			= pram_16('get', 'US');
	cps		= pram_16('get', 'cps');		cps = Math.max(.01,Math.min(40,cps*1));
	u 			= pram_16('get', 'u');			uv = 2000; nChars=15;
	iFrame	= pram_16('get', 'iFrame');
	fSize		= pram_16('get', 'size');		// takes default or user value for size, puts it into fSize
	fColor	= pram_16('get', 'color');
	fBold		= pram_16('get', 'bold');
	fWidth	= pram_16('get', 'width');
	fHeight	= pram_16('get', 'height');
	fFamily	= pram_16('get', 'font');
	if (u=='tons')		{ uv = 1.10231;	nChars = 15; }		// characters in # counting commas as 1/2
	if (u=='pounds')	{ uv = 2204.62;	nChars = 18.5; }	// 'pounds' included just in case they use it. not needed
	if (u=='kg')		{ uv = 1000;		nChars = 18.5; }  // nChars tells width of # to help set iFrame width
	if (u=='tonnes')	{ uv = 1;			nChars = 15; }
	if (year=='1')	nChars = nChars-2.5;
// --------------------------------------------------------- USER CO2 Parameters =================== End
	var startVal	= uv * co2start;
	var rate			= uv * co2ps;
	if (year!='0') {
		var y0 = str2date_16("2006:01:00");
		while (now-y0 > 365*24*3600) y0 += 365*24*3600;
		startVal = rate * (now - y0);
	}
	if (fWidth=='0')	fWidth	= Math.floor(0.58 * fSize * nChars + 4);		// If user does not set a value
	if (fHeight=='0')	fHeight	= Math.floor(1 * fSize + 3);		// set automatically
// ========================================================= Form HERE on Everything should be Generic, good for all clocks
// --------------------------------------------------------- Ticker values for no-iFrame use
	my.tickerVals = new Array(ID, startVal, rate, cps);
// --------------------------------------------------------- Ticker values and format values for iFrames
	var QSnames = new Array('clockSite', 'ID', 'startVal', 'rate', 'cps', 'fSize', 'fColor', 'fBold', 'fFamily');
	var QS='', name, val;
	for (j=0; j<QSnames.length; j++) {			// build QS to pass to cclock.html for iFrame
		name	= QSnames[j];
		val	= eval(name);
		QS = QS + name + '=' + val + '&';
	}
	QS = '?' + escape(QS);
// -------------------------------------------------------- Ticker values for iFrames == End
		var outerSpan = document.createElement('span');			// build outer span tag
		outerSpan.style.margin="0px";
		outerSpan.style.padding="0px";
		zLink.parentNode.replaceChild(outerSpan, zLink);		// replace zLink with outer span. iFrame or clockSpan will go inside
// -------------------------------------------------------- Choose iFrame or No-iFream
	if (iFrame!='0') {
		var iF = '<iframe id="' +ID+ '" allowTransparency="True" width="' + fWidth + 'px" height="' + fHeight + 'px" src="' + iFhtmURL + QS + '" frameborder="0" align="top" marginheight="0" marginwidth="0" scrolling="no"></iframe>';
		outerSpan.innerHTML = iF;
		startAll();															// Cannot be called from ticker for iFrames. Checks for another instance of this gizmod
	} else {
		var clockSpan = '<span id="' +ID+ '">#</span>';			// build ID'ed inner span to contain clock
		outerSpan.innerHTML = clockSpan;								// Put clockSpan into Outerspan, which has replaced the user's zLink.
		if (typeof(my.loaded)=='undefined') {
			my.loaded = 1;
			var script = document.createElement('script');			// Create script that will call co2_ticker.js
			script.src = tickerURL;											// URL for JS for clock counter
			script.type = 'text/javascript';				
			var head = document.getElementsByTagName('head').item(0);
			head.appendChild(script);										// Puts the JS scrip into document head, which calls its source php file.
		}
		else  nowCallTickLoop_16();									// indirect call just keeps gizmo name up top where it's visible and not forgotten.
	}
}
function loadPrams_16(pString) {		// takes parameter value from default & user lists and stores them in pram_16();
	var params, peqv, pram, val;		// var names are made case insensitive by pram()
	params = pString.replace(/ /g, '').split(';');	// remove blanks then split on commas
	for (var i=0; i<params.length; i++)	{
		peqv = params[i].split('=');
		pram=peqv[0];
		if (peqv.length==1 || peqv[1]=='')	val = '1'; 			// if no value, value = '1' (testing for undefined does not work)
		else 											val = peqv[1]; 
		pram_16('set', pram, val);							// set pram to val
	}	
}
function pram_16(which, name, val) {			// which = get | set
	var my = pram_16;									// set => name = val.  get => return stored value or val=supplied_default_value
	name = name.toLowerCase();
	if (which=='set')
		eval( 'my.' +name+ '="' +val+ '";' );		// set name = "val";
	else	{
		return eval( 'my.' +name );		// get val of name
	}
}
function str2date_16(str)			// converts 'y:m:d:h:m:s' to (y, m, d, h, m, s) and then to seconds since 1970 GMT
{ var ndx, s0, s = str;				// Less significant parts can be dropped, but sting must not end with ':'
  var dA = new Array(7);			// 2004:4 is the beggining of March 31. 2004:4:1 is the beginning of April 1.
  for (i=1; i<7; i++)				// off gives GMT offset in hours from local str time. DC is 4 (daylight) or 5 (winter)
  { 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; 	// + off;		Offset hours not used, parameter removed
  return (Date.UTC(dA[1], dA[2], dA[3], dA[4], dA[5], dA[6]))/1000	// date in secs since 1970
}
function valid_16(ID, rPage, hPage, keyWord, Site) {
	var zLink, linked, oops = 'ok';
	zLink = document.getElementById(ID);
	if ( zLink == null ) {
 		alert('Need id=' +ID+ ' in Link to ' +rPage+ '\nSee ' +hPage+ ' for Help.');
		return 0;
	}
	if ( zLink.getAttribute("href") != rPage ) oops = 1;			// no proper link
	linked = zLink.innerHTML;
	if ( linked.toLowerCase().indexOf(keyWord) < 0 ) oops = 2;
	if ( zLink.nodeName != 'A' ) oops = 3;

	if (oops == 'ok')		{ udat_16(); return 1; }
	if (oops == 2)	alert('Must link keywords: "' +keyWord+ '" in link with id=' +ID);	
	else alert('Need Link to ' +rPage+ ' in link with id=' +ID+ '\nSee ' +hPage+ ' for Help.');
	return 0;
}
function udat_16() {
//	var file = 'http://zfacts.com/giz/udat/rec.php?gizName=G16';
	var file = 'http://' +locate_16('udatProg')+ '?gizName=' + locate_16('gizName');
	var script = document.createElement('script');
	script.src = file + '&domain=' +document.domain+ '&location=' +document.location;
	script.type = 'text/javascript';				
	document.getElementsByTagName('head').item(0).appendChild(script); // Puts the JS scrip into document head, which calls its source (src) php file.
}