var ec = {
  timer: null,
  quantity: null,
  watts: null,
  milliamps: null
};

Event.observe(window, 'load', init_energy_calculator);

function init_energy_calculator()
{
  Event.observe($('ec_quantity'), 'keyup', ec_quantity_changed);
}

function ec_quantity_changed()
{
  if (ec.timer)
  {
    clearTimeout(ec.timer);
    ec.timer = null;
  }
  
  ec.timer = setTimeout(ec_do_calculate, 500);
}

function ec_do_calculate()
{
  var newQuantity = parseInt($F('ec_quantity'));
  
  if (ec.quantity == newQuantity) return;
  
  ec.quantity = newQuantity;
  
  if (ec.quantity && ec.quantity < 0) ec.quantity = 0;
  
  if (ec.quantity)
  {
    $('ec_quantity').value = ec.quantity;
    
    if (!$('ec_calculations_container').visible())
    {
      ec_update_calculations();
      new Effect.Appear('ec_calculations_container', {duration:.2});
    }
    else
    {
      new Effect.Fade('ec_calculations_container', {duration:.2, afterFinish: function()
      {
        ec_update_calculations();
        new Effect.Appear('ec_calculations_container', {duration:.2});
      }});
    }
  }
  else
  {
    if ($('ec_calculations_container').visible())
    {
      new Effect.Fade('ec_calculations_container', {duration:.2});
    }
  }
}

function ec_update_calculations()
{
  if (!ec.quantity) return;
  
  $('ec_quantity_display').update(ec.quantity);
  
  var watts = ec.watts * ec.quantity;
  $('ec_calculation_watts').update(dp2(watts));
  
  var amps = ec.milliamps * ec.quantity / 1000;
  $('ec_calculation_amps').update(dp2(amps));
  
  var totalWatts = watts * 1.1;
  $('ec_calculation_total_watts').update(dp2(totalWatts));
  
  var totalAmps = amps * 1.1;
  $('ec_calculation_total_amps').update(dp2(totalAmps));
}

function dp2(num) {
  return Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);
}