var CAChartXMLObject;

var CAAccountingOptions = Array(2)
CAAccountingOptions[0] = Array('Change in real (' + baseYear + ') dollars', 'Change in nominal dollars', 'Change as % of real outlays', ' Change as % of nominal outlays');
CAAccountingOptions[1] = Array('Real','Nominal','RealPercent','NominalPercent');

function initCAPage (transport) {
	var i;
	var j;
	var year;
	var currentYear = currentDate.getFullYear();
	var newCAPage = transport.responseXML.getElementsByTagName('div')[0];
	var chngAnalysisDiv = $('CAPage');
	
	copyXMLToDOM (newCAPage,chngAnalysisDiv);

	//Build the option selection menu.
	var optionSelector = $('CATypeSelector');
	optionSelector.appendChild(document.createTextNode("Show the change in the outlays of ..."));
	optionSelector.appendChild(document.createElement('br'));
	optionSelector.appendChild(document.createElement('br'));
	var optionForm = new Element('form', {'name':'CAOptionForm'});
	optionSelector.appendChild(optionForm);
	var largestDiv = new Element('div', {'id':'CALargestTextDiv'});
	largestDiv.appendChild(new Element('input', {'type':'radio', 'name':'CAOption', 'value':'largest', 'checked':true}));
	largestDiv.appendChild(document.createTextNode(" ... the 10 largest agencies"));
	optionForm.appendChild(largestDiv);
	optionForm.appendChild(document.createElement('br'));
	var largestGainDiv = new Element('div', {'id':'CALargestGainTextDiv'});
	largestGainDiv.appendChild(new Element('input', {'type':'radio', 'name':'CAOption', 'value':'biggestGain'}));
	largestGainDiv.appendChild(document.createTextNode(" ... the 10 agencies with the largest real dollar increase"));
	optionForm.appendChild(largestGainDiv);
	optionForm.appendChild(document.createElement('br'));
	var largestLossDiv = new Element('div', {'id':'CALargestLossTextDiv'});
	largestLossDiv.appendChild(new Element('input', {'type':'radio', 'name':'CAOption', 'value':'biggestLoss'}));
	largestLossDiv.appendChild(document.createTextNode(" ... the 10 agencies with the largest real dollar decrease"));
	optionForm.appendChild(largestLossDiv);
	optionForm.appendChild(document.createElement('br'));
	var CASelectItemsButtonDiv = new Element('div', {'id':'CASelectItemsButtonDiv'});
	CASelectItemsButtonDiv.appendChild(new Element('input', {'type':'radio', 'name':'CAOption', 'value':'selectItems'}));
	CASelectItemsButtonDiv.appendChild(document.createTextNode(" ... up to 15 items of your choosing"));
	CASelectItemsButtonDiv.appendChild(document.createElement('br'));
	CASelectChartToggleButton = new Element('p', {'style':'text-align:center'});
	CASelectChartToggleButton.appendChild(new Element('input', {'id':'CASelectChartToggle', 'type':'button', 'value':'Show chart', 'style':'cursor:pointer'}));
	CASelectItemsButtonDiv.appendChild(CASelectChartToggleButton);
	optionForm.appendChild(CASelectItemsButtonDiv);
	
	optionForm.onclick=function(){changeOption(this)};
	$('CASelectChartToggle').onclick=processCASelectToggle;
	$('showCASelectionChartButton').onclick=processCASelectToggle;
	
	//Build the time frame selection menu.
	var timeFrameSelector = $('CATimeFrameSelector');
	timeFrameSelector.appendChild(document.createTextNode("Set the calculation time frame:"));
	timeFrameSelector.appendChild(document.createElement('br'));
	timeFrameSelector.appendChild(document.createElement('br'));
	var timeFrameForm = new Element('form', {'name':'CATimeFrameForm'});
	timeFrameSelector.appendChild(timeFrameForm);
	timeFrameForm.appendChild(new Element('input', {'type':'radio', 'name':'CATimeFrame', 'value':'current', 'checked':true}));
	timeFrameForm.appendChild(document.createTextNode(" Current fiscal year to next fiscal year"));
	timeFrameForm.appendChild(document.createElement('br'));
	timeFrameForm.appendChild(document.createElement('br'));
	timeFrameForm.appendChild(new Element('input', {'type':'radio', 'name':'CATimeFrame', 'value':'presAdmin'}));
	timeFrameForm.appendChild(document.createTextNode(" Choose a presidential administration"));
	timeFrameForm.appendChild(document.createElement('br'));
	//Build the presidential administration menu.
	var presAdminForm = new Element('form', {'name':'presAdminForm', 'id':'presAdminForm'});
	timeFrameForm.appendChild(presAdminForm);
	var presAdminMenu = new Element('select', {'name':'presAdminMenu', 'id':'presAdminMenu', 'class':'ddmenu'});
	presAdminForm.appendChild(presAdminMenu);
	for (i=0;i<presidentialAdmins.length;i++) {
		presAdminMenu.appendChild(new Element('option'));
		presAdminMenu.options[i].text = presidentialAdmins[i].firstChild.nodeValue;
		presAdminMenu.options[i].setAttribute('startYear',Math.max(presidentialAdmins[i].getAttribute('start'),1962));
		presAdminMenu.options[i].setAttribute('endYear',presidentialAdmins[i].getAttribute('end'));
	}
	presAdminMenu.disable();
	presAdminMenu.onchange = function(){changePresAdmin(this)};
	
	timeFrameForm.appendChild(document.createElement('br'));
	timeFrameForm.appendChild(new Element('input', {'type':'radio', 'name':'CATimeFrame', 'value':'custom'}));
	timeFrameForm.appendChild(document.createTextNode(" Set a custom time frame"));
	timeFrameForm.appendChild(document.createElement('br'));
	//Build the custome time frame menus.
	var customTimeTable = new Element('table');
	timeFrameForm.appendChild(customTimeTable);
	customTimeTable.appendChild(new Element('tr'));
	customTimeTable.firstChild.appendChild(new Element('td'));
	var timeFromForm = new Element('form', {'name':'timeFromForm', 'id':'timeFromForm'});
	customTimeTable.firstChild.firstChild.appendChild(timeFromForm);
	timeFromForm.appendChild(document.createTextNode("From:"));
	var timeFromMenu = new Element('select', {'name':'timeFromMenu', 'id':'timeFromMenu'});
	timeFromForm.appendChild(timeFromMenu);
	for (year=1962;year<=currentYear;year++) {
		timeFromMenu.appendChild(new Element('option'));
		timeFromMenu.options[year-1962].text =  year+'';
		timeFromMenu.options[year-1962].value = year;
		if (year==currentYear) {
			timeFromMenu.options[year-1962].selected = true;
		} else {
			timeFromMenu.options[year-1962].selected = false;
		}
	}
	timeFromMenu.disable();
	timeFromMenu.onchange = function(){changeCustomTimeFrame(this)};
	
	customTimeTable.firstChild.appendChild(new Element('td'));
	var timeToForm = new Element('form', {'name':'timeToForm', 'id':'timeToForm'});
	customTimeTable.firstChild.childNodes[1].appendChild(timeToForm);
	timeToForm.appendChild(document.createTextNode("To:"));
	var timeToMenu = new Element('select', {'name':'timeToMenu', 'id':'timeToMenu'});
	timeToForm.appendChild(timeToMenu);
	for (year=currentYear+1;year<=2015;year++) {
		timeToMenu.appendChild(new Element('option'));
		timeToMenu.options[year-currentYear-1].text =  year+'';
		timeToMenu.options[year-currentYear-1].value = year;
		if (year==currentYear+1) {
			timeToMenu.options[year-currentYear-1].selected = true;
		} else {
			timeToMenu.options[year-currentYear-1].selected = false;
		}
	}
	timeToMenu.disable();
	timeToMenu.onchange = function(){changeCustomTimeFrame(this)};
	
	timeFrameForm.onclick=function(){changeTimeFrame(this)};
	
	//Build the chart options selectors.
	//Start with the accounting options.
	var accountingArea = $('CAAccounting');
	var accountingForm = new Element("form");
	accountingArea.appendChild(accountingForm);
	var accountingMenu = new Element("select", {'id': 'CAaccountingMenu'});
	accountingForm.appendChild(accountingMenu);
	
	for (i=0; i<CAAccountingOptions[0].length; i++) {
		accountingMenu.appendChild(new Element("option"));
		accountingMenu.options[i].text = CAAccountingOptions[0][i];
		accountingMenu.options[i].value = CAAccountingOptions[1][i];
	}
	accountingMenu.onchange=function(){changeCAAccounting(this)};
	
	//Set up the agency vs. function selector.
	var itemTypeArea = $('CAItemTypeSelector');
	var itemTypeForm = new Element("form");
	itemTypeArea.appendChild(itemTypeForm);
	var itemTypeMenu = new Element("select", {'id': 'CAitemTypeMenu'});
	itemTypeForm.appendChild(itemTypeMenu);
	
	itemTypeMenu.appendChild(new Element("option"));
	itemTypeMenu.options[0].text = 'Agencies';
	itemTypeMenu.options[0].value = 'agencies';
	
	itemTypeMenu.appendChild(new Element("option"));
	itemTypeMenu.options[1].text = 'Functions';
	itemTypeMenu.options[1].value = 'functions';

	itemTypeMenu.onchange=function(){changeCAItemType(this)};
	
	initCASelectorDiv ();
	
	$('CASelectItemDiv').hide();
	$('CASelectChartToggle').hide();

	//Now set the global page variable to indicate the page has been initialized.
	for (i=0;i<pageDivIds[0].length;i++) {
		if (pageDivIds[0][i] == 'CAPage') {
			pageDivIds[1][i] = true;
		}
	}
}

function refreshCAChart(loadchart) {
	var i;
	var chartObject = CAChartXMLObject.getElementsByTagName('chart')[0];
	
	var CAXMLString = convertXMLObjectToChartString(chartObject);

	if (loadchart) {
		var CAChart = new FusionCharts("./FusionCharts/MSBar3D.swf", "CAChartID", "638","500","0","1");
		CAChart.setDataXML(CAXMLString);
		CAChart.render("changeAnalysisChart");
	} else {
		var CAChart = getChartFromId(CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeChart'));
		CAChart.setDataXML(CAXMLString);
	}
}

function initializeCAChart (transport) {
	var i;
	var j;
	var startCPI;
	var endCPI;
	var startGDP;
	var endGDP;
	var economicDataItems = economicData.getElementsByTagName("economicStat");
	
	var chartData = transport.responseXML;
	
	var agencyData = chartData.getElementsByTagName('agency');
	
	CAChartXMLObject = convertStringToXMLDOMObject("<CAChartData></CAChartData>");
	
	var CAChartInfo = CAChartXMLObject.createElement("CAChartInfo");
	CAChartXMLObject.firstChild.appendChild(CAChartInfo);
	CAChartInfo.setAttribute('id','CAChartInfo');
	CAChartInfo.setAttribute('activeChart','CAChartID');
	CAChartInfo.setAttribute('activeChartDiv','changeAnalysisChart');
	CAChartInfo.setAttribute('activeOption','largest');
	CAChartInfo.setAttribute('activeTimeFrameOption','current');
	CAChartInfo.setAttribute('itemType','agencies');
	CAChartInfo.setAttribute('startYear',2010);
	CAChartInfo.setAttribute('endYear',2011);
	CAChartInfo.setAttribute('itemTextLargest','the 10 largest agencies');
	CAChartInfo.setAttribute('itemTextLargestGain','the 10 agencies with the largest real dollar increase');
	CAChartInfo.setAttribute('itemTextLargestLoss','the 10 agencies with the largest real dollar decrease');
	
	for (i=0;i<economicDataItems.length && economicDataItems[i].getAttribute('year') != baseYear;i++);
	CAChartInfo.setAttribute('baseCPI',economicDataItems[i].getAttribute('CPI'));
	
	//Create the chart data
	var CAChartXMLData = CAChartXMLObject.createElement("chart");
	CAChartXMLObject.firstChild.appendChild(CAChartXMLData);
	
	//Set chart attributes.
	CAChartXMLData.setAttribute('caption','Change in outlays of the 10 largest agencies');
	CAChartXMLData.setAttribute('subCaption','Change from 2010 to 2011');
	CAChartXMLData.setAttribute('xAxisName','Agency');
	CAChartXMLData.setAttribute('yAxisName','Real (' + baseYear + ') Dollars');
	CAChartXMLData.setAttribute('numberPrefix','$');
	CAChartXMLData.setAttribute('bgColor','707E92');
	CAChartXMLData.setAttribute('bgAlpha','50');
	CAChartXMLData.setAttribute('baseFontSize','12');
	CAChartXMLData.setAttribute('baseFontColor','000000');
	CAChartXMLData.setAttribute('showBorder','1');
	CAChartXMLData.setAttribute('animation','1');
	CAChartXMLData.setAttribute('showValues','0');
	CAChartXMLData.setAttribute('formatNumberScale','1');
	CAChartXMLData.setAttribute('numberScaleValue','1000,1000,1000,1000');
	CAChartXMLData.setAttribute('numberScaleUnit','K,M,B,T');
	CAChartXMLData.setAttribute('decimals','2');
	CAChartXMLData.setAttribute('chartBottomMargin','20');
//	CAChartXMLData.setAttribute('logoURL','./images/copyright.png');
	CAChartXMLData.setAttribute('logoPosition','BR');
	CAChartXMLData.setAttribute('showAboutMenuItem','1');
	CAChartXMLData.setAttribute('aboutMenuItemLink','n-http://www.rpdanalytics.com');
	CAChartXMLData.setAttribute('aboutMenuItemLabel','About rpd | ANALYTICS');
	
/*	CAChartXMLData.setAttribute('logoURL','./images/samplescreens/revoutlays_political.png');
	CAChartXMLData.setAttribute('logoPosition','BR');
	CAChartXMLData.setAttribute('logoAlpha','50');
*/	
	//Create agency categories.
	var CAChartXMLCategories = CAChartXMLObject.createElement("categories");
	CAChartXMLData.appendChild(CAChartXMLCategories);
	
	for (i=0; i<agencyData.length; i++) {
		//Append category element.
		CAChartXMLCategories.appendChild(CAChartXMLObject.createElement('category'));
		CAChartXMLCategories.childNodes[CAChartXMLCategories.childNodes.length - 1].setAttribute('label',agencyData[i].firstChild.nodeValue);
	}
	
	//Create change analysis datasets.
	var CAChartDataNominal = CAChartXMLObject.createElement("dataset");
	CAChartDataNominal.setAttribute('id','CASeriesNominal');
	CAChartDataNominal.setAttribute('showInChart','0');
	CAChartXMLData.appendChild(CAChartDataNominal);
	var CAChartDataReal = CAChartXMLObject.createElement("dataset");
	CAChartDataReal.setAttribute('id','CASeriesReal');
	CAChartDataReal.setAttribute('showInChart','0');
	CAChartXMLData.appendChild(CAChartDataReal);
	var CAChartDataNominalPercent = CAChartXMLObject.createElement("dataset");
	CAChartDataNominalPercent.setAttribute('id','CASeriesNominalPercent');
	CAChartDataNominalPercent.setAttribute('showInChart','0');
	CAChartXMLData.appendChild(CAChartDataNominalPercent);
	var CAChartDataRealPercent = CAChartXMLObject.createElement("dataset");
	CAChartDataRealPercent.setAttribute('id','CASeriesRealPercent');
	CAChartDataRealPercent.setAttribute('showInChart','0');
	CAChartXMLData.appendChild(CAChartDataRealPercent);
	var CAChartDataGDP = CAChartXMLObject.createElement("dataset");
	CAChartDataGDP.setAttribute('id','CASeriesGDP');
	CAChartDataGDP.setAttribute('showInChart','0');
	CAChartXMLData.appendChild(CAChartDataGDP);
	
	//Get economic data.
	for (i=0;i<economicDataItems.length;i++) {
		if (economicDataItems[i].getAttribute('year') == CAChartInfo.getAttribute('startYear')) {
			startCPI = economicDataItems[i].getAttribute('CPI');
			startGDP = economicDataItems[i].getAttribute('GDP');
		} else if (economicDataItems[i].getAttribute('year') == CAChartInfo.getAttribute('endYear')) {
			endCPI = economicDataItems[i].getAttribute('CPI');
			endGDP = economicDataItems[i].getAttribute('GDP');
		}
	}
	
	//Populate series data.
	for (i=0; i<agencyData.length; i++) {
		//Append data elements.
		CAChartDataNominal.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataNominal.childNodes[i].setAttribute('value',agencyData[i].getAttribute('endValue') - agencyData[i].getAttribute('startValue'));
		CAChartDataReal.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataReal.childNodes[i].setAttribute('value',(agencyData[i].getAttribute('endValue')/endCPI - agencyData[i].getAttribute('startValue')/startCPI)*CAChartInfo.getAttribute('baseCPI'));
		if(agencyData[i].getAttribute('startValue') != 0) {
			CAChartDataNominalPercent.appendChild(CAChartXMLObject.createElement('set'));
			CAChartDataNominalPercent.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))-1));
			CAChartDataRealPercent.appendChild(CAChartXMLObject.createElement('set'));
			CAChartDataRealPercent.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))*(startCPI/endCPI)-1));
			CAChartDataGDP.appendChild(CAChartXMLObject.createElement('set'));
			CAChartDataGDP.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))*(startGDP/endGDP)-1));
		}
		
		CAChartDataNominal.childNodes[i].setAttribute('color',(CAChartDataNominal.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataReal.childNodes[i].setAttribute('color',(CAChartDataReal.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataNominalPercent.childNodes[i].setAttribute('color',(CAChartDataNominalPercent.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataRealPercent.childNodes[i].setAttribute('color',(CAChartDataRealPercent.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataGDP.childNodes[i].setAttribute('color',(CAChartDataGDP.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
	}
	
	CAChartDataReal.setAttribute('showInChart','1');
	
	//Now set the global page variable to indicate the data structure has been initialized.
	for (i=0;i<pageDivIds[0].length;i++) {
		if (pageDivIds[0][i] == 'CAPage') {
			pageDivIds[2][i] = true;
		}
	}
}

function updateCAChart (chartData) {
	var i;
	var j;
	var startCPI;
	var endCPI;
	var startGDP;
	var endGDP;
	var economicDataItems = economicData.getElementsByTagName("economicStat");
	var CAChartInfo = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0];
	
	var agencyData = chartData.getElementsByTagName('agency');
	
	//Get economic data.
	for (i=0;i<economicDataItems.length;i++) {
		if (economicDataItems[i].getAttribute('year') == CAChartInfo.getAttribute('startYear')) {
			startCPI = economicDataItems[i].getAttribute('CPI');
			startGDP = economicDataItems[i].getAttribute('GDP');
		} else if (economicDataItems[i].getAttribute('year') == CAChartInfo.getAttribute('endYear')) {
			endCPI = economicDataItems[i].getAttribute('CPI');
			endGDP = economicDataItems[i].getAttribute('GDP');
		}
	}
	
	//Get agency category list.
	var CAChartXMLCategories = CAChartXMLObject.getElementsByTagName("categories")[0];
	
	//Remove existing categories.
	removeAllChildren(CAChartXMLCategories);
	
	//Get change analysis datasets and remove child nodes.
	CAChartDatasets = CAChartXMLObject.getElementsByTagName("dataset");
	for (i=0; i<CAChartDatasets.length; i++) {
		removeAllChildren(CAChartDatasets[i]);
		switch (CAChartDatasets[i].getAttribute('id')) {
			case 'CASeriesNominal':
				var CAChartDataNominal = CAChartDatasets[i];
				break;
			case 'CASeriesReal':
				var CAChartDataReal = CAChartDatasets[i];
				break;
			case 'CASeriesNominalPercent':
				var CAChartDataNominalPercent = CAChartDatasets[i];
				break;
			case 'CASeriesRealPercent':
				var CAChartDataRealPercent = CAChartDatasets[i];
				break;
			case 'CASeriesGDP':
				var CAChartDataGDP = CAChartDatasets[i];
				break;
		}
	}
	
	//Populate category and data sets.
	for (i=0; i<agencyData.length; i++) {
		//Append category element.
		CAChartXMLCategories.appendChild(CAChartXMLObject.createElement('category'));
		if (agencyData[i].firstChild.nodeValue.length > 35) {
			CAChartXMLCategories.childNodes[CAChartXMLCategories.childNodes.length - 1].setAttribute('label',agencyData[i].firstChild.nodeValue.substr(0,34) + ' ...');
		} else {
			CAChartXMLCategories.childNodes[CAChartXMLCategories.childNodes.length - 1].setAttribute('label',agencyData[i].firstChild.nodeValue);
		}
		
		//Append data elements.
		CAChartDataNominal.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataNominal.childNodes[i].setAttribute('value',agencyData[i].getAttribute('endValue') - agencyData[i].getAttribute('startValue'));
		CAChartDataReal.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataReal.childNodes[i].setAttribute('value',(agencyData[i].getAttribute('endValue')/endCPI - agencyData[i].getAttribute('startValue')/startCPI)*CAChartInfo.getAttribute('baseCPI'));
		CAChartDataNominalPercent.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataRealPercent.appendChild(CAChartXMLObject.createElement('set'));
		CAChartDataGDP.appendChild(CAChartXMLObject.createElement('set'));
		if(agencyData[i].getAttribute('startValue') > 0 && agencyData[i].getAttribute('endValue') > 0) {
			CAChartDataNominalPercent.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))-1));
			CAChartDataRealPercent.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))*(startCPI/endCPI)-1));
			CAChartDataGDP.childNodes[i].setAttribute('value',100*((agencyData[i].getAttribute('endValue')/agencyData[i].getAttribute('startValue'))*(startGDP/endGDP)-1));
		} else {
			CAChartDataNominalPercent.childNodes[i].setAttribute('value',0);
			CAChartDataNominalPercent.childNodes[i].setAttribute('showValue',1);
			CAChartDataNominalPercent.childNodes[i].setAttribute('displayValue','Undefined');
			CAChartDataRealPercent.childNodes[i].setAttribute('value',0);
			CAChartDataRealPercent.childNodes[i].setAttribute('showValue',1);
			CAChartDataRealPercent.childNodes[i].setAttribute('displayValue','Undefined');
			CAChartDataGDP.childNodes[i].setAttribute('value',0);
			CAChartDataGDP.childNodes[i].setAttribute('showValue',1);
			CAChartDataGDP.childNodes[i].setAttribute('displayValue','Undefined');
			if (agencyData[i].getAttribute('startValue') == 0) {
				CAChartDataNominalPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to zero initial outlays');
				CAChartDataRealPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to zero initial outlays');
				CAChartDataGDP.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to zero initial outlays');
			} else if (agencyData[i].getAttribute('startValue') < 0) {
				CAChartDataNominalPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative initial outlays');
				CAChartDataRealPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative initial outlays');
				CAChartDataGDP.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative initial outlays');
			} else if (agencyData[i].getAttribute('endValue') < 0) {
				CAChartDataNominalPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative final outlays');
				CAChartDataRealPercent.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative final outlays');
				CAChartDataGDP.childNodes[i].setAttribute('toolText',agencyData[i].firstChild.nodeValue + ', Undefined due to negative final outlays');
			}
		}
			
		CAChartDataNominal.childNodes[i].setAttribute('color',(CAChartDataNominal.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataReal.childNodes[i].setAttribute('color',(CAChartDataReal.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataNominalPercent.childNodes[i].setAttribute('color',(CAChartDataNominalPercent.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataRealPercent.childNodes[i].setAttribute('color',(CAChartDataRealPercent.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
		CAChartDataGDP.childNodes[i].setAttribute('color',(CAChartDataGDP.childNodes[i].getAttribute('value') < 0 ? 'B00000' : '344B6D'));
	}
	
	//Now reset the global page variable to indicate the data structure has been re-populated.
	for (i=0;i<pageDivIds[0].length;i++) {
		if (pageDivIds[0][i] == 'CAPage') {
			pageDivIds[2][i] = true;
		}
	}
}

function changePresAdmin (presAdminMenu) {
	var startYear = presAdminMenu.options[presAdminMenu.selectedIndex].getAttribute('startYear');
	var endYear = presAdminMenu.options[presAdminMenu.selectedIndex].getAttribute('endYear');
	var analysisOption = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeOption');
	var itemType = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('itemType');
	
	CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('subCaption','Change during the administration of ' + presAdminMenu.options[presAdminMenu.selectedIndex].text);
	updateCustomTimeFrameMenus(startYear,endYear);
	
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('startYear',startYear);
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('endYear',endYear);
	
	if (analysisOption == 'selectItems') {
		processCASelections (false);
	} else {
		new Ajax.Request ("./phpscripts/getCAdata.php", {
						  parameters: {sessionID: sessionID, analysisID: "CAChartData", startYear: startYear, endYear: endYear, itemType: itemType, category: 'outlays', analysisOption: analysisOption},
						  onSuccess: function(transport) {
						  updateCAChart(transport.responseXML);
						  refreshCAChart(false);
						  },
						  onFailure: function(){ alert('Something went wrong...') }
						  });
	}
}

function changeCustomTimeFrame (customTimeMenu) {
	var startYear = $('timeFromMenu').options[$('timeFromMenu').selectedIndex].value;
	var endYear = $('timeToMenu').options[$('timeToMenu').selectedIndex].value;
	var analysisOption = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeOption');
	var itemType = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('itemType');
	
	CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('subCaption','Change from ' + startYear + ' to ' + endYear);
	updateCustomTimeFrameMenus(startYear,endYear);
	
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('startYear',startYear);
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('endYear',endYear);
	
	if (analysisOption == 'selectItems') {
		processCASelections (false);
	} else {
		new Ajax.Request ("./phpscripts/getCAdata.php", {
						  parameters: {sessionID: sessionID, analysisID: "CAChartData", startYear: startYear, endYear: endYear, itemType: itemType, category: 'outlays', analysisOption: analysisOption},
						  onSuccess: function(transport) {
						  updateCAChart(transport.responseXML);
						  refreshCAChart(false);
						  },
						  onFailure: function(){ alert('Something went wrong...') }
						  });
	}
}

function changeTimeFrame (timeFrameForm) {
	var i;
	var startYear;
	var endYear;
	var currentYear = currentDate.getFullYear();
	var currentValue = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeTimeFrameOption');
	var analysisOption = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeOption');
	var itemType = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('itemType');
	var newValue;
	
	for (i=0;i<timeFrameForm.CATimeFrame.length;i++) {
		if (timeFrameForm.CATimeFrame[i].checked) {
			newValue=timeFrameForm.CATimeFrame[i].value;
			if (currentValue == newValue) return null;
		}
	}
	
	switch (newValue) {
		case 'current':
			startYear = currentYear;
			endYear = currentYear+1;
			CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('subCaption','Change from ' + startYear + ' to ' + endYear);
			$('presAdminMenu').disable();
			updateCustomTimeFrameMenus(startYear,endYear);
			$('timeFromMenu').disable();
			$('timeToMenu').disable();
			break;
		case 'presAdmin':
			startYear = $('presAdminMenu').options[$('presAdminMenu').selectedIndex].getAttribute('startYear');
			endYear = $('presAdminMenu').options[$('presAdminMenu').selectedIndex].getAttribute('endYear');
			CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('subCaption','Change during the administration of ' + $('presAdminMenu').options[$('presAdminMenu').selectedIndex].text);
			$('presAdminMenu').enable();
			updateCustomTimeFrameMenus(startYear,endYear);
			$('timeFromMenu').disable();
			$('timeToMenu').disable();
			break;
		case 'custom':
			startYear = $('timeFromMenu').options[$('timeFromMenu').selectedIndex].value;
			endYear = $('timeToMenu').options[$('timeToMenu').selectedIndex].value;
			CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('subCaption','Change from ' + startYear + ' to ' + endYear);
			$('presAdminMenu').disable();
			$('timeFromMenu').enable();
			$('timeToMenu').enable();
			break;
	}
	
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('activeTimeFrameOption',newValue);
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('startYear',startYear);
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('endYear',endYear);
	
	if (analysisOption == 'selectItems') {
		processCASelections (false);
	} else {
		new Ajax.Request ("./phpscripts/getCAdata.php", {
						  parameters: {sessionID: sessionID, analysisID: "CAChartData", startYear: startYear, endYear: endYear, itemType: itemType, category: 'outlays', analysisOption: analysisOption},
						  onSuccess: function(transport) {
						  updateCAChart(transport.responseXML);
						  refreshCAChart(false);
						  },
						  onFailure: function(){ alert('Something went wrong...') }
						  });
	}
}
	
function changeOption (optionForm) {
	var i;
	var CAChartInfo = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0];
	var itemType = CAChartInfo.getAttribute('itemType');
	var startYear = CAChartInfo.getAttribute('startYear');
	var endYear = CAChartInfo.getAttribute('endYear');

	var currentValue=CAChartInfo.getAttribute('activeOption');
	var newValue;
	
	for (i=0;i<optionForm.CAOption.length;i++) {
		if (optionForm.CAOption[i].checked) {
			newValue=optionForm.CAOption[i].value;
			if (currentValue == newValue) return null;
		}
	}

	CAChartInfo.setAttribute('activeOption',newValue);
	
	if (newValue == 'selectItems') {
		$('CAitemTypeMenu').disable();
		CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('caption', 'Change in outlays of selected items');
		if($('CASelectChartToggle').getAttribute('value') == 'Show chart') {
			$('changeAnalysisChart').hide();
			$('CASelectItemDiv').show();
		} else {
			processCASelections (true);
		}
		$('CASelectChartToggle').show();
	} else {
		$('CAitemTypeMenu').enable();
		$('CASelectItemDiv').hide();
		$('CASelectChartToggle').hide();
		$('changeAnalysisChart').show();
		switch (CAChartInfo.getAttribute('activeOption')) {
			case 'largest':
				CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargest'));
				break;
			case 'biggestGain':
				CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargestGain'));
				break;
			case 'biggestLoss':
				CAChartXMLObject.getElementsByTagName('chart')[0].setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargestLoss'));
				break;
		}
		
		new Ajax.Request ("./phpscripts/getCAdata.php", {
						  parameters: {sessionID: sessionID, analysisID: "CAChartData", startYear: startYear, endYear: endYear, itemType: itemType, category: 'outlays', analysisOption: newValue},
						  onSuccess: function(transport) {
						  updateCAChart(transport.responseXML);
						  refreshCAChart(false);
						  },
						  onFailure: function(){ alert('Something went wrong...') }
						  });
	}
}

function processCASelectToggle () {
	if ($('CASelectChartToggle').getAttribute('value') == 'Show chart') {
		if ($('numCASelectionsText').firstChild.nodeValue == '0') {
			alert("Please select items to chart.");
		} else {
			processCASelections (true);
			$('CASelectChartToggle').setAttribute('value','Change selections');
		}
	} else {
		$('changeAnalysisChart').hide();
		$('CASelectItemDiv').show();
		$('CASelectChartToggle').setAttribute('value','Show chart');
	}		
}

function processCASelections (loadchart) {
	var i;
	var numFunctions = 0;
	var functionList = '(';
	var numSubfunctions = 0;
	var subfunctionList = '';
	var numBranches = 0;
	var numAgencies = 0;
	var agencyList = '(';
	var numBureaus = 0;
	var bureauList = '';
	var CAChartInfo = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0];
	var startYear = CAChartInfo.getAttribute('startYear');
	var endYear = CAChartInfo.getAttribute('endYear');
	
	var CASelectTable = $('CASelectTable').getElementsByTagName('input');
	for (i=0;i<CASelectTable.length;i++) {
		if (CASelectTable[i].getAttribute('type') == 'checkbox' && CASelectTable[i].checked) {
			switch (CASelectTable[i].getAttribute('drillDown')) {
				case 'function':
					numFunctions++;
					functionList += (numFunctions > 1 ? ',' : '') + CASelectTable[i].getAttribute('functionCode');
					break;
				case 'subfunction':
					numSubfunctions++;
					subfunctionList += (numSubfunctions > 1 ? ' OR ' : '') + '(function_code = ' + CASelectTable[i].getAttribute('functionCode');
					subfunctionList += ' AND subfunction_code = ' + CASelectTable[i].getAttribute('subfunctionCode') + ')';
					break;
				case 'branch':
					if (CASelectTable[i].getAttribute('branchCode') == 'EB') {
						numBranches = 1;
					} else {
						numAgencies++;
						agencyList += (numAgencies > 1 ? ',' : '') + CASelectTable[i].getAttribute('branchCode');
					}
					break;
				case 'agency':
					numAgencies++;
					agencyList += (numAgencies > 1 ? ',' : '') + CASelectTable[i].getAttribute('agencyCode');
					break;
				case 'bureau':
					numBureaus++;
					bureauList += (numBureaus > 1 ? ' OR ' : '') + '(agency_code = ' + CASelectTable[i].getAttribute('agencyCode');
					bureauList += ' AND bureau_code = ' + CASelectTable[i].getAttribute('bureauCode') + ')';
					break;
			}
		}
	}
	
	functionList += ')';
	agencyList += ')';

	new Ajax.Request ("./phpscripts/getCAselectdata.php", {
					  parameters: {sessionID: sessionID, analysisID:"CAChartData", startYear:startYear, endYear:endYear, category:'outlays', numFunctions:numFunctions, functionList:functionList, numSubfunctions:numSubfunctions, subfunctionList:subfunctionList, numBranches:numBranches, numAgencies:numAgencies, agencyList:agencyList, numBureaus:numBureaus, bureauList:bureauList},
					  onSuccess: function(transport) {
					  updateCAChart(transport.responseXML);
					  $('CASelectItemDiv').hide();
					  $('changeAnalysisChart').show();
					  refreshCAChart(loadchart);
					  },
					  onFailure: function(){ alert('Something went wrong...') }
					  });
}

function resetCASelections () {
	var i;
	
	var CASelectTable = $('CASelectTable').getElementsByTagName('input');
	for (i=0;i<CASelectTable.length;i++) {
		if (CASelectTable[i].getAttribute('type') == 'checkbox') {
			CASelectTable[i].checked = false;
		}
	}
	$('numCASelectionsText').firstChild.nodeValue = 0;
}

function changeCAAccounting(myMenu) {
	var i;
	var chartObject = CAChartXMLObject.getElementsByTagName('chart')[0];
	var datasets = CAChartXMLObject.getElementsByTagName('dataset');
	var dataType = myMenu.options[myMenu.selectedIndex].value;
	var dataID = 'CASeries' + dataType;
	
	for (i=0;i<datasets.length;i++) {
		if (datasets[i].getAttribute('id') == dataID) {
			datasets[i].setAttribute('showInChart','1');
		} else {
			datasets[i].setAttribute('showInChart','0');
		}
	}
	
	if (dataType == 'Real' || dataType == 'Nominal') {
		if(chartObject.getAttribute('numberSuffix')) {
			chartObject.removeAttribute('numberSuffix');
		}
		chartObject.setAttribute('numberPrefix','$');
	} else {
		if(chartObject.getAttribute('numberPrefix')) {
			chartObject.removeAttribute('numberPrefix');
		}
		chartObject.setAttribute('numberSuffix','%25');
	}
	
	switch (dataType) {
		case 'Real':
			chartObject.setAttribute('yAxisName','Real (' + baseYear + ') Dollars');
			break;
		case 'Nominal':
			chartObject.setAttribute('yAxisName','Nominal Dollars');
			break;
		case 'RealPercent':
			chartObject.setAttribute('yAxisName','Percent Change in Real (' + baseYear + ') Dollars');
			break;
		case 'NominalPercent':
			chartObject.setAttribute('yAxisName','Percent Change in Nominal Dollars');
			break;
		case 'GDP':
			chartObject.setAttribute('yAxisName','Percent Change Relative to GDP');
			break;
	}
	
	refreshCAChart(false);
}

function changeCAItemType(myMenu) {
	var i;
	var startYear = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('startYear');
	var endYear = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('endYear');
	var currentValue=CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].getAttribute('activeOption');
	var CAChartInfo = CAChartXMLObject.getElementsByTagName('CAChartInfo')[0];
	var chartObject = CAChartXMLObject.getElementsByTagName('chart')[0];
	var itemType = myMenu.options[myMenu.selectedIndex].value;
		
	CAChartXMLObject.getElementsByTagName('CAChartInfo')[0].setAttribute('itemType',itemType);

	switch (itemType) {
		case 'agencies':
			CAChartInfo.setAttribute('itemTextLargest','the 10 largest agencies');
			CAChartInfo.setAttribute('itemTextLargestGain','the 10 agencies with the largest real dollar increase');
			CAChartInfo.setAttribute('itemTextLargestLoss','the 10 agencies with the largest real dollar decrease');
			break;
		case 'functions':
			CAChartInfo.setAttribute('itemTextLargest','the 10 largest functions');
			CAChartInfo.setAttribute('itemTextLargestGain','the 10 functions with the largest real dollar increase');
			CAChartInfo.setAttribute('itemTextLargestLoss','the 10 functions with the largest real dollar decrease');
			break;
	}
	
	$('CALargestTextDiv').removeChild($('CALargestTextDiv').childNodes[1]);
	$('CALargestTextDiv').appendChild(document.createTextNode(' ... ' + CAChartInfo.getAttribute('itemTextLargest')));
	$('CALargestGainTextDiv').removeChild($('CALargestGainTextDiv').childNodes[1]);
	$('CALargestGainTextDiv').appendChild(document.createTextNode(' ... ' + CAChartInfo.getAttribute('itemTextLargestGain')));
	$('CALargestLossTextDiv').removeChild($('CALargestLossTextDiv').childNodes[1]);
	$('CALargestLossTextDiv').appendChild(document.createTextNode(' ... ' + CAChartInfo.getAttribute('itemTextLargestLoss')));
	
	if (CAChartInfo.getAttribute('activeOption') == 'selectItems') {
		processCASelections (false);
	} else {
		switch (CAChartInfo.getAttribute('activeOption')) {
			case 'largest':
				chartObject.setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargest'));
				break;
			case 'biggestGain':
				chartObject.setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargestGain'));
				break;
			case 'biggestLoss':
				chartObject.setAttribute('caption', 'Change in outlays of ' + CAChartInfo.getAttribute('itemTextLargestLoss'));
				break;
		}
		
		new Ajax.Request ("./phpscripts/getCAdata.php", {
						  parameters: {sessionID: sessionID, analysisID: "CAChartData", startYear: startYear, endYear: endYear, itemType: itemType, category: 'outlays', analysisOption: currentValue},
						  onSuccess: function(transport) {
						  updateCAChart(transport.responseXML);
						  refreshCAChart(false);
						  },
						  onFailure: function(){ alert('Something went wrong...') }
						  });
	}
}

function updateCustomTimeFrameMenus (startYear, endYear) {
	var i;
	var currentMaxYear;
	var currentMinYear;

	var fromMenu = document.timeFromForm.timeFromMenu;
	var toMenu = document.timeToForm.timeToMenu;

	if (fromMenu.options[fromMenu.options.length-1].value >= endYear) {
		for (i=fromMenu.options.length-1;i>0 && fromMenu.options[i].value >= endYear;i--) {
			fromMenu.removeChild(fromMenu.options[i])
		}
	} else {
		currentMaxYear = fromMenu.options[fromMenu.options.length-1].value;
		for(i=1.0*currentMaxYear+1.0;i<endYear;i++) {
			fromMenu.appendChild(new Element('option'));
			fromMenu.options[fromMenu.options.length-1].text = i;
			fromMenu.options[fromMenu.options.length-1].value = i;
		}
	}
	if (toMenu.options[0].value <= startYear) {
		while (toMenu.options[0].value <= startYear) {
			toMenu.removeChild(toMenu.options[0])
		}
	} else {
		currentMinYear = toMenu.options[0].value;
		for(i=currentMinYear-1;i>startYear;i--) {
			toMenu.insertBefore(new Element('option'),toMenu.options[0]);
			toMenu.options[0].text = i;
			toMenu.options[0].value = i;
		}
	}
	
	for (i=0;i<fromMenu.options.length;i++) {
		if (fromMenu.options[i].value == startYear) {
			fromMenu.options[i].selected = true;
		} else {
			fromMenu.options[i].selected = false;
		}
	}
	for (i=0;i<toMenu.options.length;i++) {
		if (toMenu.options[i].value == endYear) {
			toMenu.options[i].selected = true;
		} else {
			toMenu.options[i].selected = false;
		}
	}
}

function initCASelectorDiv () {
	var i;
	var j;
	var year;
	var currentYear = currentDate.getFullYear();
	var subfunctionList;
	var newFunctionRow;
	var newFunctionChildRow;
	
	//Set the "reset" button handler function.
	$('resetCASelectionChartButton').onclick = resetCASelections;
	
	//Populate function list selector.
	var functionArea = $('functionListTable');
	var functionList = menuTree.getElementsByTagName('function');
	populateSelectorCells (functionArea, functionList);
	
	//Populate branch list selector.
	var branchArea = $('branchListTable');
	var branchList = menuTree.getElementsByTagName('branch');
	populateSelectorCells (branchArea, branchList);
	
	//Populate entity type selectors.
	var entityList = menuTree.getElementsByTagName('entityType');
	
	var EOPArea = $('EOPListTable');
	var EOPList = entityList[1].childNodes;
	populateSelectorCells (EOPArea, EOPList);
	
	var departmentArea = $('departmentListTable');
	var departmentList = entityList[2].childNodes;
	populateSelectorCells (departmentArea, departmentList);
	
	var independentAgencyArea = $('independentAgencyListTable');
	var independentAgencyList = entityList[3].childNodes;
	populateSelectorCells (independentAgencyArea, independentAgencyList);
	
	var currentCommissionArea = $('currentCommissionListTable');
	var currentCommissionList = entityList[4].childNodes;
	populateSelectorCells (currentCommissionArea, currentCommissionList);
	
	var unfundedEntityArea = $('unfundedEntityListTable');
	var unfundedEntityList = entityList[5].childNodes;
	populateSelectorCells (unfundedEntityArea, unfundedEntityList);
	
	var miscellaneousArea = $('miscellaneousListTable');
	var miscellaneousList = entityList[6].childNodes;
	populateSelectorCells (miscellaneousArea, miscellaneousList);
}

function populateSelectorCells (listArea, listElements) {
	var i;
	var j;
	var newItemRow;
	var newItemChildRow;
	
	for (i=0; i<listElements.length; i++) {
		newItemRow = new Element('tr', {'style':'vertical-align: top'});
		listArea.appendChild(newItemRow);
		if (listElements[i].childNodes.length > 0) {
			newItemRow.appendChild(new Element('th', {'style':'text-align: center'}));
			newItemRow.setAttribute('class','select');
			newItemRow.setAttribute('numChildren',listElements[i].childNodes.length);
			newItemRow.onclick = CASelectExpandHandler;
			newItemRow.firstChild.appendChild(document.createTextNode("+"));
			newItemRow.appendChild(new Element('th', {'colspan':'2', 'style':'text-align: left'}));
			newItemRow.childNodes[1].appendChild(document.createTextNode(listElements[i].getAttribute('name')));
			for (j=0;j<listElements[i].childNodes.length;j++) {
				newItemChildRow = new Element('tr', {'style':'vertical-align: top'});
				listArea.appendChild(newItemChildRow);
				newItemChildRow.appendChild(new Element('td', {'style':'text-align: center'}));
				newItemChildRow.appendChild(new Element('td', {'style':'text-align: center'}));
				newItemChildRow.childNodes[1].appendChild(new Element('input', {'type':'checkbox', 'name':'CASelectOptions', 'value':listElements[i].childNodes[j].getAttribute('name'), 'drillDown':listElements[i].childNodes[j].getAttribute('drillDown')}));
				if (listElements[i].childNodes[j].getAttribute('branchCode') != null) {
					newItemChildRow.childNodes[1].firstChild.setAttribute('branchCode',listElements[i].childNodes[j].getAttribute('branchCode'));
				}
				if (listElements[i].childNodes[j].getAttribute('agencyCode') != null) {
					newItemChildRow.childNodes[1].firstChild.setAttribute('agencyCode',listElements[i].childNodes[j].getAttribute('agencyCode'));
				}
				if (listElements[i].childNodes[j].getAttribute('bureauCode') != null) {
					newItemChildRow.childNodes[1].firstChild.setAttribute('bureauCode',listElements[i].childNodes[j].getAttribute('bureauCode'));
				}
				if (listElements[i].childNodes[j].getAttribute('functionCode') != null) {
					newItemChildRow.childNodes[1].firstChild.setAttribute('functionCode',listElements[i].childNodes[j].getAttribute('functionCode'));
				}
				if (listElements[i].childNodes[j].getAttribute('subfunctionCode') != null) {
					newItemChildRow.childNodes[1].firstChild.setAttribute('subfunctionCode',listElements[i].childNodes[j].getAttribute('subfunctionCode'));
				}
				newItemChildRow.childNodes[1].firstChild.onclick = CASelectChkBoxHandler;
				newItemChildRow.appendChild(new Element('td', {'style':'text-align: left'}));
				newItemChildRow.childNodes[2].appendChild(document.createTextNode(listElements[i].childNodes[j].getAttribute('name')));
				newItemChildRow.hide();
				if (listElements[i].getAttribute('value') == 'EB') {
					newItemRow.setAttribute('numChildren','1');
					j = listElements[i].childNodes.length;
				}
			}
		} else {
			newItemRow.appendChild(new Element('td', {'style':'text-align: center'}));
			newItemRow.firstChild.appendChild(new Element('input', {'type':'checkbox', 'name':'CASelectOptions', 'value':listElements[i].getAttribute('name'), 'drillDown':listElements[i].getAttribute('drillDown')}));
			if (listElements[i].getAttribute('agencyCode') != null) {
				newItemRow.firstChild.firstChild.setAttribute('agencyCode',listElements[i].getAttribute('agencyCode'));
			}
			if (listElements[i].getAttribute('bureauCode') != null) {
				newItemRow.firstChild.firstChild.setAttribute('bureauCode',listElements[i].getAttribute('bureauCode'));
			}
			if (listElements[i].getAttribute('functionCode') != null) {
				newItemRow.firstChild.firstChild.setAttribute('functionCode',listElements[i].getAttribute('functionCode'));
			}
			if (listElements[i].getAttribute('subfunctionCode') != null) {
				newItemRow.firstChild.firstChild.setAttribute('subfunctionCode',listElements[i].getAttribute('subfunctionCode'));
			}
			newItemRow.firstChild.firstChild.onclick = CASelectChkBoxHandler;
			newItemRow.appendChild(new Element('td', {'colspan':'2'}));
			newItemRow.childNodes[1].appendChild(document.createTextNode(listElements[i].getAttribute('name')));
		}
	}
}

function CASelectChkBoxHandler () {
	var i;
	var numSelections = 1.0*$('numCASelectionsText').firstChild.nodeValue;
	
	if (this.checked) {
		if (numSelections == 15) {
			alert("Too many selections!");
			this.checked = false;
		} else {
			numSelections++;
			$('numCASelectionsText').firstChild.nodeValue = numSelections;
		}
	} else {
		numSelections--;
		$('numCASelectionsText').firstChild.nodeValue = numSelections;
	}
	
}

function CASelectExpandHandler () {
	var i;
	var currentRow;
	
	if (this.firstChild.firstChild.nodeValue == "+") {
		this.firstChild.firstChild.nodeValue = "-";
		this.nextSibling.show();
		currentRow = this;
		for (i=0;i<this.getAttribute('numChildren');i++) {
			currentRow = currentRow.nextSibling;
			currentRow.show();
		}
	} else {
		this.firstChild.firstChild.nodeValue = "+";
		this.nextSibling.hide();
		currentRow = this;
		for (i=0;i<this.getAttribute('numChildren');i++) {
			currentRow = currentRow.nextSibling;
			currentRow.hide();
		}
	}
}