var	m_bInRecalcCashFlow = false;
var	m_bInRecalcAdjustedCashFlow = false;
var	m_iProgressQty=1;
var	m_iProgressCurrent=1;
var m_bShowProgress = false;

// Caching hashtables
var cacheCalcs = new Array();
var cacheVars = new Array();

var bdiTagStart = new Array(); // budget detail input tagstart collection built during initialization
var iiTagStart = new Array(); // income input tagstart collection built during initialization
//var bdiTagStartCount = 0;

var m_currentIdx = 0;

var m_TotalSales = -1;
var m_FinalBudget = -1;

var m_bShowMessageBox = false;
var m_bInitializing = true;

var m_bInPerformAllSimpleCalcs = false;
var	m_bInEvallAllOnChange = false;

var m_tooltipID = 0;
var m_bShowWarning = true;

function QuickHelp(oCtl, event, helpText)
{
	domTT_deactivate(m_tooltipID); // close any already open tooltip

	m_tooltipID = domTT_activate(oCtl, event, 'caption', 'Quick Help', 'content', helpText, 'trail', true);

}

function QHInfo(oCtl, event)
{
	domTT_deactivate(m_tooltipID); // close any already open tooltip
	
	var str = 'Get quick help by placing the cursor over the text description of the line-item '+
			'for which you have a question. The quick help box will stay visible as long as '+
			'the cursor remains over the text.  You may also push the \"?\" button for more '+
			'detailed information and/or larger text size.';
	m_tooltipID = domTT_activate(oCtl, event, 'content', str, 'trail', true);

}

function TCAlert(msg)
{
	if(m_bShowMessageBox)
		return alert(msg);
	else
		return true;
}

function WindowWidth() 
{
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}


function WindowHeight() 
{
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }

  return myHeight;
}


var _bOverviewVisible = false;
var _bInstructionVisible = false;

var htOverview = 125;

var htFooter = 40;
var htMargin = 160;

var htSep = 90;
var topContent = 140;



function SetSpan(spanID, spanHTML)
{
	var aSpan = document.body.getElementsByTagName("SPAN");
	for(var i = 0; i < aSpan.length; i++)
	{
		if(aSpan[i].id.indexOf(spanID) > -1)
		{
			aSpan[i].innerHTML = spanHTML;
			break;
		}
	}

}

function SetNPPBTOptionNote()
{
// Special purpose function for setting note text on Market Variables / Market Investment Criteria page

	SetSpan("NPBT_OptionNote","");// initialize - clear

	if( (NTC("SubjectBusIndustryStd_NPBT") > 0.0) &&
		(NTC("TotalOtherCashInvestments") > 0.0) )
	{
		SetSpan("NPBT_OptionNote", "When using the NPBT % as the investment standard, the business " + 
			"value won\'t change with a variation of \"Other Cash Investments\" but the ROI percentage " + 
			"to the investor will decrease as other cash investments increase. To see the percentage " + 
			"variation of ROI, perform an analysis with and without \"Other Cash Investments\" and " + 
			"view the ROI % variance in the Analysis Summary Section.");
	}	
			
	if( (NTC("Investor_ROI") > 0.0) &&
		(NTC("TotalOtherCashInvestments") > 0.0) )
	{
		SetSpan("NPBT_OptionNote",
			"When using the \"Investor Market Rate of Return on Down Payment % (ROI)\" as the investment standard, the business " + 
			"value will change with a variation of \"Other Cash Investments\" but the ROI percentage " + 
			"to the investor will remain consistent to the ROI % specified.  To see the variation of business "+
			"value, perform an analysis with and without \"Other Cash Investments\" and calculate and view "+
			"the different business values at the Income Statement Input Tab page in the Financial Statements Section.");
	}
					
}


function getElementPosition(elemID) {
    var offsetTrail = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

// * IssueID PDC002 PDC 03/26/2007
// * Duplicate Method for New Cash Flow pages which have different qualities
// * Added custom cmode for the tab control
function Resize_CF()
{
	var oContent = document.getElementById('divContent_CF');
	var oOverview = document.getElementById('divOverview');
	var oPHolder = document.getElementById('divPlaceHolder');
	var oInstruction = document.getElementById('divInstruction');//Added:
	var oButtons = document.getElementById('divButtons');

	if (null == oContent)
		return;

// test
var pos = getElementPosition('divContent_CF');
// test

	var htWindow = WindowHeight();
		
	if (null == oOverview || null == oPHolder)
	{
		oContent.style.height = htWindow - 280;//htFooter;
		return;
	}
		
	var topOverview = htWindow - (htOverview + htFooter);

	oOverview.style.top = topOverview + 10;

	oOverview.style.position = 'absolute';
//	oContent.style.position = 'absolute';
//	oContent.style.top = topContent;  -- can only set top when using absolute positioning
	
	//Added: make hidden first
	oOverview.style.visibility = 'hidden';
	oInstruction.style.visibility = 'hidden';
		
	var ContentHeight;
	if(true == _bOverviewVisible)
	{
		oOverview.style.visibility = 'visible';
		oInstruction.style.visibility = 'hidden';	//Added:
		oPHolder.style.height = htOverview;
		//ContentHeight = htWindow - (oContent.offsetTop + htOverview + htFooter + htMargin);
		//ContentHeight = topOverview - (oContent.offsetTop + htSep);
		ContentHeight = topOverview - (topContent + htSep) - 15;
	}
	else
	{
		oOverview.style.visibility = 'hidden';
		oPHolder.style.height = '1px';
		//ContentHeight = htWindow - (oContent.offsetTop + htFooter + htMargin);
		
		
		ContentHeight = topOverview - (htFooter + htSep);
		ContentHeight = htWindow - pos.top - (htFooter + htSep);
	}
	
	if (ContentHeight > 0)
		oContent.style.height = ContentHeight;
		
	// * IssueID PDC002 PDC 03/26/2007
	oContent.style.width = WindowWidth() - 50;
	oContent.style.overflow = 'auto';
	
	if (null != oButtons)
	{
		oButtons.style.position = 'absolute';
		oButtons.style.top = getElementPosition('divTabs').top - 23;
		// JJF 6/11/2008 - Moved to allow another button
		//oButtons.style.left = WindowWidth() - 185 - 130 - 25;
		oButtons.style.left = WindowWidth() - 185 - 150 - 125;
		//oButtons.style.border = "1px solid #000000";
		oButtons.style.width = 425;
		oButtons.style.textAlign = "right";
		if(document.location.pathname.indexOf("CashFlowVariables") != -1)
		{
			oButtons.style.visibility = 'hidden';
		}
		if(document.location.pathname.indexOf("KeepOnTrack") != -1) {
			document.getElementById("btnKOTStrategies").style.display = "";
		}		
	}	
	
}	


function Resize()
{
	var oContent = document.getElementById('divContent');
	var oOverview = document.getElementById('divOverview');
	var oPHolder = document.getElementById('divPlaceHolder');
	var oInstruction = document.getElementById('divInstruction');//Added:
	
	// * IssueID PDC002 PDC 03/26/2007
	if (null == oContent)
	{
		Resize_CF();
		return;
	}
	
// test
var pos = getElementPosition('divContent');
// test

	var htWindow = WindowHeight();
		
	if (null == oOverview || null == oPHolder)
	{
		oContent.style.height = htWindow - 280;//htFooter;
		return;
	}
		
	var topOverview = htWindow - (htOverview + htFooter);

	oOverview.style.top = topOverview + 10;

	oOverview.style.position = 'absolute';
//	oContent.style.position = 'absolute';
//	oContent.style.top = topContent;  -- can only set top when using absolute positioning
	
	//Added: make hidden first
	oOverview.style.visibility = 'hidden';
	oInstruction.style.visibility = 'hidden';
		
	var ContentHeight;
	if(true == _bOverviewVisible)
	{
		oOverview.style.visibility = 'visible';
		oInstruction.style.visibility = 'hidden';	//Added:
		oPHolder.style.height = htOverview;
		//ContentHeight = htWindow - (oContent.offsetTop + htOverview + htFooter + htMargin);
		//ContentHeight = topOverview - (oContent.offsetTop + htSep);
		ContentHeight = topOverview - (topContent + htSep) - 15;
	}
	else
	{
		oOverview.style.visibility = 'hidden';
		oPHolder.style.height = '1px';
		//ContentHeight = htWindow - (oContent.offsetTop + htFooter + htMargin);
		
		
		ContentHeight = topOverview - (htFooter + htSep);
		ContentHeight = htWindow - pos.top - (htFooter + htSep);
	}
	
	if (ContentHeight > 0)
		oContent.style.height = ContentHeight;
}	


function ToggleOverviewDisplay()
{
	var btn = document.getElementById('btnToggleOverview');
	if(_bOverviewVisible  )
	{
		_bOverviewVisible = false;
		btn.value = "Section Overview";
	}
	else
	{
		_bOverviewVisible = true;
		btn.value = "Hide Section Overview";

	}
	
	Resize();	
}

// * IssueID PDC002 PDC 03/26/2007
// * Duplicate Method for New Cash Flow pages which have different qualities
function ResizeInstructionBox_CF()
{
	var oContent = document.getElementById('divContent_CF');
	var oInstruction = document.getElementById('divInstruction');
	var oOverview = document.getElementById('divOverview');
	var oPHolder = document.getElementById('divPlaceHolder');
	
	if (null == oContent)
		return;
		
	var htWindow = WindowHeight();
	
// test
var pos = getElementPosition('divContent_CF');
// test	

	if (null == oInstruction || null == oPHolder)
	{
		oContent.style.height = htWindow - 280;//htFooter;
		return;
	}
		
	var topOverview = htWindow - (htOverview + htFooter);

	oInstruction.style.top = topOverview + 10;

	oInstruction.style.position = 'absolute';
//	oContent.style.position = 'absolute';
	oContent.style.top = topContent;
	
	//Added: make hidden first
	oOverview.style.visibility = 'hidden';
	oInstruction.style.visibility = 'hidden';
	
	var ContentHeight;
	if(true == _bInstructionVisible)
	{
		oInstruction.style.visibility = 'visible';
		oOverview.style.visibility = 'hidden';
		
		oPHolder.style.height = htOverview;
		//ContentHeight = htWindow - (oContent.offsetTop + htOverview + htFooter + htMargin);
		//ContentHeight = topOverview - (oContent.offsetTop + htSep);
		ContentHeight = topOverview - (topContent + htSep) - 15;
	}
	else
	{
		oInstruction.style.visibility = 'hidden';
		oPHolder.style.height = '1px';
		//ContentHeight = htWindow - (oContent.offsetTop + htFooter + htMargin);
		ContentHeight = topOverview - (htFooter + htSep);
		ContentHeight = htWindow - pos.top - 70;// test
	}
	
	if (ContentHeight > 0)
		oContent.style.height = ContentHeight;
		
	oContent.style.width = WindowWidth() - 50;
	oContent.style.overflow= 'auto';
}

function ResizeInstructionBox()
{
	var oContent = document.getElementById('divContent');
	var oInstruction = document.getElementById('divInstruction');
	var oOverview = document.getElementById('divOverview');
	var oPHolder = document.getElementById('divPlaceHolder');
	
	// * IssueID PDC002 PDC 03/26/2007
	if (null == oContent)
	{
		ResizeInstructionBox_CF();
		return;
	}
		
	var htWindow = WindowHeight();

// test
var pos = getElementPosition('divContent');
// test
		
	if (null == oInstruction || null == oPHolder)
	{
		oContent.style.height = htWindow - 280;//htFooter;
		return;
	}
		
	var topOverview = htWindow - (htOverview + htFooter);

	oInstruction.style.top = topOverview + 10;

	oInstruction.style.position = 'absolute';
//	oContent.style.position = 'absolute';
	oContent.style.top = topContent;
	
	//Added: make hidden first
	oOverview.style.visibility = 'hidden';
	oInstruction.style.visibility = 'hidden';
	
	var ContentHeight;
	if(true == _bInstructionVisible)
	{
		oInstruction.style.visibility = 'visible';
		oOverview.style.visibility = 'hidden';
		
		oPHolder.style.height = htOverview;
		//ContentHeight = htWindow - (oContent.offsetTop + htOverview + htFooter + htMargin);
		//ContentHeight = topOverview - (oContent.offsetTop + htSep);
		ContentHeight = topOverview - (topContent + htSep) - 15;
	}
	else
	{
		oInstruction.style.visibility = 'hidden';
		oPHolder.style.height = '1px';
		//ContentHeight = htWindow - (oContent.offsetTop + htFooter + htMargin);
		ContentHeight = topOverview - (htFooter + htSep);
		ContentHeight = htWindow - pos.top - 70;// test
	}
	
	if (ContentHeight > 0)
		oContent.style.height = ContentHeight;
}


function MakeButtonVisible()
{
	var btn = document.getElementById('btnToggleInstruction');
	btn.style.visibility = 'visible';
	
	//only show Quick Start Guide when instruction button is also visible
	//Also only show if in business or income property valuation section
	if(document.location.pathname.indexOf("BusinessValuation") !=-1)
	{
		var btn = document.getElementById('btnQuickStart');
		btn.style.display = '';
		var btn2 = document.getElementById('btnQuickStart2');
		btn2.style.display = '';
	}
	else if(document.location.pathname.indexOf("PropertyValuation") !=-1)
	{
		var btn = document.getElementById('btnQuickStart3');
		btn.style.display = '';
	}
}

function ShowQuickStart()
{
	var url = document.location.protocol + "//"+ document.location.hostname +"/"+ document.location.pathname.split("/")[1];
	
	if(document.location.pathname.indexOf("BusinessValuation") !=-1)
	{
		window.open( url +  '/Sample Docs/QuickStartGuideBiz.pdf', 'quickstart');
	}
	else
	{
		window.open( url +  '/Sample Docs/QuickStartGuideIncProp.pdf', 'quickstart');
	}
}

function ToggleInstructionDisplay()
{
	var btn = document.getElementById('btnToggleInstruction');
	if(_bInstructionVisible  )
	{
		_bInstructionVisible = false;
		btn.value = "Start Instructions";
	}
	else
	{
		_bInstructionVisible = true;
		btn.value = "Hide Instructions";
	}
	
	ResizeInstructionBox();	
}

function GetElementIndex( elemId)
// Return index of element with id equal to elemId
{
	with (document.forms[0])
	{
		for(var i = 0; i < length; i++)
		{
			if(elemId == elements[i].id)
			{
				return i;
			}
		}
	}
	return -1;
}

function EnableFieldRange(bEnable, tagNameStart, tagNameEnd)
{
	var idxStart = GetElementIndexByTag(tagNameStart);
	var idxEnd = GetElementIndexByTag(tagNameEnd);

	if (-1 == idxStart)
		return;
		
	with (document.forms[0])
	{
		for(var i = idxStart; i <= idxEnd; i++)
		{
			if(elements[i].type == "select-one")
			{
				elements[i].disabled = !bEnable;
			}
			else // "text", "radio", etc.
			{
				elements[i].readOnly = !bEnable;
				// * IssueID PDC002 PDC 04/02/2007
				if (!bEnable)
				{
					elements[i].className = "readonlyValue";
				} else
				{
					elements[i].className = "currency";
				}
			}
				//elements[i].style.visibility = 'visible';
				//elements[i].onfocus =  null;
				
				//elements[i].style.visibility = 'hidden';
				//elements[i].onfocus = elements[i].blur;
		}
	}
	
}


function GetElementIndexByTag( elemTag)
// Return index of element with id *containing* elemTag
{
	with (document.forms[0])
	{
		for(var i = 0; i < length; i++)
		{
			if(-1 != elements[i].id.indexOf(elemTag))
			{
				return i;
			}
		}
	}
	return -1;
}

function GetRowWidth(idx)
// Return number of elements with same id prefix as the element at index idx
{
	with (document.forms[0])
	{
		var pos = elements[idx].id.lastIndexOf("_");
		var prefix = elements[idx].id.substr(0, pos);
		
		var start = -1;
		var end = -1;
		// back-up to find start of row
		for(var i = idx; i >=0; i--)
		{
			if (-1 == elements[i].id.indexOf(prefix))
			{
				start = i;
				break;
			}
		}
		
		// move forward to find row end
		for(var i = idx; i < length; i++)
		{
			if (-1 == elements[i].id.indexOf(prefix))
			{
				end = i;
				break;
			}
		}
		
		if((start == -1) || (end == -1))
			alert('failed to find row limits.');
			
		return ((end-start) -1);
	}
}

function GetNextRowBaseId()
// Return number of elements with same id prefix as the element at index idx
{
	with (document.forms[0])
	{
		var pos = elements[m_currentIdx].id.lastIndexOf("_");
		var prefix = elements[m_currentIdx].id.substr(0, pos);
		
		pos = -1;
		
		// move forward to find next row 
		var i;
		for(i = m_currentIdx; i < length; i++)
		{
			if (-1 == elements[i].id.indexOf(prefix))
			{
				break;
			}
		}

		m_currentIdx = i;
		{
			pos = elements[m_currentIdx].id.lastIndexOf("~");
			prefix = elements[m_currentIdx].id.substr(0, pos);
		}
		
		return prefix;
	}
}


function DE(elemTag)
// Return the Document Element (i.e. element object) with id elemTag
{

	// Check element cache first
/***	
	var elem = cacheVars[elemTag];
	if (null != elem)
		return elem;
**/
	with (document)
	{
		for(var i = 0; i < all.length; i++)
		{
			if(-1 != all[i].id.indexOf(elemTag))
			{
				//cacheVars[elemTag] = elements[i];
				return all[i];
			}
		}
	}
	alert('Could not find Document Element: ' + elemTag);
	return null;
}

// * IssueID PDC002 PDC 06/12/2007
function FieldExists(elemTag)
// if there is a field with id elemTag, return True
{
	var elem = cacheVars[elemTag];
	if (null != elem)
		return true;
	with (document.forms[0])
	{
		var sTemp = ClientIDTable[elemTag];
		if (null != elements[sTemp])
		{
			cacheVars[elemTag] = elements[sTemp];
			return elements[sTemp];
		} else
		{
			with (document.forms[0])
			{
				for(var i = 0; i < length; i++)
				{
					if(-1 != elements[i].id.indexOf(elemTag))
					{
						cacheVars[elemTag] = elements[i];
						return true;
					}
				}
			}
		}
	}

	return false;		
}

function UpdateBudgetField(fieldNum)
{
	var radType  = TC('CF_SalesPct_CalcType~RAD1');
	var pctField = 'CF_SalesPct_M' + fieldNum;
	var amtField = 'CF_SalesAmt_M' + fieldNum;
	var slsTotal = TC('CF_SalesPct_Total');
	var pctAmt   = 0;
	var totSales = 0;
	var totAmt   = 0;
	var pctTotal = 0;

	try {
		if (typeof(radType) == 'object')
		{
			if (radType.checked)
			{
				totSales = NTC('CF_SalesAmt_Annual');
				pctAmt   = NTC(pctField);

				TC(amtField).value = Currency(totSales * (pctAmt / 100));

				if (FieldExists('CF_SalesPct_Total'))
				{
				}
			}
			else
			{
				TC(pctField).value = PctOf(amtField,'CF_SalesAmt_Annual');
			}

			if (typeof(slsTotal) == 'object')
			{
				for (var i = 1; i < 13; i++)
					totAmt += NTC('CF_SalesPct_M' + i);
				slsTotal.value = TwoDecimal(totAmt);
			}
		}
	}
	catch(err) {
	
	}
}

function TC(elemTag)
// Return the Tagged Control (i.e. element object) with id elemTag
{

	// Check element cache first
	var elem = cacheVars[elemTag];
	if (null != elem)
		return elem;

// * IssueID PDC002 PDC 04/16/2007
/*
	with (document.forms[0])
	{
		for(var i = 0; i < length; i++)
		{
			if(-1 != elements[i].id.indexOf(elemTag))
			{
				cacheVars[elemTag] = elements[i];
				return elements[i];
			}
		}
	}
*/
	with (document.forms[0])
	{
		var sTemp = ClientIDTable[elemTag];
		if (null != elements[sTemp])
		{
			cacheVars[elemTag] = elements[sTemp];
			return elements[sTemp];
		} else
		{
			with (document.forms[0])
			{
				for(var i = 0; i < length; i++)
				{
					if(-1 != elements[i].id.indexOf(elemTag))
					{
						cacheVars[elemTag] = elements[i];
						return elements[i];
					}
				}
			}
		}
	}
	
	//if(m_bShowWarning)
		//alert('Could not find Tagged Control: ' + elemTag);
		
	return null;
}

function NTC(elemTag)
// Return the numerical value of the Tagged Control with id elemTag
{
	return Number(TC(elemTag).value.replace(/%/g , ""));
}

function EvalAllOnChange()
{
	// * IssueID PDC002 PDC 03/22/2007
	var bRecalcCashFlow = false;
	var bRecalcAdjustedCashFlow = false;
	
	if(m_bInEvallAllOnChange)
		return;
	
	m_bInEvallAllOnChange = true;
	
	// No caching in this routine - only being called once on page load
	// this is being called more than once a page - DanB
	var exprsn;
	with (document.forms[0])
	{
		for(var i = 0; i < length; i++)
		{

			var onchange = elements[i].attributes['onchange'];
			if (onchange != undefined)
			{
				exprsn = onchange.value;
			} else {
				exprsn = "null";
			}
			if( (exprsn != "")&& (exprsn != "null"))
			{
			
				if ( (-1 != elements[i].id.indexOf('~ADJUST')) && 
				     (-1 != exprsn.indexOf('this')) )
				{
					// Only need to invoke update expression once per row
					exprsn = exprsn.replace('this','document.forms[0].elements['+i+']')
				}
			
				// * IssueID PDC002 PDC 03/22/2007
				// * Only run this once
				// * Enhance to strip out only that call
				
				if (-1 != exprsn.indexOf('RecalcCashFlow'))
				{
					bRecalcCashFlow=true;
					var arrCommands = new Array();
					arrCommands = exprsn.split(';');
					exprsn = '';
					for(var j = 0; j < arrCommands.length; j++)
					{
						if (-1 == arrCommands[j].indexOf('RecalcCashFlow'))
						{
							exprsn=exprsn+arrCommands[j]+';';
						}
					}
					exprsn=exprsn.replace(';;', ';');
					if (exprsn==';')
					{
						exprsn='';	
					}
				} else
				{
					bRecalcCashFlow=false;
				}
				// * Only run this once
				if (-1 != exprsn.indexOf('RecalcAdjustedCashFlow'))
				{
					bRecalcAdjustedCashFlow=true;
					var arrCommands = new Array();
					arrCommands = exprsn.split(';');
					exprsn = '';
					for(var j = 0; j < arrCommands.length; j++)
					{
						if (-1 == arrCommands[j].indexOf('RecalcAdjustedCashFlow'))
						{
							exprsn=exprsn+arrCommands[j]+';';
						}
					}
					exprsn=exprsn.replace(';;', ';');
					if (exprsn==';')
					{
						exprsn='';	
					}
				} else
				{
					bRecalcAdjustedCashFlow=false;
				}
				// * IssueID 03281 PDC 07/31/2007
				//if (-1 != exprsn.indexOf('UpdateAdjustPctAmt( this,') && (-1 != exprsn.indexOf('AmountAdjustable|WI_Amt_Depreciation~BASE')))
				if ( (exprsn.indexOf('UpdateAdjustPctAmt( this,') != -1) && (exprsn.indexOf('AmountAdjustable|WI_Amt_Depreciation~BASE') != -1))
				{
					exprsn = exprsn.replace('this','document.forms[0].elements['+i+']');
				}
				
				// Don't attempt to evaluate expressions that contain 
				// a "this" argument in a function call, or that 
				// invoke a postback.
				if ( (-1 == exprsn.indexOf('this')) &&
				     (-1 == exprsn.indexOf('doPostBack')) 
				    ) {
					eval(exprsn);
				}
			}
		
		}
	}

	for(var i = 0; i < bdiTagStart.length; i++)
	{
		UpdateAdjustedPctSalesTotal(bdiTagStart[i]); 
	}
	
	// * IssueID 03281 PDC 08/01/2007
	for(var i = 0; i < iiTagStart.length; i++)
	{
		UpdateAdjustedTotal(iiTagStart[i]); 
	}
	

	// * IssueID PDC002 PDC 03/22/2007
	if (bRecalcCashFlow)
	{
		m_bShowProgress = true;
		RecalcCashFlow(1);
	}
	if (bRecalcAdjustedCashFlow)
	{
		m_bShowProgress = true;
		RecalcAdjustedCashFlow(1);
	}
	
	PerformAllSimpleCalcs();
	
	m_bShowMessageBox = true;
	m_bInitializing = false;
	m_bInEvallAllOnChange = false;
	
}

function ClearTC(tag)
{
	var ctl = TC(tag); 
	if (ctl != null)
		ctl.value = "";

}


function ClearBusinessValue()
// Clear business value field if present, and not initializing
{
	if(!m_bInitializing)
	{
		// Clear other calculation result fields
		
		m_bShowWarning = false;
		
		ClearTC("FinalBusinessValue"); 
		ClearTC("OIL_Amount"); 
		ClearTC("OIL_Amount~FINAL"); 
		ClearTC("OIL_Percent"); 
		ClearTC("OIL_Percent~FINAL"); 
		ClearTC("ROIRequired"); 
		ClearTC("ROIRequired_Pct"); 
		
		ClearTC("EBITDA"); 
		ClearTC("EBITDA_MYA"); 
		ClearTC("EBITDA_Pct"); 
		ClearTC("EBITDA_Pct_MYA"); 
		ClearTC("DebtServiceCoverageRatio"); 
		ClearTC("DebtServiceCoverageRatio_MYA"); 
		
		// * IssueID 03208 PDC 05/25/2007
		ClearTC("BD_NOI_FinalPctSales")
		ClearTC("BD_NOI_FinalAIS")
			
		m_bShowWarning = true;				
	}
}


function PerformAllSimpleCalcs()
{
	if(m_bInPerformAllSimpleCalcs) // guard against recursion overflow
		return;

	m_bInPerformAllSimpleCalcs = true;
	
	// Use cached array of calculation expressions
	if( cacheCalcs.length > 0)
	{
		var l = cacheCalcs.length;
		for(var ic = 0; ic < l; ic++)
		{
			eval(cacheCalcs[ic]);
		}
	}
	else
	{
		// Calculation cache not yet defined - build it while evaluating
		var ic = 0;
		var exprsn;
		with (document.forms[0])
		{
			var eID;
			for(var i = 0; i < length; i++)
			{
				eID = elements[i].id;
				if( (-1 != eID.indexOf("AmountCalc|")) ||
				    (-1 != eID.indexOf("AmountTotal|")) ||
				    (-1 != eID.indexOf("SimpleCalc|")) )
				{
					exprsn = elements[i].attributes['onselect'].value;
					if( (exprsn != "")&& (exprsn != "null"))
					{
						eval(exprsn);
						cacheCalcs[ic] = exprsn;
						ic++;
					}
				}
			}
		}

	}
	
	// Clear business value field if present
	ClearBusinessValue();
	
	m_bInPerformAllSimpleCalcs = false;
}

function ElemBaseId(sId)
{
	var pos = sId.indexOf("~");
	if(-1 != pos)
	{
		return sId.substr(0,pos);		
	}
	else
	{
		return sId;
	}
}

// * IssueID PDC002 PDC 04/11/2007
function UpdateAdjustedTotal_Round(tagStart)
// Sum Base and Total columns starting at element tagStart
{
	m_currentIdx = GetElementIndexByTag(tagStart);

	with (document.forms[0])
	{
		var baseTotal = 0;
		var finalTotal = 0;
		var interimTotal = 0;
		var bAdd = true;
		
		var sBaseId = ElemBaseId(elements[m_currentIdx].id);	
		var oBase = document.getElementById(sBaseId + "~BASE");
		var oFinal = document.getElementById(sBaseId + "~FINAL");
		var oAdjust = document.getElementById(sBaseId + "~ADJUST");
		var oInterim = document.getElementById(sBaseId + "~INTERIM");
		
		while(null != oAdjust)  // go until no more Adjust elements - that is total row
		{
			// Is field additive or subtractive?
			bAdd = (sBaseId.indexOf("$-$") == -1 ? true : false); 
			if (bAdd)
			{
				finalTotal += Number(CVal(oFinal.value));
				baseTotal += Number(CVal(oBase.value));
				if (oInterim != null) interimTotal += Number(CVal(oInterim.value));
			}
			else
			{
				finalTotal -= Number(CVal(oFinal.value));
				baseTotal -= Number(CVal(oBase.value));
				if (oInterim != null) interimTotal -= Number(CVal(oInterim.value));
			}	
			sBaseId = GetNextRowBaseId();
			
			oBase = document.getElementById(sBaseId + "~BASE");
			oFinal = document.getElementById(sBaseId + "~FINAL");
			oAdjust = document.getElementById(sBaseId + "~ADJUST");
			oInterim = document.getElementById(sBaseId + "~INTERIM");
		}

		if(null != oBase)
		{
			oBase.value = TwoDecimal(baseTotal);
			oFinal.value = TwoDecimal(finalTotal);
			if (oInterim != null) oInterim.value = TwoDecimal(interimTotal);
		}

	}

}

function UpdateAdjustedTotal(tagStart)
// Sum Base and Total columns starting at element tagStart
{
	m_currentIdx = GetElementIndexByTag(tagStart);

	with (document.forms[0])
	{
		var baseTotal = 0;
		var finalTotal = 0;
		var interimTotal = 0;
		var bAdd = true;
		
		var sBaseId = ElemBaseId(elements[m_currentIdx].id);	
		var oBase = document.getElementById(sBaseId + "~BASE");
		var oFinal = document.getElementById(sBaseId + "~FINAL");
		var oAdjust = document.getElementById(sBaseId + "~ADJUST");
		var oInterim = document.getElementById(sBaseId + "~INTERIM");
		
		while(null != oAdjust)  // go until no more Adjust elements - that is total row
		{
			// Is field additive or subtractive?
			bAdd = (sBaseId.indexOf("$-$") == -1 ? true : false); 
			if (bAdd)
			{
				finalTotal += Number(CVal(oFinal.value));
				baseTotal += Number(CVal(oBase.value));
				if (oInterim != null) interimTotal += Number(CVal(oInterim.value));
			}
			else
			{
				finalTotal -= Number(CVal(oFinal.value));
				baseTotal -= Number(CVal(oBase.value));
				if (oInterim != null) interimTotal -= Number(CVal(oInterim.value));
			}	
			sBaseId = GetNextRowBaseId();
			
			oBase = document.getElementById(sBaseId + "~BASE");
			oFinal = document.getElementById(sBaseId + "~FINAL");
			oAdjust = document.getElementById(sBaseId + "~ADJUST");
			oInterim = document.getElementById(sBaseId + "~INTERIM");
		}

		if(null != oBase)
		{
			//oBase.value = baseTotal.toFixed(2);
			//oFinal.value = finalTotal.toFixed(2);
			oBase.value = Math.floor(baseTotal);
			oFinal.value = Math.floor(finalTotal);
			if (oInterim != null) oInterim.value = Math.floor(interimTotal);
		}

	}

}

function UpdateAdjustedPctSalesTotal(tagStart)
// Sum BaseTotal columns starting at element tagStart
{
	m_currentIdx = GetElementIndexByTag(tagStart);

	with (document.forms[0])
	{
		var baseTotal = 0;
		var finalTotal = 0;
		var actualTotal = 0;
		var pctSaleTotal = 0;
		
		var sBaseId = ElemBaseId(elements[m_currentIdx].id);	
		var oBase = document.getElementById(sBaseId + "~BASE");
		var oActual = document.getElementById(sBaseId + "~ACTUAL");
		var oPctSales = document.getElementById(sBaseId + "~APCTSALES");
		var oFinal = document.getElementById(sBaseId + "~FINAL");
		var oAdjust = document.getElementById(sBaseId + "~ADJUST");
		
		while(null != oAdjust)  // go until no more Adjust elements - that is total row
		{
		
//			finalTotal += Number(CVal(oFinal.value));

			// Is field additive or subtractive?
			bAdd = (sBaseId.indexOf("$-$") == -1 ? true : false); 
			if (bAdd)
			{
				finalTotal += Number(CVal(oFinal.value));
			}
			else
			{
				finalTotal -= Number(CVal(oFinal.value));
			}	
// don't adjust base or actual at all for Budget Input page
//			baseTotal += Number(CVal(oBase.value));
//			actualTotal += Number(CVal(oActual.value));
		
		
		
		
			pctSaleTotal += Number(CVal(oPctSales.value));
			
			sBaseId = GetNextRowBaseId();
			
			oBase = document.getElementById(sBaseId + "~BASE");
			oActual = document.getElementById(sBaseId + "~ACTUAL");
			oPctSales = document.getElementById(sBaseId + "~APCTSALES");
			oFinal = document.getElementById(sBaseId + "~FINAL");
			oAdjust = document.getElementById(sBaseId + "~ADJUST");
		}

		if(null != oBase)
		{

			// don't adjust base or actual at all for Budget Input page
			//oBase.value = Math.floor(baseTotal);
			//oActual.value = Math.floor(actualTotal);
			
			////oFinal.value = Math.floor(finalTotal);
			////oPctSales.value = Math.floor(pctSaleTotal);
			oFinal.value = WholeNum(finalTotal);
			oPctSales.value = TwoDecimal(pctSaleTotal);
		}
	}

}

// * IssueID PDC002 PDC 06/06/2007
function UpdateLAMTForSFI_S(oAmt)
{
	var sID = oAmt.id;
	var sBase;
	var pos = sID.lastIndexOf("~");
	if(-1 == pos)
	{
		sBase = sID
	}
	else
	{
		sBase = sID.substring(0,pos);
	}
	var actual = Number(CVal(document.getElementById(sBase + "~BASE").value));
	var oAdjust = document.getElementById(sBase + "~LTV");
	var sAdjust = oAdjust.value;
	var adjust = Number(sAdjust);
	document.getElementById(sBase + "~LAMT").value = Currency(actual * (adjust/100));
}

function UpdateTotalFinancing()
{
	var Total;
	Total = NTC("WI_SFI_A&T~LAMT");
	Total = Total + NTC("WI_SFI_inventory~LAMT");
	Total = Total + NTC("WI_SFI_M&E~LAMT");
	Total = Total + NTC("WI_SFI_OffFurniture~LAMT");
	Total = Total + NTC("WI_SFI_Other~LAMT");
	Total = Total + NTC("WI_SFI_RealEstate~LAMT");
	Total = Total + NTC("WI_AmtFinance_Seller");
	TC("TotalFinancing").Value = Total;
}


function GetGrossSales()
{
	return TC( "SalesIncome~BASE").value;
}



// Income Statement Input
function UpdateAdjustPctAmtRow(oAmt)
{
	var sID = oAmt.id;
	// ID string is of form: <repeaterName>__<controlCount>_<fieldType>|<fieldName>|<itemCount>~<optional modifier>
	// where reperaterName and controlCount are set by ASP.NET.
	// E.g.: rptFields__ctl3_AmountAdjustable|SalesIncome|3~ADJUST


	var sBase;
	var pos = sID.lastIndexOf("~");
	if(-1 == pos)
	{
		sBase = sID
	}
	else
	{
		sBase = sID.substring(0,pos);
	}
//alert("sBase = " + sBase);
	

	var actual = Number(CVal(document.getElementById(sBase + "~BASE").value));
	var oAdjust = document.getElementById(sBase + "~ADJUST");
	var sAdjust = oAdjust.value;
	var sPercent = "";
	var oPct = document.getElementById(sBase + "~PERCENT");
	if (null != oPct)
	{
		sPercent = oPct.value;	
	}
	
	if( (sAdjust.length > 0) && (sPercent.length > 0) )
	{
		// Clear contents of "other" adjustment field
		if(sID.indexOf("~PERCENT") > -1)
		{
			oAdjust.value = "";
		}
		else
		{
			oPct.value = "";
		}
		alert("Enter a value for either Normalization Adjustment or Industry Standard % of Sales, not both.")
		return;
	}

	var adjust = Number(sAdjust);
	var result;
	
	// adjusting by addition or percent multiplier
	if(sPercent.length > 0)
	{
		var percent = Number(sPercent);
		// result = actual * (percent/100);
		result = Number(GetGrossSales()) * (percent/100);
		
		
	}
	else
	{
		result = actual + adjust;
	}
	
	document.getElementById(sBase + "~FINAL").value = Currency(result);
	
}

// * IssueID PDC002 04/02/2007
// Income Statement Input
function UpdateAdjustPctAmtRow_Round(oAmt)
{
	var sID = oAmt.id;
	// ID string is of form: <repeaterName>__<controlCount>_<fieldType>|<fieldName>|<itemCount>~<optional modifier>
	// where reperaterName and controlCount are set by ASP.NET.
	// E.g.: rptFields__ctl3_AmountAdjustable|SalesIncome|3~ADJUST


	var sBase;
	var pos = sID.lastIndexOf("~");
	if(-1 == pos)
	{
		sBase = sID
	}
	else
	{
		sBase = sID.substring(0,pos);
	}

	var actual = Number(CVal(document.getElementById(sBase + "~BASE").value));
	var oAdjust = document.getElementById(sBase + "~ADJUST");
	var sAdjust = oAdjust.value;
	var sPercent = "";
	var oPct = document.getElementById(sBase + "~PERCENT");
	if (null != oPct)
	{
		sPercent = oPct.value;	
	}
	
	if( (sAdjust.length > 0) && (sPercent.length > 0) )
	{
		// Clear contents of "other" adjustment field
		if(sID.indexOf("~PERCENT") > -1)
		{
			oAdjust.value = "";
		}
		else
		{
			oPct.value = "";
		}
		alert("Enter a value for either Normalization Adjustment or Industry Standard % of Sales, not both.")
		return;
	}

	var adjust = Number(sAdjust);
	var result;
	
	// adjusting by addition or percent multiplier
	if(sPercent.length > 0)
	{
		var percent = Number(sPercent);
		// result = actual * (percent/100);
		result = Number(GetGrossSales()) * (percent/100);
		
		
	}
	else
	{
		result = actual + adjust;
	}
	
	document.getElementById(sBase + "~FINAL").value = TwoDecimal(result);
	
}
// * IssueID PDC002 04/02/2007
function UpdateAdjustPctAmt_Round(oAmt, tagStart)
{

	UpdateAdjustPctAmtRow_Round(oAmt);	
	
	if(m_bInitializing)
	{
		if(!InTagStart(iiTagStart,tagStart))
		{
			iiTagStart[iiTagStart.length] = tagStart;
		}	
	}
	else
	{
		UpdateAdjustedTotal_Round(tagStart);
		PerformAllSimpleCalcs();
	}
}


function UpdateAdjustPctAmt(oAmt, tagStart)
{

	UpdateAdjustPctAmtRow(oAmt);	
	
	if(m_bInitializing)
	{
		if(!InTagStart(iiTagStart,tagStart))
		{
			iiTagStart[iiTagStart.length] = tagStart;
		}	
	}
	else
	{
		UpdateAdjustedTotal(tagStart);
		PerformAllSimpleCalcs();
	}
}

var UAIFcount = 0;

function UpdateAllInterimFields()
{
	if(m_bInPerformAllSimpleCalcs) // guard against recursion overflow
		return;
	if(m_bInEvallAllOnChange)
		return;

	m_bInitializing = true;

	window.status = "Running Update All Interim Fields: " + UAIFcount;
	with (document.forms[0])
	{
		for(var i = 0; i < length; i++)
		{
			if(-1 != elements[i].id.indexOf("~INTERIM"))
			{
				elements[i].onchange();
			}
		}
	}
	
	for(var i = 0; i < iiTagStart.length; i++)
	{
		UpdateAdjustedTotal(iiTagStart[i]); 
	}

	PerformAllSimpleCalcs();
	window.status = "Finished Update All Interim Fields: " + UAIFcount++;
	m_bInitializing = false;

}

function UpdateInterimProforma(oAmt)
{
	var sID = oAmt.id;
	// ID string is of form: <repeaterName>__<controlCount>_<fieldType>|<fieldName>|<itemCount>~<optional modifier>
	// where reperaterName and controlCount are set by ASP.NET.
	// E.g.: rptFields__ctl3_AmountAdjustable|SalesIncome|3~ADJUST


	var sBase;
	var pos = sID.lastIndexOf("~");
	if(-1 == pos)
	{
		sBase = sID
	}
	else
	{
		sBase = sID.substring(0,pos);
	}

	var interim = Number(CVal(document.getElementById(sBase + "~INTERIM").value));
	var numberOfMonths = Number(document.getElementById("rptFields:_ctl13:DropList|Interim_Num_Months").value);;
	
	//calculate proforma value
	document.getElementById(sBase + "~BASE").value = Currency(interim * (12 / numberOfMonths));
}

function GetTotalSales()
{
/**
if we do this, we have to update m_TotalSales when the form field changes!

	if (m_TotalSales < 0)
	{
		m_TotalSales = TC( "BD_SalesIncome").value
	}
	
	return m_TotalSales;
**/
	return TC( "BD_SalesIncome").value;
}
 

function GetFinalBudget()
{
/**
if we do this, we have to update m_FinalBudget when the form field changes!
	if (m_FinalBudget < 0)
	{
		m_FinalBudget = TC( "BD_SalesIncome_Final").value
	}
	return m_FinalBudget;
**/
	return TC( "BD_SalesIncome_Final").value;
}

function WholeNum(numValue)
{
	var sResult = numValue.toFixed(0);
	if (0 == sResult.indexOf("NaN"))
		sResult= "??";
		
	return sResult;
}

function TwoDecimal(numValue)
{
	var sResult = numValue.toFixed(2);
	if (0 == sResult.indexOf("NaN"))
		sResult= "??";
		
	return sResult;
}

function Currency(numValue)
{
	var sResult = "";
	var sNumber = new String(Math.floor(numValue));
	
	return sNumber;
	
/***
	if (0 == sNumber.indexOf("NaN"))
		sResult= "??";
	else
	{
		var l = sNumber.length;
		var n = 0;
		for(var i = l; i--; i >=0)
		{
			if((n > 0) && (0 == n%3) )
			{
				sResult = "," + sResult;
			}
			sResult = sNumber.charAt(i) + sResult;
			n++;
		}
	}
	return sResult;
***/	
}

function CVal(sValue)
{
	return  sValue.replace(",", "");
}



function InTagStart(arrTagStart, tagStart)
{
	for(var i = 0; i < arrTagStart.length; i++)
	{
		if(arrTagStart[i] == tagStart)
			return true;		
	}
	return false;
}


// Budget Detail Input
// on page calculation for AmtSalesAdjustPercent items
function UpdateSalesAdjustPctAmt(oAmt, tagStart)
{

	if(m_bInitializing)
		return; //test



	var sID = oAmt.id; // oAmt == form element whose onchange event called this function
	
	// ID string is of form: <repeaterName>__<controlCount>_<fieldType>|<fieldName>|<itemCount>~<optional modifier>
	// where reperaterName and controlCount are set by ASP.NET.
	// E.g.: rptFields__ctl3_AmountAdjustable|SalesIncome|3~ADJUST


	var sBase;
	var pos = sID.lastIndexOf("~");
	if(-1 == pos)
	{
		sBase = sID
	}
	else
	{
		sBase = sID.substring(0,pos);
	}
//alert("sBase = " + sBase);
	

	var sAdjust = CVal(document.getElementById(sBase + "~ADJUST").value);
	var sPercent = "";
	var oPct = document.getElementById(sBase + "~PERCENT");
	if (null != oPct)
	{
		sPercent = CVal(oPct.value);	
	}

	//if( (sAdjust.length > 0) && (sPercent.length > 0) )
	//{
	//	alert("Enter a value for either Normalization Adjustment or Industry Standard % of Sales, not both.")
	//	return;
	//}

	var actual = Number(CVal(document.getElementById(sBase + "~ACTUAL").value));
	var adjust = Number(sAdjust);
	
	var result;
	// adjusting by addition or percent multiplier
	if(sPercent.length > 0)
	{
		var percent = Number(sPercent);
		result = actual * (percent/100);
	}
	else
	{
		result = actual + adjust;
	}
	
	
	/// Don't bother updating fields since other fields of greater significance 
	/// also need to be updated server-side during postback.  Just set the affected
	/// fields to "???"
///	document.getElementById(sBase + "~FINAL").value = Currency(result);
	document.getElementById(sBase + "~FINAL").value = "Calculate Budget"; //"???";


	var budget = Number(GetFinalBudget());
///	document.getElementById(sBase + "~APCTSALES").value = TwoDecimal(result/budget *100);
	// not to worry, javascript handles divide-by-zero nicely...
	document.getElementById(sBase + "~APCTSALES").value = "Calculate"; //"???";
	
	var sales = Number(GetTotalSales());	
///	document.getElementById(sBase + "~BASE").value = TwoDecimal(actual/sales * 100);
	document.getElementById(sBase + "~BASE").value = "???";
	

	if(m_bInitializing)
	{
		if(!InTagStart(bdiTagStart,tagStart))
		{
			bdiTagStart[bdiTagStart.length] = tagStart;
			//bdiTagStartCount++;
		}
	}
	else
	{
		UpdateAdjustedPctSalesTotal(tagStart);
		PerformAllSimpleCalcs();
	}
}

function AdjustOwnerSalary()
{
	if(!m_bInitializing)
	{
		if( //TC("Amt_SalaryOwner~ADJUST").value == "automatic" && 
			TC("Amt_SalaryOwner~PERCENT").value == "" && 
			TC("Amt_SalaryOwner~BASE").value != "" &&
			TC("Amt_SalaryOwner~FINAL").value != "" )
		{
			TC("Amt_SalaryOwner~ADJUST").value = NTC("Amt_SalaryOwner~FINAL") - NTC("Amt_SalaryOwner~BASE");
			SetSpan("OwnerSalaryMsg", 
			"The owner’s salary has been auto-loaded into the \"adjusted income statement\" " + 
			"column of this line-item for you. If you make any changes to any of the data " + 
			"fields on this line-item, it will remove the auto entry and you will be required "+
			"to make all future desired adjustments to this line-item by using the standard " +
			"adjustment methods.");
		}
	}
}

function ValidateBudgetInput(txtBoxName , lblName)
{
	if(TC(txtBoxName) !=null)
		{
			var contVal = TC(txtBoxName).value;
			
			if (contVal =="")
				{
				return ; // ok if the value is empty
				}
			
			if(!IsNumeric(contVal))
				{
				alert ('Enter numeric value for ' + lblName);
				}	
		}
}

function IsNumeric(sText)
{
   // * IssueID 03213 PDC 05/29/2007
   //var ValidChars="0123456789.";
   var ValidChars="0123456789.-";
   var IsNumber=true;
   var Char;

	if (sText=="")
		IsNumber= false;

   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}


function ShowHelp()
{
	var option = 'toolbar=0,location=0,directories=0,status=0,' +
				  'menubar=0,scrollbars=1,resizable=1,width=400,height=400,left=200,top=250'

	popUp = window.open('../Help.aspx', 'popupproj', option);
	

}//Show/ hide each FAQ
function ShowHide(id)
{		
	var divId ="div"+id;
	var imgId= "img"+id;
	
	if (document.getElementById(divId))
	{
		obj = document.getElementById(divId);
		if (obj.style.display == "none")
		{
			obj.style.display = "";
			document.images[imgId].src="../images/minus.gif";
			
		} 
		else 
		{
			obj.style.display = "none";
			document.images[imgId].src="../images/plus.gif";
		}
	}
}


//Show/hide all topics at once
function ShowHideAll(ExpColpButton, LastIndex)
{
	var ExpColpVal = ExpColpButton.value;
				
	for (id = 1; id <= LastIndex; id++)
		{
			var divId ="div"+id;
			var imgId= "img"+id;
			
			if (document.getElementById(divId))
			{
				obj = document.getElementById(divId);
				if (ExpColpVal=="Expand All")
				{
					obj.style.display = "";
					document.images[imgId].src="../images/minus.gif";
				}
				else
				{
					obj.style.display = "none";
					document.images[imgId].src="../images/plus.gif";
				}
			}
		}	
		if (ExpColpVal=="Expand All")
			ExpColpButton.value ="Collapse All";
		else
			ExpColpButton.value ="Expand All";
}

//Show hide FAQs under a topic
function ShowHideGroup(id)
{		
	var divId ="Div_GRP"+id;
	var imgId= "Img_GRP"+id;
		if (document.getElementById(divId))
		{
			obj = document.getElementById(divId);
			if (obj.style.display == "none")
			{
				obj.style.display = "";
				document.images[imgId].src="../images/minus.gif";	
			} 
			else 
			{
				obj.style.display = "none";
				document.images[imgId].src="../images/plus.gif";
			}
		}
}



var timerID = 0;
var tRemaining =null;

function UpdateTimer() 
{	
	///////////////////////
		//commented: mar 29/06
		//to remove auto saving before session time out
	///////////////////////
	
	//save before 10 seconds
	/*if (tRemaining>0 && (tRemaining/1000)<10)
	{
		if (document.location.pathname.toLowerCase().indexOf("desktopdefault") ==-1)
		{
		__doPostBack('Header2$lnkLogOff','');
		
		//logoffPath =document.location.protocol + "//"+ document.location.hostname +"/"+ document.location.pathname.split("/")[1];
		//window.location = logoffPath + "/LogOff.aspx";
		}	
		Stop();	
	}
	
else */	if ( tRemaining < 0)
	{
			
		Stop();
	}

   else
   {		
		var   tTimtOut = new Date()
		var	  hdnLstActiv =document.getElementById('hdnLastActivity').value;
		var	  hdnTimeOut =document.getElementById('hdnTimeOut').value;	
		var	  tLstActiv = new Date(hdnLstActiv);
		var   tDate = new Date();
		var	  theTimebox = document.getElementById('theTime');

		tTimtOut.setMinutes(hdnTimeOut);		
		tRemaining = tTimtOut *60000 -  (tDate.getTime()- tLstActiv.getTime());	
		
		tDate.setTime(tRemaining);		
		theTimebox.value =   tDate.getMinutes() + ":" + tDate.getSeconds();
		timerID = setTimeout("UpdateTimer()", 1000);		
	}

}

function StartTimer() 
{
   var theTimebox = document.getElementById('theTime');
   if(typeof(theTimebox) != "undefined") 
   {
		tStart   = new Date();
		theTimebox.value = "00:00";
		timerID  = setTimeout("UpdateTimer()", 1000);
   }
}

function Stop() 
{
   var theTimebox = document.getElementById('theTime');
   if(timerID) 
   {
      clearTimeout(timerID);
      theTimebox.value = "00:00";
      timerID  = 0;
   }
   tStart = null;
}

//Hide session count down, for shopping card, forgotpassword and promotional user entry pages
function HideTimeOut()
{
	//The row is already hide in header control's .aspx file
		//TimeOutInfoRow.style.visibility = 'hidden';
}

function ShowPTMsg( messageText ) {
// Display page tranisition message
	if(typeof(divPageTransition) != "undefined") {
		divPageTransition.innerText = messageText;
		divPageTransition.style.visibility = 'visible';
	}
}

function HidePTMsg( ) {
// Hide page tranisition message
	divPageTransition.innerText = '';
	divPageTransition.style.visibility = 'hidden';
	
}


// * IssueID PDC002 PPDC 03/29/2007
function HideProgressBar( ) {
	document.getElementById("Progress_d1").innerHTML="";
	document.getElementById("Progress_d2").style.width=0;
	divProgressBar.innerText = '';
	divProgressBar.style.visibility = 'hidden';
}

// * IssueID PDC002 PPDC 03/29/2007
function ShowProgressBar(iQty)
{
	m_iProgressQty = iQty;
	m_iProgressCurrent=0;
	divProgressBar.style.visibility = 'visible';
}

// * IssueID PDC002 PPDC 03/29/2007
function UpdateProgressBar()
{
	if (m_iProgressCurrent<=(m_iProgressQty))
	{
		if (m_iProgressCurrent/m_iProgressQty>.15)
		{
			// * No percentages
			//document.getElementById("Progress_d1").innerHTML=parseInt(m_iProgressCurrent/(m_iProgressQty/100))+"%";
			document.getElementById("Progress_d1").innerHTML="";
		}
	    document.getElementById("Progress_d2").style.width=(m_iProgressCurrent/(m_iProgressQty/100))*3+"px";
		m_iProgressCurrent++;
   }
}
	

function AutoSave(MilliSeconds)
{
	window.setInterval('SaveData()', MilliSeconds)
}

var showAutoSaveMsg = true;

function SaveData()
{
	if(!m_bInitializing) {
		if (typeof(SmartScroller_GetCoords) == 'function')
			SmartScroller_GetCoords();
		var autoBtn = document.getElementById('btnAutoSave');
		if (autoBtn && autoBtn.click)
			autoBtn.click();
		//document.forms["Form1"].submit();
		if(showAutoSaveMsg) {
			ShowPTMsg('Autosaving...');
		}
	}
}

// Added by JJF 4/15/2008
var isNN = document.layers ? true : false;
var isIE = document.all ? true : false;
var mouseX;
var mouseY;
var lastOpen = "";

// * PDC 01/14/2009 IssueID 03732
var isCR = navigator.userAgent.toLowerCase().indexOf("chrome") > -1;

// Added by JJF 5/2/2008
function getASPElement(fldID) {
	id = ClientIDTable[fldID];
	element = document.getElementById(id);
	return element;
}

function changeAdjustBudgetLineItemsBy(changeTo) {
	oldValue = document.getElementById("AdjustBudgetLineItemsBy~RADVALUE").value;
	radio = getASPElement("AdjustBudgetLineItemsBy");
	switch(changeTo) {
		case "LineItem":
			if(confirm("If you continue, the automated entries made to the fixed cost category line items will be cleared.  Do you want to continue?")) {
				for(i=0; i<document.forms[0].elements.length; i++) {
					if (document.forms[0].elements[i].name.indexOf("_FX") > -1) {
						document.forms[0].elements[i].value = "";
					}
				}
				showAutoSaveMsg=false;
				SaveData();
			} else {
				if(oldValue == "Category") {
					getASPElement("AdjustBudgetLineItemsBy").checked = true;
				} else {
					getASPElement("AdjustBudgetLineItemsBy~RAD1").checked = true;
				}
			}
			break;
		
		case "Category":
			if(confirm("If you continue, all of the existing fixed cost category line item entries will be cleared and each line item will be replaced with the fixed cost category percentage adjustment selected.  Before continuing you can print the page to make a record of your line item entries. Do you want to continue?")) {
				showAutoSaveMsg=false;
				SaveData();
			} else {
				if(oldValue == "Category") {
					getASPElement("AdjustBudgetLineItemsBy").checked = true;
				} else {
					getASPElement("AdjustBudgetLineItemsBy~RAD1").checked = true;
				}
			}		
			break;
	}
}

// Added by JJF 4/15/2008
function getPageSizeWithScroll(){     
	if (window.innerHeight && window.scrollMaxY) {// Firefox         
		yWithScroll = window.innerHeight + window.scrollMaxY;         
		xWithScroll = window.innerWidth + window.scrollMaxX;     
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac         
		yWithScroll = document.body.scrollHeight;         
		xWithScroll = document.body.scrollWidth;    
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari         
		yWithScroll = document.body.offsetHeight;         
		xWithScroll = document.body.offsetWidth;       
	}     
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);    
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );     
	return arrayPageSizeWithScroll; 
}
 
if(window.location.href.indexOf("#") > -1) {
	window.onscroll=function() { window.scrollTo(0,0) }
}

function hideDiv(id) {
	document.getElementById(id).style.display = "none";
	var field = id.replace("~CPANEL", "~COMMENT");
	var defaultFld = id.replace("~CPANEL", "~DEFAULT");
	
	try {
		var defaultValue = document.getElementById(defaultFld).value;
		var targetField;
		for(i=0; i<document.forms[0].elements.length; i++) {
			if (document.forms[0].elements[i].name.indexOf(field) > -1) {
				targetField = document.forms[0].elements[i];
			}
		}
		targetField.value = defaultValue;
	} catch(e) {
	
	}
}

function showDiv(id) {
	mouseX = domTT_mousePosition.get('x');
	mouseY = domTT_mousePosition.get('y');

	if(lastOpen != "") {
		hideDiv(lastOpen);
	}
	
	var scrollContent = document.getElementById('divContent').scrollTop;
	var pgSize = getPageSizeWithScroll();
	
	//alert("mouseX:" + mouseX + " mouseY:" + mouseY + " docScroll:" + scrollTop + " conScroll:" + scrollContent);	
	
	// * PDC 01/14/2009 IssueID 03732	
	if (!isCR)
	{
		document.getElementById(id).style.top = mouseY + scrollContent - 275; //(mouseX + scrollContent + scrollTop) - 350;
		document.getElementById(id).style.left = pgSize[0] - 500;
		document.getElementById(id).style.display = "";
	} else
	{
		document.getElementById(id).style.top = mouseY - 50;
		document.getElementById(id).style.left = pgSize[0] - 500;
		document.getElementById(id).style.display = "";
	}
	
	lastOpen = id;
}

// JJF - Added "automatic clear column" feature to prevent multiple inputs
function changeBudgetAdjustment(fldID, fldSuffix) {
	if(!m_bInitializing) {
		// Locate adjustment fields in current row
		id = (fldID + "~ADJUST").split("|");
		id = ClientIDTable[id[1]];
		adjustment = document.getElementById(id);
		
		id = (fldID + "~ADJUST_PCT").split("|");
		id = ClientIDTable[id[1]];
		adjust_pct = document.getElementById(id);
		
		id = (fldID + "~PERCENT").split("|");
		id = ClientIDTable[id[1]];
		indHisPercent = document.getElementById(id);
		
		id = (fldID + "~PERCENT_REVENUE").split("|");
		id = ClientIDTable[id[1]];
		pct_revenue = document.getElementById(id);	
		
		id = (fldID + fldSuffix).split("|");
		id = ClientIDTable[id[1]];
		curField = document.getElementById(id);
			
		if(curField.value != "") {
			switch(fldSuffix) {
				case "~ADJUST":
					adjust_pct.value = "";
					indHisPercent.value = "";
					pct_revenue.value = "";
					break;
					
				case "~ADJUST_PCT":
					adjustment.value = "";
					indHisPercent.value = "";
					pct_revenue.value = "";
					break;
					
				case "~PERCENT":
					adjustment.value = "";
					adjust_pct.value = "";
					pct_revenue.value = "";
					break;
					
				case "~PERCENT_REVENUE":
					adjustment.value = "";
					adjust_pct.value = "";
					indHisPercent.value = "";
					break;									
			}
		}
	}
}

// JJF 7/3/2008 - Added "automatic clear column" feature to prevent multiple inputs
function changeIncomeAdjustment(fldID, fldSuffix) {
	if(!m_bInitializing) {
		// Locate adjustment fields in current row
		id = (fldID + "~ADJUST").split("|");
		id = ClientIDTable[id[1]];
		adjustment = document.getElementById(id);
		
		id = (fldID + "~PERCENT").split("|");
		id = ClientIDTable[id[1]];
		indHisPercent = document.getElementById(id);
		
		id = (fldID + fldSuffix).split("|");
		id = ClientIDTable[id[1]];
		curField = document.getElementById(id);
			
		if(curField.value != "") {
			switch(fldSuffix) {
				case "~ADJUST":
					indHisPercent.value = "";
					break;
					
				case "~PERCENT":
					adjustment.value = "";
					break;								
			}
		}
	}
}


