var InputCellFocus = 0;

function disableEnterKey()
{
	return true;
}

/***************************************************************************
*
*				INIT FUNCTIONS
*
****************************************************************************/

// Image roll-over function that works via the classname for an image.
function initRollovers() 
{
	if (!document.getElementById) 
		return;
	
	var aPreLoad = new Array();
	var sTempSrc;
	var aImages = document.getElementsByTagName('img');

	for (var i = 0; i < aImages.length; i++) 
	{		
		if (aImages[i].className == 'imgover') 
		{
			var src = aImages[i].getAttribute('src');
			var ftype = src.substring(src.lastIndexOf('.'), src.length);
			var hsrc = src.replace(ftype, '-over'+ftype);

			aImages[i].setAttribute('hsrc', hsrc);
			
			aPreLoad[i] = new Image();
			aPreLoad[i].src = hsrc;
			
			aImages[i].onmouseover = function() {
				sTempSrc = this.getAttribute('src');
				this.setAttribute('src', this.getAttribute('hsrc'));
			}	
			
			aImages[i].onmouseout = function() {
				if (!sTempSrc) sTempSrc = this.getAttribute('src').replace('-over'+ftype, ftype);
				this.setAttribute('src', sTempSrc);
			}
		}
	}
}

// Initialize table cells
function initTableCells()
{
	if (!document.getElementById)
		return;
	var inputs = document.getElementsByTagName('input');
	for (var i = 0 ; i < inputs.length ; i++)
	{
		if (inputs[i].className == "InputCell" ||
				inputs[i].className == "InputMoney" ||
				inputs[i].className == "InputPercent" ||
				inputs[i].className == "InputString" ||
				inputs[i].className == "InputCellWhole" ||
				inputs[i].className == "InputCellYear" ||
				inputs[i].className == "InputMoneyWhole" ||
				inputs[i].className == "InputPercentWhole" ||
				inputs[i].className == "InputPercentShort" ||
				inputs[i].className == "InputMoneyShort" ||
				inputs[i].className == "InputCellShort")
		{	
			inputs[i].onkeydown = 
				function() 
				{
					InputCellFocus=1;
				} 
			inputs[i].onkeyup=
				function()
				{
					InputCellFocus=0; 
					UpdateAll();
				} 
			inputs[i].onkeypress=
				function()
				{
					return disableEnterKey();
				}
		}
	}
}

/***************************************************************************
*
*				TABLE FUNCTIONS
*
****************************************************************************/

var table;
var hasTable = false;

/*
CreateTable()
Determines the dimensions of the table on this page given by the input fields
where class="InputCell", etc. Assumes cells have excel spreadsheet style ids, ie id="B3"
*/
function CreateTable()
{
	var inputs = document.getElementsByTagName('input');
	var divs = document.getElementsByTagName('div');
	var numCols = 0;
	var numRows = 0;
	
	// Loop through all input and output cells
	for (var i = 0 ; i < inputs.length ; ++i)
	{
		if (inputs[i].className == "InputCell" ||
			  inputs[i].className == "InputMoney" ||
			  inputs[i].className == "InputPercent" ||
			  inputs[i].className == "InputCellWhole" ||
			  inputs[i].className == "InputCellYear" ||
			  inputs[i].className == "InputMoneyWhole" ||
			  inputs[i].className == "InputPercentWhole" ||
			  inputs[i].className == "InputPercentShort" ||
			  inputs[i].className == "InputMoneyShort" ||
			  inputs[i].className == "InputCellShort")
		{
			var cell = inputs[i].getAttribute('id');
			// Get the column and row
			var col = cell.charCodeAt(0) - 64;	// Unicode 'A' = 0x41=65
			var row = parseInt(cell.slice(1));
			if (col > numCols)
				numCols = col;
			if (row > numRows)
				numRows = row;
		}
	}
	for (var i = 0 ; i < divs.length ; ++i)
	{
		if (divs[i].className == "OutputCell" ||
			divs[i].className == "OutputMoney" ||
			divs[i].className == "OutputPercent" ||
			divs[i].className == "OutputCellWhole" ||
			divs[i].className == "OutputMoneyWhole" ||
			divs[i].className == "OutputPercentWhole" ||
			divs[i].className == "OutputPercentShort" ||
			divs[i].className == "OutputCellShort" ||
			divs[i].className == "OutputMoneyShort")
		{
			var cell = divs[i].getAttribute('id');
			// Get the column and row
			var col = cell.charCodeAt(0) - 64;	// Unicode 'A' = 0x41=65
			var row = parseInt(cell.slice(1));
			if (col > numCols)
				numCols = col;
			if (row > numRows)
				numRows = row;
		}
	}
	
	if (numRows > 0 && numCols > 0)
	{
		hasTable = true;
		
		table = new Array(numCols);
		for (var i = 0 ; i < numCols ; ++i)
		{
			table[i] = new Array(numRows);
		}
	}
}

/*
ReadTable()
Reads the values from the appropriate table cells into the table array
*/
function ReadTable()
{
	var inputs = document.getElementsByTagName('input');
	var divs = document.getElementsByTagName('div');
	
	for (var i = 0 ; i < inputs.length ; ++i)
	{
		var cell = inputs[i].getAttribute('id');
		var cls = inputs[i].className;
			
		if (cls == "InputCell" ||
				cls == "InputMoney" ||
				cls == "InputPercent" ||
				cls == "InputCellWhole" ||
				cls == "InputCellYear" ||
				cls == "InputMoneyWhole" ||
				cls == "InputPercentWhole" ||
				cls == "InputPercentShort" ||
				cls == "InputMoneyShort" ||
				cls == "InputCellShort")
		{
			// Get the column and row
			var col = cell.charCodeAt(0) - 64;	// Unicode 'A' = 0x41=65
			var row = parseInt(cell.slice(1));
			
			var val;
			if ( (cls == "InputPercent") || (cls == "InputPercentWhole") || (cls == "InputPercentShort") )
			{
				val = (parseFloat(inputs[i].value) / 100);
			} else {
				val = parseFloat(inputs[i].value);
			}
			
			table[col-1][row-1] = val;
			if (isNaN(table[col-1][row-1]) || !isFinite(table[col-1][row-1]))
				table[col-1][row-1] = 0;
		}
	}
	for (var i = 0 ; i < divs.length ; ++i)
	{
		var cell = divs[i].getAttribute('id');
		var cls = divs[i].className;
		
		if (cls == "OutputCell" ||
				cls == "OutputMoney" ||
				cls == "OutputPercent" ||
				cls == "OutputCellWhole" ||
				cls == "OutputMoneyWhole" ||
				cls == "OutputPercentWhole" ||
				cls == "OutputPercentShort" ||
				cls == "OutputCellShort" ||
				cls == "OutputMoneyShort")
		{
			// Get the column and row
			var col = cell.charCodeAt(0) - 64;	// Unicode 'A' = 0x41=65
			var row = parseInt(cell.slice(1));

			if ( (cls == "OutputCell") || (cls == "OutputCellShort") || (cls == "OutputCellWhole") )
			{
				table[col-1][row-1] = StripCommas(divs[i].innerHTML);
			}
			if ( (cls == "OutputMoney") || (cls == "OutputMoneyShort") || (cls == "OutputMoneyWhole") )
			{
				table[col-1][row-1] = StripMoney(divs[i].innerHTML);
			}
			if ( (cls == "OutputPercent") || (cls == "OutputPercentWhole") || (cls == "OutputPercentShort") )
			{
				table[col-1][row-1] = StripPercent(divs[i].innerHTML);
			}
			if (isNaN(table[col-1][row-1]) || !isFinite(table[col-1][row-1]))
					table[col-1][row-1] = 0;
		}
	}
}

/*
WriteTable()
Write the values in the table array into the appropriate div cells
*/

function WriteTable()
{
	var divs = document.getElementsByTagName('div');
	
	for (var i = 0 ; i < divs.length ; ++i)
	{
		var cell = divs[i].getAttribute('id');
		var cls = divs[i].className;
		
		if (cls == "OutputCell" ||
				cls == "OutputMoney" ||
				cls == "OutputPercent" ||
				cls == "OutputCellWhole" ||
				cls == "OutputMoneyWhole" ||
				cls == "OutputPercentWhole" ||
				cls == "OutputPercentShort" ||
				cls == "OutputCellShort" ||
				cls == "OutputMoneyShort")
		{
			// Get the column and row
			var col = cell.charCodeAt(0) - 64;	// Unicode 'A' = 0x41=65
			var row = parseInt(cell.slice(1));
		
			if (cls == "OutputCell")
			{	
			/*	divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" : 
					((isFinite(table[col-1][row-1]) ? table[col-1][row-1] : String.fromCharCode(8734));	*/
				
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatFloat(table[col-1][row-1], 2) : "Infinity");	
			}
			if (cls == "OutputMoney")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatMoney(table[col-1][row-1], 2) : "Infinity");	
			}
			if (cls == "OutputPercent")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatPercent(table[col-1][row-1], 2) : "Infinity");	
			}
			if (cls == "OutputCellWhole")
			{
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatFloat(table[col-1][row-1], 0) : "Infinity");	
			}
			if (cls == "OutputMoneyWhole")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatMoney(table[col-1][row-1], 0) : "Infinity");	
			}
			if (cls == "OutputPercentWhole")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatPercent(table[col-1][row-1], 0) : "Infinity");				
			}
			if (cls == "OutputPercentShort")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatPercent(table[col-1][row-1], 1) : "Infinity");	
			}
			if (cls == "OutputCellShort")
			{
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatFloat(table[col-1][row-1], 1) : "Infinity");	
			}
			if (cls == "OutputMoneyShort")
			{	
				divs[i].innerHTML = (isNaN(table[col-1][row-1])) ? "0" :
					(isFinite(table[col-1][row-1]) ? FormatMoney(table[col-1][row-1], 1) : "Infinity");	
			}
		}
	}
}

function UpdateAll()
{
	CreateTable();
	
	if (hasTable)
	{
		ReadTable();
		PerformCalculations();		// Must be defined in including page
		WriteTable();
	}
	
	UpdateHiddenCells();
}

/***************************************************************************
*
*				PRINTING RELATED FUNCTIONS
*
****************************************************************************/

// Update hidden cells with the values of their associated textboxes
function UpdateHiddenCells()
{		
	var divs = document.getElementsByTagName('div');
	for (var i = 0 ; i < divs.length ; ++i)
	{
		if (divs[i].className == "InputHidden")
		{
			var cell = divs[i].getAttribute('id');
			cell = cell.replace('_H',"");
			
			var input = document.getElementById(cell);
			var cls = input.className;
			var val = 0;
			
			if (cls == "InputCell")
			{
				val = FormatFloat(input.value, 2);
			}
			else if (cls == "InputMoney")
			{
				val = FormatMoney(input.value, 2);
			}
			else if (cls == "InputPercent")
			{
				val = FormatPercent( (input.value / 100), 2 );
			}
			else if (cls == "InputString")
			{
				val = input.value;
			}
			else if (cls == "InputCellWhole")
			{
				val = FormatFloat(input.value, 0);
			}
			else if (cls == "InputCellYear")
			{
				val = input.value;
			}
			else if (cls == "InputMoneyWhole")
			{
				val = FormatMoney(input.value, 0);
			}
			else if (cls == "InputPercentWhole")
			{
				val = FormatPercent( (input.value / 100), 0 );
			}
			else if (cls == "InputPercentShort")
			{
				val = FormatPercent( (input.value / 100), 1 );
			}
			else if (cls == "InputMoneyShort")
			{
				val = FormatMoney(input.value, 1);
			}
			else if (cls == "InputCellShort")
			{
				val = FormatFloat(input.value, 1);
			}
			
			divs[i].innerHTML = val;
		}
	}
}

/***************************************************************************
*
*				FORMAT FUNCTIONS
*
****************************************************************************/

function FormatFloat(num, decPlaces)
{	
	// Round the number
	var factor = Math.pow(10, decPlaces);
	num = Math.round(num * factor) / factor;
	
  numStr = (num < 0) ? new String(-1 * num) : new String(num);
  
  // find the position of the decimal
  dotPosition = numStr.indexOf('.');

  // if it's an integer, there is no decimal, so stick ".*" on the end
  if (dotPosition < 0)
  {
  	if (decPlaces > 0)
  	{
   		numStr = numStr + ".";
   		for (var i = 0 ; i < decPlaces ; ++i)
   		{
   			numStr = numStr + "0";
   		}
  	}
  } else {
    // probably need to trim it
    if(numStr.length > (dotPosition + decPlaces)) 
    	numStr = numStr.substr(0, dotPosition + decPlaces + 1);
    else 
    {
    	for (var i = numStr.length ; i <= (dotPosition + decPlaces) ; ++i)
    		numStr = numStr + '0';
    }

    if ( (dotPosition == 0) && (decPlaces > 0) )
    	numStr = '0' + numStr;
    if ( decPlaces == 0)
    	numStr = numStr.replace(".", "");
  }

	// Insert commas
	var count = 0;
	var numSegments = 0;
	var thisSegment = 0;
	var start = 0;
	if (decPlaces > 0)
		start = numStr.length - (2 + decPlaces);
	else
		start = numStr.length - 1;
		
	for (var i = start ; i >= 0 ; --i)
	{
		++thisSegment;
		if ( (++count % 3) == 0)
		{
			++numSegments;
			thisSegment = 0;
		}
	}
	if (thisSegment == 0)
	{
		thisSegment = 3;
		--numSegments;
	}
	var tmpStr = numStr.substr(0, thisSegment);
	var curIndex = thisSegment;
	while (numSegments > 0)
	{
		tmpStr += ",";
		tmpStr += numStr.substr(curIndex, 3);
		curIndex += 3;
		--numSegments;
	}
	tmpStr += numStr.substr(curIndex);
	numStr = tmpStr;
	
	// Check validity
	if(num < 0 && isFinite(num) && numStr.match(/[1-9]/) ) 
  	numStr = '-' + numStr;
  else if (isNaN(num) || !isFinite(num)) 
  	numStr = '0.00';

  return (numStr);
}

function FormatMoney(num, decPlaces)
{
	var wasNeg = false;
	
	if (num < 0)
	{
		num *= -1;
		wasNeg = true;
	}
		
	str = FormatFloat(num, decPlaces);
	
	if (wasNeg && str.match(/[1-9]/) )
	{
		str = "-$" + str;
	} else {
		str = "$" + str;
	}
	
	return str;
}

function FormatPercent(num, decPlaces)
{
	str = FormatFloat( (num * 100) , decPlaces );
	
	str += "%";
	
	return str;
}

function StripCommas(str)
{
	while (str.indexOf(',') >= 0)
		str = str.replace(',', "");
	return str;
}

function StripMoney(str)
{
	str = StripCommas(str.replace('$', ""));
	return parseFloat(str);
}

function StripPercent(str)
{
	str = StripCommas(str.replace('%', ""));
	return (parseFloat(str) / 100);
}
