// JavaScript Document for Homework 3, INP271, Mike Behnke

window.onload = finishTable;

// Global Variables
var theTable;

function finishTable() {
	// Object detection
	if (!document.getElementById && !document.getElementsByTagName) {return;}

	// Write the TFoot
	theTable = document.getElementById('study1');
	createTfoot();

	// Highlight the cells when moused over
	var highlightCells = theTable.getElementsByTagName('td');
	var numCells = highlightCells.length;
	for (var h = 0; h < numCells; h++) {
	  highlightCells[h].onmouseover = highlightTheCells;
	  highlightCells[h].onmouseout = unhighlightTheCells;
	}
}

function createTfoot() {
	// This function inserts the tfoot section of the table for study data 1
	var tableBody = theTable.getElementsByTagName('tbody')[0];
	var tableFoot = document.createElement('tfoot');
	
	// Populate tfoot prior to creation so it is all inserted together
	var tfootRow = document.createElement('tr');
	var tfootTH = document.createElement('th');
	
	// Get total number of cols and rows not including header rows
	var totalCols = theTable.rows[0].cells.length - 1;
	var totalRows = theTable.rows.length - theTable.tHead.rows.length;
	
	// Create Empty variables for use in loops
	var cellTotal = new Array(), 
			cellAverage = new Array(), 
			tdElement,
			i, j;
	
	// Create Label for bottom row
	tfootTH.appendChild(document.createTextNode('Mean'));
	tfootTH.scope = 'row';
	tfootRow.appendChild(tfootTH);
	
	// Add Averages - loop to pick up all values
	for (i = 1; i <= totalCols; i++) {
		cellTotal[i] = 0;
		cellAverage[i] = 0;
		for (j = 1; j <= totalRows; j++) {
			cellTotal[i] += theTable.rows[j].cells[i].firstChild.data - 0;
		}
		cellAverage[i] = cellTotal[i]/(j-1);
		
		// Fix cell to 2 decimals
		if (cellAverage[i].toFixed) {cellAverage[i] = cellAverage[i].toFixed(2)}
		
		// Create TDs and append average as TextNode
		tdElement = document.createElement('td');
		tdElement.appendChild(document.createTextNode(cellAverage[i]));
		tfootRow.appendChild(tdElement);
	}
			
	tableFoot.appendChild(tfootRow);
	// Insert tfoot in proper place
	theTable.insertBefore(tableFoot,tableBody);	
}

function highlightTheCells() {
	var theCell = this.cellIndex;
	var theRow = this.parentNode.rowIndex;
	var rowHeader = theTable.rows[theRow].cells[0];
	var colHeader = theTable.rows[0].cells[theCell];
	var cellTitle = rowHeader.firstChild.data + ', ' + colHeader.firstChild.data;
	
	// Apply Hover Styles and 
	this.className = rowHeader.className = colHeader.className = 'jshover';	
	this.title = cellTitle;
}

function unhighlightTheCells() {
	var theCell = this.cellIndex;
	var theRow = this.parentNode.rowIndex;
	var rowHeader = theTable.rows[theRow].cells[0];
	var colHeader = theTable.rows[0].cells[theCell];
	
	this.className = rowHeader.className = colHeader.className = '';
	this.title = '';
}
