window.addEventListener("load", initializeTable, false);

var g_totals;
var g_startColumn = 1;  // first col is not number.
var g_numColumns;
var g_totalRowCells;

// Redo totals.
function populateTotalRow()
{
  for(i = g_startColumn; i < g_numColumns; i++)
  {
    g_totalRowCells[i].replaceChild(document.createTextNode(g_totals[i]), g_totalRowCells[i].firstChild);
  }
}

// Called once on load.  Gets column totals.  Sets up
// event handlers for row toggling.
function initializeTable()
{
  var table = document.getElementById("t");
  var rows = table.rows;

  g_numColumns = rows[0].cells.length;
  g_totals = new Array(g_numColumns);
  g_totalRowCells = document.getElementById("totalrow").cells;

  for(i = g_startColumn; i < g_numColumns; i++)
  {
    g_totals[i] = 0;
  }

  for(i = 0; i < rows.length; i++)
  {
    var row = rows[i];
    if(row.className.indexOf("notdata") == -1)
    {
      // This is a row with data to sum up.

      // Starts off included in total.
      row.on = true;

      var cells = row.cells;
      for(j = g_startColumn; j < g_numColumns; j++)
      {
        var thisCell = cells[j];

        // Set up ability to click this row (via these cells only)
        // to invoke the toggle.
        thisCell.style.cursor = "pointer";
        thisCell.onclick = togglerow;

        // Add these cells' values to our totals.
        var value = parseInt(thisCell.firstChild.nodeValue);
        if(!isNaN(value))
        {
          g_totals[j] += parseInt(value);
        }
      }
    }
  }

  populateTotalRow();
}

function deductFromTotals(cells)
{
  for(i = g_startColumn; i < g_numColumns; i++)
  {
    var value = parseInt(cells[i].firstChild.nodeValue);
    if(!isNaN(value))
    {
      g_totals[i] -= value;
    }
  }
}

function addToTotals(cells)
{
  for(i = g_startColumn; i < g_numColumns; i++)
  {
    var value = parseInt(cells[i].firstChild.nodeValue);
    if(!isNaN(value))
    {
      g_totals[i] += value;
    }
  }
}

// Handler to include/exclude a row's values in the total.
function togglerow()
{
  // "this" will be a cell in the row of interest.
  var row = this.parentNode;

  if(row.on)
  {
    row.style.color = "#ccc";
    // Style the link also.
    row.cells[0].firstChild.style.color = "#aaa";
    row.on = false;
    deductFromTotals(row.cells);
  }
  else
  {
    row.style.color = "black";
    row.cells[0].firstChild.style.color = "#585";
    row.on = true;
    addToTotals(row.cells);
  }

  populateTotalRow();
}
