/*                 ---------- EnergyCounter.js ----------
 * HTML Output Looks Like:
 * 
 * Energy Consumption Count since <epoch>
 * Current Time: <time>
 *        World: <number>
 *      US Only: <number>
 * 
 * Conceptualized by: Joe Loper & Rahul Walawalkar
 * Source Code Author: Rajesh Deo 
 * Developed for Alliance to Save Energy, Washington, DC
 * December 2002
 *
 * Function roundOff() taken from DevEdge Examples
 * http://developer.netscape.com/docs/examples/javascript/rounding.html
 *                -----------------------------------------
 */

function counter() {
  /* Data Constants */
  rate_yr_world = 69641379310;
  rate_yr_us = 6752500000;
  
  growth_rate_sec_world = rate_yr_world/(365.*24.*60.*60.);
  growth_rate_sec_us = rate_yr_us/(365.*24.*60.*60.);

  // Total consumption on a known epoch.
  epoch = "January 1, 2003";
  epoch_consump_us = 0.0;
  epoch_consump_world = 0.0;
  
  // get number of msec since Jan. 1, 1970
  epochObj = new Date(epoch);
  epoch_ms = epochObj.getTime();
  now = new Date();
  now_str = now.toString();
  now_ms = now.getTime();
  
  // test for future time and overflow
  //now_ms = epoch_ms + (now_ms - epoch_ms)*2;
  //tmp_date = new Date(now_ms);
  //alert(tmp_date.toString());

  // this will be in seconds
  timegap = Math.round((now_ms - epoch_ms)/1000.0);
  
  // this assumes a constant growth rate
  increase_world = timegap * growth_rate_sec_world;
  increase_us = timegap * growth_rate_sec_us;
  
  new_consump_world = epoch_consump_world + roundOff(increase_world, 2);
  new_consump_us = epoch_consump_us + roundOff(increase_us, 2);
  
  // Form output HTML
  output = "<p><font size='2' face='Arial, Helvetica, sans-serif'><em>World Energy Consumption Since "+ epoch + " </em></font></p>";
  output += "<p><font size='5' face='Arial, Helvetica, sans-serif' color='#003399'><strong>"  + new_consump_world + " </strong></font><font size='3' face='Arial, Helvetica, sans-serif' color='#003399'>Oil Barrels Equiv.</p>";
  obj_handle = document.getElementById("counter");
  obj_handle.innerHTML = output;
  
  // call us every 2 seconds
  newtime = window.setTimeout("counter();", 2000);
}
function roundOff(value, precision)
{
  value = "" + value; //convert value to string
  precision = parseInt(precision);
  var whole = "" + Math.round(value * Math.pow(10, precision));
  var decPoint = whole.length - precision;
  if(decPoint != 0) {
    result = whole.substring(0, decPoint);
    result += ".";
    result += whole.substring(decPoint, whole.length);
  }
  else {
    result = whole;
  }
  return result;
}
// start counter
counter();
