// After the page loads, create the multiplication table (1 to 12).
window.onload = function()
{
	createNewTable(12);
}

function createNewTable(maxNum)
{
	// Define and intialize the variables.
	var tbl, tr, td, hasError = false;
	
	// Do error checking on maxNum.
	if(isNaN(maxNum) || maxNum == "")
		hasError = true;
	else
	{
		maxNum = parseInt(maxNum);
		if(maxNum < 1 || maxNum > 16)
			hasError = true;
	}
	// If an error occurred, show the message, set the focus back to the text box,
	// and don't continue.
	if(hasError)
	{
		alert("You must enter an integer that is greater than or equal to 1 and less than or equal to 16 as the maximum.");
		gE("txtMaxNum").select();
		return;
	}

	// Create the table.
	tbl	= document.createElement("TABLE");
	// Remove any children of divTable.
	gE("divTable").innerHTML = "";
	// Insert the table into divTable.
	gE("divTable").appendChild(tbl);
	
	// Set the style of the table.
	tbl.border = 1;
	tbl.cellPadding = 1;
	tbl.cellSpacing = 1;
	tbl.id = "tblMult";	// Additional styling in stylesheet.
	
	// Make the table by adding the rows, cells, and cell values.
	maxIndex = maxNum + 1;
	for(var rowIndex = 0; rowIndex < maxIndex; rowIndex++)
	{
		// Create the next row.
		tr = tbl.insertRow(rowIndex);
		for(var colIndex = 0; colIndex < maxIndex; colIndex++)
		{
			// Create the next cell.
			td = tr.insertCell(colIndex);
			
			// Write the headers for the top row.
			if(rowIndex == 0 && colIndex > 0)
			{
				td.className = "colHead";
				td.innerHTML = "<b>" + colIndex + "</b>";
			}
			// Write the headers for the left-most column.
			else if(colIndex == 0 && rowIndex > 0)
			{
				td.className = "rowHead";
				td.innerHTML = "<b>" + rowIndex + "</b>";
			}
			// Write the product of the headers.
			else if(rowIndex > 0 && colIndex > 0)
				td.innerHTML = rowIndex * colIndex;
		}
	}
}

// Gives me easy access to elements via their ID.
function gE(id){ return document.getElementById(id); }
