/* Dialog functionality */
var RAT_AJAX_SCRIPT		= 'ajax.php';
var RAT_SALESFORCE_URL  = "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
var RAT_DIALOG_DIV;
var RAT_PAGE_DATA		= {};
var RAT_Assemblies 		= new Array();
var RAT_Material_Types  = new Array();
var RAT_Materials 		= new Array();
var RAT_Tranport_Steps 	= new Array();
var RAT_Consumables 	= new Array();
var RAT_EndOfLife 		= new Array();
var RAT_CombinedTotals 	= new Array();
var RAT_Guidelines 		= new Array();
var RAT_Tips 			= new Array();
var RAT_Phase 			= 'none';
var RAT_CurrencySymbol  = '$';
var RAT_NextFieldMap    = {};

// Default focus values for the graphs
var RAT_Combined_Focus 		= 'GlobalWarming';
var RAT_Manufacture_1_Focus = 'GlobalWarming';
var RAT_Manufacture_2_Focus = 'GlobalWarming';
var RAT_Transport_Focus     = 'GlobalWarming';
var RAT_Use_Focus 			= 'GlobalWarming';
var RAT_End_Of_Life_Focus 	= 'GlobalWarming';

var RAT_DEFAULT_PART 		= {}; //{Material_ID: 303, Material_Name: 'Steel'};
var RAT_DEFAULT_PROCESS 	= {}; //{Material_Type_ID: 6, Material_Name: 'Steel Forging'};

var RAT_HelpText = {
	'home': '<p><b>How to use greenfly.</b> Throughout greenfly, you can click the Help link (top right) to access the <a href="javascript:help()">quick start guide</a>. </p>',
	'start': '<p><b>Welcome to the Construct wizard,</b> the  step-by-step guide that models your scenario. Here\'s some quick hints:</p><ul class="help"><li><b>No need to save.</b> Your input is automatically saved as you go. To not change your scenario just click Save As for a new scenario to work with.</li><li><b>Enter what you want.</b> To keep it simple we have prefilled your scenario with defaults. You can add as much detail as you need to refine your model.</li><li><b>Help is at hand.</b>  Click Help (top right) for quick start guide and comprehensive help at any time.</li></ul><p><b>Lets get started!</b> Fill out any details at left and click Next to continue. You can come back here or jump to other sections at any time via the Next & Back buttons.</p><p>See the <a href="javascript:help()">Quick Start Guide</a> for more help.',
	'manufacturing': "<p><b>Add parts and comment on design guidelines.</b> Try different combinations and view impacts in graphs below. Click next to continue.</p><p><b>Parts, materials and Processes. </b>You can model your scenario by adding any number of parts. To add a part click (+) in the Part column, Then click its Material to select a new material. Add processes to the part by clicking the (+) in the Processes column.</p><p><b>Assemblies.</b> Assemblies help you group parts into functional units. Create a new assembly by clicking the Add Assembly link then add parts as above.</p><p><b>Design guidelines.</b> Below your materials and processes, a list of Design Guidelines is automatically created according to the items you have selected. Responses you add can be included in a report later on.</p><p><p>For more info about this life cycle phase, continue to the Guidelines section or see the   <a target=_blank href='data_storage/docs/Guidelines_EOL.pdf'>End of Life Design Guidelines PDF</a>.</p>",
	'transport': '<p>For more info about this life cycle phase, continue to the Guidelines section or see the   <a target=_blank href="data_storage/docs/guidlines_manufacture.pdf">Product Distribution Design Guidelines PDF</a>.</p>',
	'use': '<p>For more info about this life cycle phase, continue to the Guidelines section or see the  <a target=_blank href="data_storage/docs/guidline_operational.pdf">Operational Use Design Guidelines PDF</a>.</p>',
	'endoflife': '<p><b>Why are some of the graphs negative?</b> If the bar chart below shows a below-zero value, this indicates a beneficial impact is occuring, for example you recycle a product instead of sending it to landfill.</p><p>For more info about this life cycle phase, continue to the Guidelines section or see the   <a target=_blank href="data_storage/docs/Guidelines_EOL.pdf">End of Life Design Guidelines PDF</a>.</p>',
	'guidelines': '<p>Further information on reducing the environmental load of your product is available on the Greenfly <a  href="resources.php">Resources</a> page.</p>'
};

// Globals for Graphing functionality (used by other functions)
var RAT_BarGraph = null;
var RAT_BarGraphDiv = null;
var RAT_PieChart = null;
var RAT_PieChartDiv = null;
var RAT_colorMap = {0: '084b89', 1: 'bf9400', 2: '378802', 3: '8a0413', 4: 'b04c11', 5: '810c7c', 6: '117a81', 7: 'a48cd9', 8: 'a3964e', 9: '7eb4c3', 10: 'd68885', 11: '82be98'};
var RAT_focusColorMap = {0: '959595', 1: '8a5a1a', 2: '7ea4ac', 3: 'be9400'};

var repeatAt=RAT_colorMap.length;
for (var i= repeatAt; i<30; i++) 
{
	var index = i% repeatAt;
	RAT_colorMap[i] = RAT_colorMap[index];
}

// Navigation functions
function RAT_Navigation(mode)
{
	if (mode == 'on')
	{
		$('nav_buttons_holder').show();
		$('bottom_nav_buttons_holder').show();
		$('crumbsRight').hide();
		new Effect.SlideDown('menustructure', {duration: 1, delay: 0.2, afterFinish: function(){$('crumbsRight').show();} });
	}
	else
	{
		$('menustructure').hide();
		$('nav_buttons_holder').hide();
		$('bottom_nav_buttons_holder').hide();
	}
}

function RAT_Dialog(div, mode, params)
{
	RAT_DIALOG_DIV = div;
	new Ajax.Request(RAT_AJAX_SCRIPT, {
		evalScripts: true,
		parameters: {f: 'Dialog', m: mode, p: $H(params).toJSON(), div: RAT_DIALOG_DIV},
		onComplete: function(transport) {
			var divContent = transport.responseText;
			Modalbox.show(divContent, {width: 656, height: 518, title: '<h2>Select</h2><span>&nbsp;</span>', overlayDuration: 0, slideUpDuration: 0, slideDownDuration: 0});
		}
	});
}

function RAT_Dialog_Hide()
{
	Modalbox.hide();
}

function RAT_HidePageDivs()
{
	for (var i=0; i<pageDivs.length; i++)
	{
		$(pageDivs[i]).hide();
	} 
}

function RAT_ShowPage(prevLink, nextLink, divID)
{
	RAT_HidePageDivs();
	$(divID).show();
	RAT_UpdatePageControls(prevLink, nextLink);
	RAT_CallPageFunctions(divID);
}

function RAT_ActivePage(change)
{
	var active;
	for (var i=0; i<pageDivs.length; i++)
	{
		if($(pageDivs[i]).visible())
		{
			active = i;
			break;
		}
	}
	
	if (change != null)
	{
		if (pageDivs[i+change] == null)
		{
			return null;
		}
	}
	return active;
}

function RAT_ChangePage(prevLink, nextLink, change)
{
	// Find the index of the visible div
	var active = RAT_ActivePage(change);
	
	// If visible is returned null, then we can't go further in that direction
	if (active == null) { return };
		
	// Now hide the divs
	RAT_HidePageDivs();
	
	// Now change the page as requested
	for (var i=0; i<pageDivs.length; i++)
	{
		if(i == active)
		{
			$(pageDivs[i+change]).show();
			break;
		}
	}

	RAT_UpdatePageControls(prevLink, nextLink);
	RAT_CallPageFunctions(pageDivs[active+change]);
}

function RAT_UpdatePageControls(prevLink, nextLink)
{
	if (RAT_ActivePage(+1) == null) { $(nextLink).className = 'next pageControlInactive'; } else { $(nextLink).className = 'next pageControlActive'; }
	if (RAT_ActivePage(-1) == null) { $(prevLink).className = 'back pageControlInactive'; } else { $(prevLink).className = 'back pageControlActive'; }

	if (RAT_ActivePage(+1) == null) { $('bottom_pageControlNext').className = 'next pageControlInactive'; } else { $('bottom_pageControlNext').className = 'next pageControlActive'; }
	if (RAT_ActivePage(-1) == null) { $('bottom_pageControlPrevious').className = 'back pageControlInactive'; } else { $('bottom_pageControlPrevious').className = 'back pageControlActive'; }

	
	var headers = $('submenu').childElements();
	for (var i=0; i<headers.length; i++)
	{
		var classNames = '';
		if (i == RAT_ActivePage())
		{
			classNames += "open ";
		}
		if (i == 0) 
		{ 
			classNames += 'first'; 
		} 
		else if (i+1 == headers.length)
		{
			classNames += 'last';
		}
		$(headers[i]).className = classNames;
	}
}

function RAT_EditableField(divID)
{
	$(divID+"_View").hide();
	$(divID+"_Edit").show();
	$(divID+"_Fld").focus();
}

function RAT_EditableFieldDone(divID, fld, object, trim, id, fn, type, preValue, postValue)
{
	var newValue = fld.value;
	if(preValue != null)
	{
		newValue = preValue+newValue;
	}
	
	if (fld.value.length == 0)
	{
		$(divID+"_Link").update('edit...');
		$(divID+"_Link").addClassName('formValueDefault');
		fld.focus();
	}
	else
	{
		newValue = newValue.replace(/\n/g, '<br>');
		$(divID+"_Link").removeClassName('formValueDefault');
		$(divID+"_Link").update(newValue);
	}
	
	// If we have been asked to 'trim' the last number from the field name, then apply this
	fieldName = new String(divID);
	if (trim)
	{
		fieldName = fieldName.replace(/\_\d+/, '');
	}
	
	// If we have been explicitly passed the id of the field, use this instead
	fieldID = object.ID;
	if (id != null)
	{
		fieldID = id;
	}
	
	// Validate the field before submitting it to the database
	if (type != null)
	{
		if (type == 'number' && !RAT_ValidateNumber(fld.value))
		{
			alert('You must enter a valid number in this field');
			fld.focus();
			return;
		}
	}

	// Now call ajax to save the data in the database
	new Ajax.Request(RAT_AJAX_SCRIPT,
	{
		parameters: {f: 'SaveField', field: fieldName, value: fld.value, object: object.Object, pk: object.Primary_Key, id: fieldID},
		onComplete: function()
		{
			if (fn == 'RAT_RenderManufactureOnChange')
			{
				RAT_RenderManufactureOnChange();
			}
			else if (fn == 'RAT_RenderTransportOnChange')
			{
				RAT_RenderTransportOnChange();
			}
			else if (fn == 'RAT_RenderUseOnChange')
			{
				RAT_RenderUseOnChange();
			}
			else if (fn == 'RAT_RenderEndoflifeOnChange')
			{
				RAT_RenderEndoflifeOnChange();
			}			
			else if (fn == 'RAT_UpdateBreadcrumbs')
			{
				RAT_UpdateBreadcrumbs(fld.value);
			}
		}
	});
	
	$(divID+"_Edit").hide();
	$(divID+"_View").show();
}

function RAT_SaveDropdownFieldValue(fld, object)
{
	var fieldName = new String(fld.name);

	new Ajax.Request(RAT_AJAX_SCRIPT,
		{
			parameters: {f: 'SaveField', field: fieldName, value: $F(fld), object: object.Object, pk: object.Primary_Key, id: object.ID}
		});
}

function RAT_CheckboxDone(divID, fld, object, trim, id)
{
	// If we have been asked to 'trim' the last number from the field name, then apply this
	fieldName = new String(divID);
	if (trim)
	{
		fieldName = fieldName.replace(/\_\d+/, '');
	}
	
	// If we have been explicitly passed the id of the field, use this instead
	fieldID = object.ID;
	if (id != null)
	{
		fieldID = id;
	}
	
	if (fld.checked)
	{
		value = 'Y';
	}
	else
	{
		value = 'N';
	}
	
	// Now call ajax to save the data in the database
	new Ajax.Request(RAT_AJAX_SCRIPT,
	{
		parameters: {f: 'SaveField', field: fieldName, value: value, object: object.Object, pk: object.Primary_Key, id: fieldID}
	});
}

function RAT_ResizeTextbox(box, fixed)
{
    lines =  box.value.split('\n')
    rows = 0
    thin_width = fixed ? 1 : 0.5
    thin_chars = "il!|'/,:;"
    lines.each(function(line){
      len = 0
      for(i=0;i<line.length; i++)
        len +=  ((thin_chars.indexOf(line[i]) > -1) ? thin_width : 1 )
      rows += 1+(len/box.cols)
    })
    box.rows = rows;
}
	
function RAT_UpdateImage(id, img)
{
	var image = $(id);
	var imageString = "<img src='"+img+"?"+Math.random()+"'>";
	image.show();
	image.update(imageString);
}

/* Rendering functionality for Assembly starts here */

/* Drawing functions */

function RAT_DrawAssembly(assembly, mode, showProcesses)
{
	mode = (!mode) ? 'edit' : mode;	
	
	var html = '';
	html += "<div class='assembly' id='Assembly_Div_"+assembly.Assembly_ID+"'>";
	
	html += "<div class='header'><h2>";
	html += (mode == 'edit') ? 
		RAT_DrawField('Assembly', assembly.Assembly_ID, 'Assembly_Name_'+assembly.Assembly_ID, assembly.Assembly_Name, 'RAT_RenderManufactureOnChange')
		: assembly.Assembly_Name;
	html += (mode == 'edit') ? "</h2><span><a href='javascript:void(0)' onclick='RAT_DeleteAssembly("+assembly.Assembly_ID+")'>x</a></span>" : '</h2><span>&nbsp;</span>';
    html += "</div>";

	html += "<table width='100%' border=0 class='assemblyTable' cellspacing=0 cellpadding=1>";
	html += "<tr class='assemblyTableHeading' id='Assembly_Heading_"+assembly.Assembly_ID+"'>";
	if (mode == 'edit')
	{
		html += "<th colspan=2>Part</th><th>Material</th><th colspan=2>Process</th><th>Amount</th><th>Costing</th><th>Certified</th><th>&nbsp;</th>";
	}
	else
	{
		html += "<th colspan=2>Part</th><th>Material</th><th colspan=2>Process</th><th>Amount</th><th>Destination</th>";
	}
	html += "</tr>";
		
	// Now draw the content of the assembly
	for (var i=0; i<assembly.Parts.length; i++)
	{
		html += RAT_DrawPart(assembly.Parts[i], mode, showProcesses);
		html += "<tr><td class='tablerspacer' colspan=9></tr>";
	}
	html += "</table>";
	html += "</div>";
	
	return html;
}

function RAT_DrawPart(part, mode, showProcesses)
{
	mode = (!mode) ? 'edit' : mode;
	
	var html = '';
	html += "<tr class='partRow' id='Part_"+part.Part_ID+"'>";
	
	html += "<td width='125px' class='firstcell topborder'>";
	html += (mode == 'edit') ? RAT_DrawField('Part', part.Part_ID, 'Part_Name_'+part.Part_ID, part.Part_Name) : part.Part_Name;
	html += "</td>";
	
	html += "<td class='pluscell topborder'>";
	// Add button for parts
	html += (mode == 'edit') ? "<a class='xlink' href='javascript:void(0)' onclick=\"RAT_AddPart("+part.Assembly_ID+", "+part.Part_ID+")\">+</a>" : '&nbsp;';
	html += "</td>";
	
	// Materials use a selector to choose and display
	html += "<td class='topborder'>";
	var part_material_name = (!part.Material_Name) ? 'Select material...' : part.Material_Name;
	html += (mode == 'edit') ? "<a href='javascript:void(0)' onClick=\"RAT_SelectMaterial(this, "+part.Part_ID+", 'Amount_2345"+part.Part_ID+"_Post')\">"+part_material_name+"</a>" : part_material_name;
	html += "</td>";
	
	html += "<td class='preplus'>&nbsp;</td>";
	
	html += "<td width=1% class='pluscell'>";
	html += (mode == 'edit') ? "<a class='xlink' href='javascript:void(0)' onclick=\"RAT_AddPartProcess("+part.Assembly_ID+", "+part.Part_ID+")\">+</a>" : '&nbsp;'
	html += "</td>"; // Add button for processes

	html += "<td width=7%>";
	if (mode == 'edit')
	{
		html += RAT_DrawField('Part', part.Part_ID, 'Amount_2345'+part.Part_ID, part.Amount, 'RAT_RenderManufactureOnChange', 'number', null, part.Unit_Type);
	}
	else
	{
		html += (part.Unit_Type ) ? "<div class='number'>"+part.Amount+"</div><div class='unit'>"+part.Unit_Type+"</div>" : "<div class='number'>"+part.Amount+"</div>";
	}
	html += "</td>";

	if (mode == 'edit') 
	{
		html += "<td>";
		html += RAT_DrawField('Part', part.Part_ID, 'Costing_'+part.Part_ID, part.Costing, null, 'number', RAT_CurrencySymbol);
		html += "</td>";
		
		html += "<td>";
		html += RAT_DrawCheckbox('Part', part.Part_ID, 'Certified_'+part.Part_ID, part.Certified);
		html += "</td>";
		
		html += "<td>";
		html += "<a href='javascript:void(0)' class='xlink' onclick=\"RAT_DeletePart("+part.Part_ID+")\">x</a>";
		html += "</td>";
	}
	else
	{
		var part_destination = (!part.Destination_Name) ? 'Select destination...' : part.Destination_Name;
		html += "<td>";
		html += "<a href='javascript:void(0)' onClick=\"RAT_SelectPartDestination(this, "+part.Part_ID+")\">"+part_destination+"</a>"
		html += "</td>";
	}
	html += "</tr>";

	// Now draw any processes that may exist for this part
	if (showProcesses == 'showProcesses')
	{
		if (part.Part_Processes != null && part.Part_Processes.length > 0)
		{
			for (var i=0; i<part.Part_Processes.length; i++)
			{
				html += RAT_DrawPartProcess(part.Part_Processes[i], mode);	
			}
		}
	}
	return html;
}

function RAT_DrawPartProcess(part_process, mode)
{
	mode = (!mode) ? 'edit' : mode;	
	
	var html = '';
	html += "<tr class='partProcessRow' id='Part_Process_"+part_process.Part_Process_ID+"'>";
	
	var part_process_name = (!part_process.Material_Name) ? 'Select process...' : part_process.Material_Name;

	html += "<td colspan=3 class='blankcell'>&nbsp;</td>";
	
	html += "<td colspan=2>";
	html += (mode == 'edit') ? "<a href='javascript:void(0)' onclick=\"RAT_SelectProcess(this, "+part_process.Part_Process_ID+", 'Amount_1234"+part_process.Part_Process_ID+"_Post')\">"+part_process_name+"</a>" : part_process_name;
	html += "</td>";
	
	html += "<td>";
	if (mode == 'edit') 
	{
		html += RAT_DrawField('Part_Process', part_process.Part_Process_ID, 'Amount_1234'+part_process.Part_Process_ID, part_process.Amount, 'RAT_RenderManufactureOnChange', 'number', null, part_process.Unit_Type);
	}
	else
	{		
		html += (part_process.Unit_Type) ? "<div class='number'>"+part_process.Amount+"</div><div class='unit'>"+part_process.Unit_Type+"</div>" : "<div class='number'>"+part_process.Amount+"</div>";
	}
	html += "</td>";
	
	if (mode == 'edit') 
	{
		html += "<td>";
		html += RAT_DrawField('Part_Process', part_process.Part_Process_ID, 'Costing_'+part_process.Part_Process_ID, part_process.Costing, null, 'number', RAT_CurrencySymbol);
		html += "</td>";

		html += "<td>";
		html += RAT_DrawCheckbox('Part_Process', part_process.Part_Process_ID, 'Certified_'+part_process.Part_Process_ID, part_process.Certified);
		html += "</td>";

		html += "<td>";
		html += "<a href='javascript:void(0)' class='xlink' onclick=\"RAT_DeletePartProcess("+part_process.Part_Process_ID+")\">x</a>";
		html += "</td>";	
	}
	else
	{
		var part_process_destination = (!part_process.Destination_Name) ? 'Select destination...' : part_process.Destination_Name;
		html += "<td>";
		html += "<a href='javascript:void(0)' onClick=\"RAT_SelectProcessDestination(this, "+part_process.Part_Process_ID+")\">"+part_process_destination+"</a>"
		html += "</td>";
	}
	html += "</tr>";
	
	return html;	
}


function RAT_DrawField(object, id, fieldName, value, fn, type, preValue, postValue)
{
	var html = '';

	html = "<div class='number' id='"+fieldName+"_View'>";
	html += "<a class='formValue";
	if (type == 'number')
	{
		html += " number";
	}
	html += "' id='"+fieldName+"_Link' href='javascript:void(0)' onClick=\"RAT_EditableField('"+fieldName+"')\">"
	if(preValue != null)
	{
		html += preValue;
	}
	html += value;

	html += "</a>";
	html += "</div>";
	
	html += "<div class='number' style='display: none;' id='"+fieldName+"_Edit'>";
	if(preValue != null)
	{
		html += "<span class='prevalue'>"+preValue+"</span>";
	}
	html += "<input class='formValue";
	if (type == 'number')
	{
		html += ' number';
	}
	html += "' id='"+fieldName+"_Fld' type='text' value=\""+value+"\" onBlur=\"RAT_EditableFieldDone('"+fieldName+"', this, "+object+", 1, "+id+", '"+fn+"', '"+type+"', ";
	html += (preValue != null) ? "'"+preValue+"'" : 'null';
	html += ", ";
	html += (postValue != null) ? "'"+postValue+"'" : 'null';
	html += ")\">";
	html += "</div>";
	
	html += "<div class='unit' id='"+fieldName+"_Post'>";
	if(postValue != null)
	{
		html += postValue;
	}
	html += "</div>";

	// Add handlers to the field
	html += "<script>$('"+fieldName+"_Fld').observe('keypress', function(e) {if(e.keyCode == Event.KEY_RETURN) {$('dd_combined').focus() }})</script>";;
	return html;
}

function RAT_DrawCheckbox(object, id, fieldName, value)
{
	var html = '';
	
	html += "<input id='"+fieldName+"' type='checkbox' value='Y' onChange=\"RAT_CheckboxDone('"+fieldName+"', this, "+object+", 1, "+id+")\"";
	if (value == 'Y')
	{
		html += "checked";
	}
	html += " >";

	return html;
}

/* 
------------------------------------------
Adding functions - utilise the Drawing functions above
------------------------------------------
*/

function RAT_RenderAssemblies(id, canvasDiv, controlsDiv, mode, showProcesses)
{
	mode = (!mode) ? 'edit' : mode;
	showProcesses = (!showProcesses) ? 'showProcesses' : 'hideProcesses';
	
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetAssembly', id: id},
            onComplete: function(transport)
            {
                RAT_Assemblies = transport.responseText.evalJSON();
					
				var html = '';

				for (var i=0; i<RAT_Assemblies.length; i++)
				{
					html += RAT_DrawAssembly(RAT_Assemblies[i], mode, showProcesses);
				}

				// When in read only mode we want to update the html
				if (mode == 'readonly')
				{
					$(canvasDiv).update(html);
				}
				else
				{
					new Insertion.Bottom(canvasDiv, html);
					var controlsHtml = "<a href='javascript:void(0)' onclick=\"RAT_AddAssembly('"+canvasDiv+"', "+id+")\">Add Assembly</a>";
					$(controlsDiv).update(controlsHtml);

					// Render the graphs
					RAT_RenderManufactureOnChange(id);	
				}
            }
        }
    );
}

function RAT_AddAssembly(canvasDiv, scenarioID)
{
	var Assembly = {Assembly_Name: 'New Assembly', Scenario_ID: scenarioID};
	
	// Create dummy part in database and get data to place in html
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'Insert', d: $H(Assembly).toJSON(), t: 'Assembly'},
            onComplete: function(transport)
            {
                Assembly.Assembly_ID = transport.responseText.evalJSON();
				Assembly.Parts = new Array();
				
				// Create html for new "Assembly"
				var html = RAT_DrawAssembly(Assembly);
				
				// Insert new part after "Assembly" in DOM	
				new Insertion.Bottom($(canvasDiv), html);
				
				// Update javascript object with new "part"
				RAT_Assemblies.push(Assembly);		
				
				// Now add a new part too
				RAT_AddPart(Assembly.Assembly_ID);	

				// Now update the graphs
				RAT_RenderManufactureOnChange(scenarioID);	
            }
        });	
}

function RAT_DeleteAssembly(assembly_id, no_confirm)
{
	if(no_confirm || confirm('Are you sure you want to delete this Assembly?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({Assembly_ID: assembly_id}).toJSON(), t: 'Assembly'},
				onComplete: function(transport)
				{	
					// Update javascript object and remove part
					for (var i=0; i<RAT_Assemblies.length; i++)
					{
						if (RAT_Assemblies[i].Assembly_ID  == assembly_id)
						{
							// Remove all the parts from the page
							for (var j=0; j<RAT_Assemblies[i].Parts.length; j++)
							{
								RAT_DeletePart(RAT_Assemblies[i].Parts[j].Part_ID, 1);
							}
							
							// Remove the part from the array 
							RAT_Assemblies.splice(i, 1);
							
							// Remove the assembly div
							$('Assembly_Div_'+assembly_id).remove();
						}
					}
					// Re-render the dynamic elements
					RAT_RenderManufactureOnChange(Scenario.Scenario_ID);				
				}
			});
	}
}

function RAT_AddPart(assembly_id, this_part_id)
{
	var Part = {Assembly_ID: assembly_id,
				Part_Name: 'Untitled part',
				Part_ID: null,
				Amount: 0,
				Costing: 0,
				Certified: 'N',
				Material_ID: RAT_DEFAULT_PART.Material_ID,
				Material_Name: RAT_DEFAULT_PART.Material_Name,
				Unit_Type: 'kg'
				};
	var Ignore = {Material_Name: 1, Unit_Type: 1};

	// Create dummy part in database and get data to place in html
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'Insert', d: $H(Part).toJSON(), i: $H(Ignore).toJSON(), t: 'Part'},
            onComplete: function(transport)
            {
                Part.Part_ID = transport.responseText.evalJSON();
				Part.Part_Processes = new Array();

				// Create html for new "part"
				partHtml = RAT_DrawPart(Part);
			
				// Insert new part after "part" in DOM
				if(this_part_id)
				{
					result = RAT_PartInsertAfter(this_part_id);
					new Insertion.After($(result.ObjectName+'_'+result.ID), partHtml);	
				}
				else
				{
					new Insertion.After($('Assembly_Heading_'+assembly_id), partHtml);
				}
				var assembly = RAT_GetAssembly(assembly_id);

				// Update javascript object with new "part"
				if (assembly.Parts.length == 0)
				{
					assembly.Parts.push(Part);
				}
				else
				{
					for (var i=0; i<assembly.Parts.length; i++)
					{
						if (assembly.Parts[i].Part_ID == this_part_id)
						{
							assembly.Parts.splice(i+1,0,Part);
							break;
						}
					}
				}
				// Update the sequence of the parts in the database
				RAT_ResequenceParts(assembly_id);
            }
        });
}

function RAT_PartInsertAfter(part_id)
{
	var result = {ObjectName: '', ID: ''};
	
	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		var assembly = RAT_Assemblies[i];
		for (var j=0; j<assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];
			if (part.Part_ID == part_id)
			{
				// If we've got processes for the part, then keep going.  Otherwise just
				// return the part
				if (part.Part_Processes.length > 0)
				{
					result.ObjectName = 'Part_Process';
					result.ID = part.Part_Processes[part.Part_Processes.length-1].Part_Process_ID;
				}
				else
				{
					result.ObjectName = 'Part';
					result.ID = part.Part_ID;
				}
				return result;
			}
		}
	}
	return result;
}

function RAT_DeletePart(part_id, automatic)
{
	if(automatic || confirm('Are you sure you want to delete this Part?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({Part_ID: part_id}).toJSON(), t: 'Part'},
				onComplete: function(transport)
				{
					// Remove the part and all sub items from the page
					$('Part_'+part_id).remove();
					
					// Delete each of the part_processes for the part		
					var part = RAT_GetPart(part_id);
					
					// Re-render the dynamic elements - but only if this isn't being automatically
					// deleted as part of a Assembly deletion 
					if(!automatic)
					{
						RAT_RenderManufactureOnChange(Scenario.Scenario_ID);
					}

					for (var i=0; i<part.Part_Processes.length; i++)
					{
						RAT_DeletePartProcess(part.Part_Processes[i].Part_Process_ID, 1);						
					}
					
					// Update javascript object and remove part
					for (var i=0; i<RAT_Assemblies.length; i++)
					{
						var assembly = RAT_Assemblies[i];
						for (var j=0; j<assembly.Parts.length; j++) 
						{
							if (assembly.Parts[j].Part_ID  == part_id)
							{
								// Remove the part from the array 
								assembly.Parts.splice(j, 1);
								
								// Now resequence the parts in the database
								RAT_ResequenceParts(assembly.Assembly_ID);
								
								// Check if the assembly has any more parts other than this one
								// if not we also remove the assembly
								if (assembly.Parts.length == 0)
								{
									RAT_DeleteAssembly(assembly.Assembly_ID, 1);
								}
							}
						}
					}				
				}
			});
	}
}

function RAT_ResequenceParts(assembly_id)
{
	var assembly = RAT_GetAssembly(assembly_id);
	for (var j=0; assembly.Parts.length; j++)
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'SaveField', 
							field: 'Sequence', 
							value: j, 
							object: 'Part', 
							pk: 'Part_ID', 
							id: assembly.Parts[j].Part_ID}
			});
	}
}

function RAT_AddPartProcess(assembly_id, part_id)
{
	var Part_Process =  
				   {Assembly_ID: assembly_id,
				   	Part_ID: part_id,
				    Process_ID: 0,
					Amount: 0,
					Costing: 0,
					Certified: 'N',
					Process_ID: 15};
        
	// Create dummy part in database and get data to place in html
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'Insert', d: $H(Part_Process).toJSON(), t: 'Part_Process'},
            onComplete: function(transport)
            {
                Part_Process.Part_Process_ID = transport.responseText.evalJSON();
				Part_Process.Material_Name = RAT_DEFAULT_PROCESS.Material_Name;
				Part_Process.Unit_Type = 'kg';
				Part_Process.Material_Type_ID = RAT_DEFAULT_PROCESS.Material_Type_ID;
       
				// Create html for new "part"
				var processHtml = RAT_DrawPartProcess(Part_Process);

				// Insert new part after "part" in DOM		
				new Insertion.After($('Part_'+part_id), processHtml);

				var Part = RAT_GetPart(part_id);
       
				// Update javascript object with new "process"
				Part.Part_Processes.push(Part_Process);
            }
        });
}

function RAT_DeletePartProcess(part_process_id, automatic)
{
	if(automatic || confirm('Are you sure you want to delete this Process?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({Part_Process_ID: part_process_id}).toJSON(), t: 'Part_Process'},
				onComplete: function(transport)
				{
					// Remove the part and all sub items from the page
					$('Part_Process_'+part_process_id).remove();
					
					// Re-render the dynamic elements - but only if this isn't being automatically
					// deleted as part of a Part or Assembly deletion 
					if(!automatic)
					{
						RAT_RenderManufactureOnChange(Scenario.Scenario_ID);
					}
					
					// Update javascript object and remove part_process
					for (var i=0; i<RAT_Assemblies.length; i++)
					{
						var assembly = RAT_Assemblies[i];
						for (var j=0; j<assembly.Parts.length; j++) 
						{
							var part = assembly.Parts[j];
							for (var k=0; k<part.Part_Processes.length; k++)
							{
								if (part.Part_Processes[k] == part_process_id)
								{
									part.Part_Processes.splice(k, 1);
									
									// resequence processes?
								}
							}
						}
					}				
				}
			});
	}	
}

/* 
------------------------------------------
Three-Level Selection Box functionality 
------------------------------------------
*/
function RAT_SelectProcess(field, part_process_id, post_field)
{
	var Part_Process = RAT_GetPartProcess(part_process_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectProcess', Part_Process);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Part_Process';
	RAT_PAGE_DATA.SelectTablePK = 'Part_Process_ID';
	RAT_PAGE_DATA.SelectTablePKValue = part_process_id;
	RAT_PAGE_DATA.SelectField = 'Process_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = post_field;

	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Part_Process.Process_ID = newValue;
		Part_Process.Material_Name = newName;
	}
}

function RAT_SelectMaterial(field, part_id, post_field)
{
	var Part = RAT_GetPart(part_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectMaterial', Part);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Part';
	RAT_PAGE_DATA.SelectTablePK = 'Part_ID';
	RAT_PAGE_DATA.SelectTablePKValue = part_id;
	RAT_PAGE_DATA.SelectField = 'Material_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = post_field;	
	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Part.Material_ID = newValue;
		Part.Material_Name = newName;
	}
}

function RAT_SelectPartDestination(field, part_id)
{
	var Part = RAT_GetPart(part_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectDestination', Part);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Part';
	RAT_PAGE_DATA.SelectTablePK = 'Part_ID';
	RAT_PAGE_DATA.SelectTablePKValue = part_id;
	RAT_PAGE_DATA.SelectField = 'Destination_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = null;	
	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Part.Destination_ID = newValue;
		Part.Destination_Name = newName;
	}
}

function RAT_SelectProcessDestination(field, part_process_id)
{
	var Part_Process = RAT_GetPartProcess(part_process_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectDestination', Part_Process);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Part_Process';
	RAT_PAGE_DATA.SelectTablePK = 'Part_Process_ID';
	RAT_PAGE_DATA.SelectTablePKValue = part_process_id;
	RAT_PAGE_DATA.SelectField = 'Destination_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 

	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Part_Process.Destination_ID = newValue;
		Part_Process.Destination_Name = newName;
	}
}

function RAT_SelectTransportStep(field, step_id, post_field)
{
	var Transport_Step = RAT_GetTransportStep(step_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectTransportStep', Transport_Step);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Transport_Step';
	RAT_PAGE_DATA.SelectTablePK = 'Transport_Step_ID';
	RAT_PAGE_DATA.SelectTablePKValue = step_id;
	RAT_PAGE_DATA.SelectField = 'Material_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = post_field;	
	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Transport_Step.Material_ID = newValue;
		Transport_Step.Material_Name = newName;
	}
}

function RAT_SelectConsumable(field, consumable_id, post_field)
{
	var Consumable = RAT_GetConsumable(consumable_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectConsumable', Consumable);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'Consumable';
	RAT_PAGE_DATA.SelectTablePK = 'Consumable_ID';
	RAT_PAGE_DATA.SelectTablePKValue = consumable_id;
	RAT_PAGE_DATA.SelectField = 'Material_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = post_field;	
	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		Consumable.Material_ID = newValue;
		Consumable.Material_Name = newName;
	}
}

function RAT_SelectEndOfLifeProcess(field, endoflife_id, post_field)
{
	var EndOfLife = RAT_GetEndOfLife(endoflife_id);
	
	// Launch dialog for process selection
	RAT_Dialog($('dialog'), 'SelectEndOfLife', EndOfLife);
	
	// Set the data to update when selection process is finished
	RAT_PAGE_DATA.SelectTable = 'EndOfLife';
	RAT_PAGE_DATA.SelectTablePK = 'EndOfLife_ID';
	RAT_PAGE_DATA.SelectTablePKValue = endoflife_id;
	RAT_PAGE_DATA.SelectField = 'Material_ID';
	RAT_PAGE_DATA.SelectFldTextElement = field; 
	RAT_PAGE_DATA.SelectFldPostTextElement = post_field;	
	RAT_PAGE_DATA.SelectUpdateObject = function (newValue, newName) {
		EndOfLife.Material_ID = newValue;
		EndOfLife.Material_Name = newName;
	}
}


function RAT_FillCategoryWidget(categoryDiv, valueDiv, resultDiv, categoryID, valueID, data)
{
	// WARNING: Use of page global: This is used to allow any function on the page
	//          					have access to the data for the select widget
	RAT_PAGE_DATA.SelectData = data;
	
	RAT_PAGE_DATA.SelectCategoryID = categoryID;
	RAT_PAGE_DATA.SelectValueID = valueID;
	
	var html = '';
	
	for (var i=0; i<data.length; i++)
	{
		html += "<div id='Category_"+data[i].ID+"' class='selectItem' ";
		html += "onClick=\"RAT_FillValueDiv('"+categoryDiv+"', '"+valueDiv+"', '"+resultDiv+"', "+data[i].ID+", null)\">";
		html += "<a name='Category_"+data[i].ID+"'></a>";
		html += data[i].Name;
		html += "</div>";
	}
	$(categoryDiv).update(html);
	
	// Now select the highlight selected items 	
	//RAT_HighlightSelectedCategoryValue(categoryID);
 
	document.location='#Category_'+categoryID;

	// if we have a selected value, then we need to fill this div now also
	if (valueID)
	{
		RAT_FillValueDiv(categoryDiv, valueDiv, resultDiv, categoryID, valueID);
		document.location='#Value_'+valueID;	
	}
	document.location='#';
}

// Function to set the color of the selected 
function RAT_HighlightSelectedCategoryValue(categoryID)
{
	var data = RAT_PAGE_DATA.SelectData;
	for (var i=0; i<data.length; i++)
	{
		var divID = 'Category_'+data[i].ID;
//alert(divID + " => "+data[i].ID+" == "+ categoryID);
	
		if (data[i].ID == categoryID)
		{
			$(divID).setStyle('background-color: #77a6d1; color: #FFFFFF;');
		}
		else
		{
			if(RAT_RoleCanAccess(data[i].Access))
			{
				$(divID).setStyle('background-color: #FFFFFF; color: #000000;');	
			}
			else
			{
				$(divID).setStyle('background-color: #FFFFFF; color: grey;');	
			}
		}
	}
}

function RAT_FillValueDiv(categoryDiv, valueDiv, resultDiv, categoryID, valueID)
{
	var html = '';
	RAT_HighlightSelectedCategoryValue(categoryID);

	// Loop through the data for the selector and find the selection that was made
	for (var i=0; i<RAT_PAGE_DATA.SelectData.length; i++)
	{
		if (RAT_PAGE_DATA.SelectData[i].ID == categoryID)
		{
			// Now iterate the selections "item" list and add them to the 
			// html to be placed in the second selector
			var items = RAT_PAGE_DATA.SelectData[i].Items;
			
			for (var j=0; j< items.length; j++)
			{
				var item = items[j];
				
				var style = '';
				if (item.ID == valueID)
				{
					style = 'background-color: #77a6d1; color: #FFFFFF;';
				}
				
				if (RAT_RoleCanAccess(item.Access))
				{
					html += "<div id='Value_"+item.ID+"' class='selectItem' ";
					html += "style='"+style+"' ";
					html += "onclick=\"RAT_FillResultDiv('"+categoryDiv+"','"+valueDiv+"','"+resultDiv+"','"+categoryID+"','"+item.ID+"')\">";
					html += "<a name='Value_"+item.ID+"'></a>";
					html += item.Name;
					html += "</div>";					
				}
				else
				{
					// User doesn't have access to this item, so grey it out
					style = 'color: grey;';
					
					html += "<div id='Value_"+item.ID+"' class='selectItem' ";
					html += "onclick=\"RAT_FillResultDiv('"+categoryDiv+"','"+valueDiv+"','"+resultDiv+"','"+categoryID+"','"+item.ID+"')\" ";
					html += "style='"+style+"' >";
					html += "<a name='Value_"+item.ID+"'></a>";
					html += item.Name;
					html += "</div>";
				}
			}
		}
	}

	$(valueDiv).update(html);
	
	// If we have the valueID set we need to default the result to display this information
	if (valueID)
	{
		RAT_FillResultDiv(categoryDiv, valueDiv, resultDiv, categoryID, valueID);
	}
		
	return html;
}

function RAT_RoleCanAccess(role)
{
	var result = 0;
	
	// Special case - where role isn't defined always return true
	if (!role)
	{
		result = 1;
	}
	else
	{
		// Otherwise, check the users role and apply rules
		if (User_Role == 'ADMIN')
		{
			result = 1;
		}
		else if (User_Role == 'USER')
		{
			if (role != 'ADMIN')
			{
				result = 1;
			}
		}
		else if (User_Role == 'DEMO')
		{
			if (role == 'DEMO')
			{
				result = 1;
			}
		}
	}
	return result;
}


// Function to set the color of the selected 
function RAT_HighlightSelectedValue(categoryID, valueID)
{
	var data = RAT_PAGE_DATA.SelectData;

	for (var i=0; i<data.length; i++)
	{
		if (data[i].ID == categoryID)
		{
			for (var j=0; j<data[i].Items.length; j++)
			{
				var item = data[i].Items[j];
				var divID = 'Value_'+item.ID;

				if(item.ID == valueID)
				{
					$(divID).setStyle('background-color: #77a6d1; color: #FFFFFF;');
				}
				else
				{				
					if(RAT_RoleCanAccess(item.Access))
					{
						$(divID).setStyle('background-color: #FFFFFF; color: #000000;');
					}
					else
					{
						$(divID).setStyle('background-color: #FFFFFF; color: grey;');					
					}
				}
			}
			break;
		}
	}
}

function RAT_FillResultDiv(categoryDiv, valueDiv, resultDiv, categoryID, valueID)
{
	var item = RAT_GetSelectItem(valueID);

	RAT_PAGE_DATA.SelectedDataItem = valueID;
	RAT_PAGE_DATA.SelectedDataItemName = item.Name;
	RAT_PAGE_DATA.SelectedDataItemUnit = item.Unit_Type;
	
	RAT_HighlightSelectedValue(categoryID, valueID);
	
	var html = "<h3>"+ item.Name + "</h3>";
	
	// Show warning that user can't select this item if not accessible
	if(!RAT_RoleCanAccess(item.Access))
	{
		html += "<span style='color: red;'>This item is not accessible as part of the trial</span><br><br>";
		
		// Disable the OK button
		$('widgetOKButton').disabled = true;
	}
	else
	{
		$('widgetOKButton').disabled = false;
	}
	
	if (item.Description)
	{
		html += "<p>"+item.Description+"</p>";
	}
	if (item.Pros)
	{
		html += "<ul class='pros'>";
		var items = item.Pros.split(/\n/);
		for (var i=0; i<items.length; i++)
		{
			html += "<li>"+items[i]+"</li>";
		}
		html += "</ul>";
	}
	if (item.Cons)
	{
		html += "<ul class='cons'>";
		var items = item.Cons.split(/\n/);
		for (var i=0; i<items.length; i++)
		{
			html += "<li>"+items[i]+"</li>";
		}
		html += "</ul>";
	}
	html += "<p>Click OK to proceed with this selection</p>";
	
	$(resultDiv).update(html);
}

function RAT_SaveSelectedItem()
{
	// Send off ajax request 
	new Ajax.Request(RAT_AJAX_SCRIPT,
	{
		parameters: {
						f: 'SaveField', 
						field: RAT_PAGE_DATA.SelectField, 
						value: RAT_PAGE_DATA.SelectedDataItem, 
						object: RAT_PAGE_DATA.SelectTable, 
						pk: RAT_PAGE_DATA.SelectTablePK, 
						id: RAT_PAGE_DATA.SelectTablePKValue},
		onComplete: function(){
			// Update the graphs on the page to reflect the change - 
			// this must be done in the onComplete to ensure the data has been
			// saved successfully before redrawing the graphs

			// Special case for EOL destinations - check for these first
			// then if not EOL destination, do the rest based on the SelectTable value
			if (RAT_PAGE_DATA.SelectField == 'Destination_ID')
			{
				RAT_RenderEndoflifeOnChange(Scenario.Scenario_ID);
			}
			else
			{
				switch (RAT_PAGE_DATA.SelectTable) {
					case 'Transport_Step':
						RAT_RenderTransportOnChange(Scenario.Scenario_ID);
						break;
					case 'EndOfLife':
						RAT_RenderEndoflifeOnChange(Scenario.Scenario_ID);
						break;
					case 'Consumable': 
						RAT_RenderUseOnChange(Scenario.Scenario_ID);
						break;
					default: 
						RAT_RenderManufactureOnChange(Scenario.Scenario_ID);
						break;	
				}		
			}
		}
	});	
	
	// Now update the text value of the link
	$(RAT_PAGE_DATA.SelectFldTextElement).update(RAT_PAGE_DATA.SelectedDataItemName);
	if ($(RAT_PAGE_DATA.SelectFldPostTextElement))
	{
		$(RAT_PAGE_DATA.SelectFldPostTextElement).update(RAT_PAGE_DATA.SelectedDataItemUnit);
	}
	
	// Now update the page's understanding of the selected Process_ID
	RAT_PAGE_DATA.SelectUpdateObject(RAT_PAGE_DATA.SelectedDataItem, RAT_PAGE_DATA.SelectedDataItemName);

	// Close the dialog box
	RAT_Dialog_Hide();
}

function RAT_GetSelectItem(valueID)
{
	for (var i=0; i<RAT_PAGE_DATA.SelectData.length; i++)
	{
		var categoryItems = RAT_PAGE_DATA.SelectData[i].Items;
		
		for (var j=0; j<categoryItems.length; j++)
		{
			if (valueID == categoryItems[j].ID)
			{
				return categoryItems[j];
			}
		}
	}
	return null;
}

/* 
------------------------------------------
Utility functions for Assembly data object 
------------------------------------------
*/

function RAT_GetAssembly(assembly_id)
{
	var assembly;
	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		if (RAT_Assemblies[i].Assembly_ID == assembly_id)
		{
			assembly = RAT_Assemblies[i];	
		}
	}
	return assembly;
}

function RAT_GetPart(part_id)
{
	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		var assembly = RAT_Assemblies[i];	
		
		for (var j=0; j < assembly.Parts.length; j++)
		{
			if (assembly.Parts[j].Part_ID == part_id)
			{
				return assembly.Parts[j];
			}
		}
	}
}

function RAT_GetPartProcess(part_process_id)
{
	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		var assembly = RAT_Assemblies[i];	

		for (var j=0; j < assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];
			
			for (var k=0; k<part.Part_Processes.length; k++)
			{
				if (part.Part_Processes[k].Part_Process_ID == part_process_id)
				{
					return part.Part_Processes[k];
				}
			}
		}
	}
}

/* 
------------------------------------------
Called anytime elements on the page effecting graphs/etc occur
------------------------------------------
*/
function RAT_RenderManufactureOnChange(id)
{
	if (!id) { id = Scenario.Scenario_ID; }	
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetAssembly', id: id},
            onComplete: function(transport)
            {
                RAT_Assemblies = transport.responseText.evalJSON();	

				// Now update everything!

				// We set a timer here because safari doesn't like it when we render too much at once
				var t = setTimeout("RAT_RenderManufactureGraphs("+id+")", 1000);
				RAT_RenderGuidelines(id);
				
				//Overall graph update
				RAT_RenderOverallOnChange(id);
			}
		}
	);
}

function RAT_RenderTransportOnChange(id)
{
	if (!id) { id = Scenario.Scenario_ID; }	
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetTransportSteps', id: id},
            onComplete: function(transport)
            {
                RAT_Transport_Steps = transport.responseText.evalJSON();

				// Now update graphs
  				RAT_RenderBarGraph(id, RAT_colorMap, 'transportBarGraph', 'transportBarLegend', 'mod_transport');
				RAT_RenderLegend(id, 'transportBarLegend', RAT_colorMap, RAT_Transport_Steps, 'Transport_Step_Name', 'Material_Name');
				
				//Overall graph update
				RAT_RenderOverallOnChange(id);
			}
		}
	);
}

function RAT_RenderUseOnChange(id)
{
	if (!id) { id = Scenario.Scenario_ID; }	
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetConsumables', id: id},
            onComplete: function(transport)
            {
                RAT_Consumables = transport.responseText.evalJSON();	

				// Now update graphs
  				RAT_RenderBarGraph(id, RAT_colorMap, 'consumableBarGraph', 'consumableBarLegend', 'mod_use');
				RAT_RenderLegend(id, 'consumableBarLegend', RAT_colorMap, RAT_Consumables, 'Consumable_Name', 'Material_Name');
				
				//Overall graph update
				RAT_RenderOverallOnChange(id);
			}
		}
	);
}

function RAT_RenderEndoflifeOnChange(id)
{
	if (!id) { id = Scenario.Scenario_ID; }	

	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetEndOfLife', id: id},
            onComplete: function(transport)
            {
                RAT_EndOfLife = transport.responseText.evalJSON();	

				// Now update graphs
  				RAT_RenderStackedBarGraph(id, RAT_colorMap, 'endoflifeBarGraph', 'endoflifeBarLegend', 'mod_end_of_life');
				
				//Overall graph update
				RAT_RenderOverallOnChange(id);
			}
		}
	);
}

function RAT_RenderOverallOnChange(id)
{
	if (!id) { id = Scenario.Scenario_ID; }	

    RAT_CombinedTotals = new Array({Name: 'Manufacture'}, {Name: 'Transport'}, {Name: 'Use'}, {Name: 'End of Life'});	
    
	// Now update graphs
  	RAT_RenderPieChart(id, RAT_focusColorMap, 'combinedPieChart', 'combinedPieLegend', RAT_CombinedTotals, 'Name', 'mod_combined');
}

// These functions are used to show/hide the containers that the graphs are in graph as the user steps through the pages.  
// The graphs themselves are rendered above.
function RAT_RenderSidePanels(page)
{
	var graphDivs = {
		start: 		 	['mod_combined'],
		manufacturing: 	['mod_combined', 'mod_manufacture_1', 'mod_tips'], // mod_manufacture_2 removed
		transport:   	['mod_combined', 'mod_transport', 'mod_tips'],
		use:   		 	['mod_combined', 'mod_use', 'mod_tips'],
		endoflife:   	['mod_combined', 'mod_end_of_life', 'mod_tips'],
		guidelines:  	['mod_combined', 'mod_tips']
	};

	for(var i=0; i<graphDivs[page].length; i++)
	{
		$(graphDivs[page][i]).show();
	}

	RAT_RenderHelpText(page);
}

function RAT_RenderHelpText(page)
{
	if (RAT_HelpText[page])
	{
		var text = "<a href='javascript:void(0)' id='hide_help' onclick=\"$('helpshow').show(); new Effect.SlideUp('helpcontents')\">Hide &laquo;</a>";
		text 	+= '<br><hr><br>'+RAT_HelpText[page];
		$('helpcontents').update(text);
		$('help').show();
	}
}

function RAT_HideSideElements()
{
	var graphDivs = ['mod_info', 'mod_combined', 'mod_manufacture_1', 'mod_manufacture_2', 'mod_transport', 'mod_use', 'mod_end_of_life', 'mod_tips'];
	graphDivs.each(function(item) {
		if ($(item)) {
			$(item).hide();
		}
	});
}

function RAT_ReloadGraph(fld, graphDiv)
{
	var focus = $(fld).options[$(fld).selectedIndex].value;
	var id = Scenario.Scenario_ID;

	if (graphDiv == 'mod_combined')
	{
		RAT_Combined_Focus = focus;
		RAT_RenderPieChart(id, RAT_focusColorMap, 'combinedPieChart', 'combinedPieLegend', RAT_CombinedTotals, 'Name', 'mod_combined');
	}
	else if (graphDiv == 'mod_manufacture_1')
	{
		RAT_Manufacture_1_Focus = focus;
		RAT_RenderStackedBarGraph(id, RAT_colorMap, null, null, 'mod_manufacture_1');
	}
	else if (graphDiv == 'mod_manufacture_2')
	{
		RAT_Manufacture_2_Focus = focus;
		RAT_RenderPieChart(id, RAT_colorMap, null, null, RAT_Assemblies, 'Assembly_Name', 'mod_manufacture_2');
	}
	else if (graphDiv == 'mod_transport')
	{
		RAT_Transport_Focus = focus;
		RAT_RenderBarGraph(id, RAT_colorMap, 'transportBarGraph', 'transportBarLegend', 'mod_transport');
	}
	else if (graphDiv == 'mod_use')
	{
		RAT_Use_Focus = focus;
		RAT_RenderBarGraph(id, RAT_colorMap, 'consumableBarGraph', 'consumableBarLegend', 'mod_use');
	}
	else if (graphDiv == 'mod_end_of_life')
	{
		RAT_End_Of_Life_Focus = focus;
		RAT_RenderStackedBarGraph(id, RAT_colorMap, null, null, 'mod_end_of_life');
	}
}

/* 
------------------------------------------
Graph functionality
------------------------------------------
*/

function RAT_RenderManufactureGraphs(id, focus)
{
	// Removed second pie chart as per John request
	//RAT_RenderPieChart(id, RAT_colorMap, null, null, RAT_Assemblies, 'Assembly_Name', 'mod_manufacture_2');
	RAT_RenderStackedBarGraph(id, RAT_colorMap, null, null, 'mod_manufacture_1');
}

function RAT_RenderPieChart(id, colorMap, graphDiv, legendDiv, legendData, legendName, mode)
{
	// Set defaults
	if (!graphDiv) { graphDiv = 'assemblyPieChart'; }
	if (!legendDiv) { legendDiv = 'assemblyPieLegend'; }
	if (graphDiv) { RAT_PieChartDiv = graphDiv; }
			
	RAT_PieChart = new FusionCharts("./ssi/FusionCharts/Charts/Pie3D.swf", "ChartId",  "134", "120", "0", "0");
	// Make the chart hide behind top layers
	RAT_PieChart.addParam("WMode", "Transparent");
		
	// Add the colors to the URL so the graph data script can use them
	var pieChartUrl = "graphdata.php?id="+id+"&type="+mode;	
	for (itemNo in colorMap)
	{
		pieChartUrl += "&"+itemNo+"="+colorMap[itemNo];
	}

	// Now add the 'focus' which depends on the type of pie chart we are doing
	var graph_focus;
	if (graphDiv == 'combinedPieChart')
	{
		graph_focus = RAT_Combined_Focus;
	}
	else if (graphDiv == 'assemblyPieChart')
	{
		graph_focus = RAT_Manufacture_2_Focus;
	}

	pieChartUrl += "&focus="+graph_focus;
	
	// Set the graph to "update mode"
	$(mode).addClassName("spinner");
	
	//alert(pieChartUrl);
	new Ajax.Request(pieChartUrl, {
		onComplete: function(transport)
		{ 
	//		alert(transport.responseText);
			RAT_PieChart.setDataXML(transport.responseText);
			RAT_PieChart.render(graphDiv);
			RAT_RenderLegend(id, legendDiv, colorMap, legendData, legendName);
			$(mode).removeClassName("spinner");
		}
	});
}

function RAT_RenderLegend(id, legendDiv, colorMap, items, item_name, inbrackets)
{
	var legendHtml = "<div class='legend' id='pie_legend_"+id+"'><ul>";
	for (var i=0; i<items.length; i++)
	{	
		legendHtml += "<li style='color: #"+colorMap[i]+"'><span>"+items[i][item_name];
		if (inbrackets) {
			legendHtml += " ("+items[i][inbrackets]+")";
		}
		legendHtml += "</span></li>";
	}
	legendHtml += "</ul></div>";

	$(legendDiv).update(legendHtml);
}

function RAT_RenderBarGraph(id, colorMap, graphDiv, legendDiv, mode)
{
	// Set defaults
	if (!id) { id = Scenario.Scenario_ID; }
//	if (!graphDiv) { graphDiv = 'assemblyBarGraph'; }
//	if (!legendDiv) { legendDiv = 'assemblyBarLegend'; }
	if (graphDiv) { RAT_BarGraphDiv = graphDiv; }
		
	RAT_BarGraph = new FusionCharts("./ssi/FusionCharts/Charts/Column2D.swf", "ChartId", "176", "140", "0", "0");
	// Make the chart hide behind top layers
	RAT_BarGraph.addParam("WMode", "Transparent");	
		
	// Add the colors to the URL so the graph data script can use them
	var barGraphUrl = "graphdata.php?id="+id+"&mode=bar&type="+mode;	

	for (itemNo in colorMap)
	{
		barGraphUrl += "&"+itemNo+"="+colorMap[itemNo];
	}

	var graphFocus = 'GlobalWarming';
	if (RAT_BarGraphDiv == 'transportBarGraph')
	{
		graphFocus = RAT_Transport_Focus;
	}
	else if (RAT_BarGraphDiv == 'consumableBarGraph')
	{
		graphFocus = RAT_Use_Focus;
	}
	barGraphUrl += "&focus=" + graphFocus;

	// Set the graph to "update mode"
	$(mode).addClassName("spinner");
//alert(barGraphUrl);
	new Ajax.Request(barGraphUrl, {
		onComplete: function(transport)
		{ 
	//		alert(transport.responseText);
			RAT_BarGraph.setDataXML(transport.responseText);
			//RAT_BarGraph.setDataURL('./test.xml');
			RAT_BarGraph.render(RAT_BarGraphDiv);
			$(mode).removeClassName("spinner");
		}
	});
		
	//alert(url);
	//chart.setDataURL(url);		   

}

function RAT_RenderStackedBarGraph(id, colorMap, graphDiv, legendDiv, mode)
{
	// Set defaults
	if (!id) { id = Scenario.Scenario_ID; }
	if (!graphDiv) { graphDiv = 'assemblyBarGraph'; }
	if (!legendDiv) { legendDiv = 'assemblyBarLegend'; }
	if (graphDiv) { RAT_BarGraphDiv = graphDiv; }

	RAT_BarGraph = new FusionCharts("./ssi/FusionCharts/Charts/StackedColumn2D.swf", "ChartId", "176", "140", "0", "0");
	// Make the chart hide behind top layers
	RAT_BarGraph.addParam("WMode", "Transparent");
			
	// Add the colors to the URL so the graph data script can use them
	var graphFocus = "GlobalWarming";
	if (mode == 'mod_manufacture_1')
	{
		graphFocus = RAT_Manufacture_1_Focus;
	}
	else if (mode == 'mod_end_of_life')
	{
		RAT_BarGraphDiv = 'endoflifeBarGraph';
		graphFocus = RAT_End_Of_Life_Focus;
	}
	var barGraphUrl = "graphdata.php?id="+id+"&mode=bar&type="+mode+"&focus="+graphFocus;	
	for (assemblyNo in colorMap)
	{
		barGraphUrl += "&"+assemblyNo+"="+colorMap[assemblyNo];
	}
	
	// Set the graph to "update mode"
	$(mode).addClassName("spinner");
	
	new Ajax.Request(barGraphUrl, {
		onComplete: function(transport)
		{
			RAT_BarGraph.setDataXML(transport.responseText);
			RAT_BarGraph.render(RAT_BarGraphDiv);
			if (mode == 'endoflife')
			{
				RAT_RenderEndOfLifeBarLegend(id, 'endoflifeBarLegend', colorMap);
			}
			else
			{
				RAT_RenderAssemblyBarLegend(id, legendDiv, colorMap);
			}
			$(mode).removeClassName("spinner");
		}
	});
		
	//alert(url);
	//chart.setDataURL(url);		   

}

function RAT_RenderAssemblyBarLegend(id, legendDiv, colorMap)
{
	var legends = Array();
	
	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		var assembly = RAT_Assemblies[i];			
		var listItems    = Array();

		// Create an array of items to display in the legend
		for (var j=0; j<assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];	
			if(part.Amount > 0 && part.Material_ID != 0)
			{
				listItems.push({name: part.Material_Name, color: null});
			}
		}

		for (var j=0; j<assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];
			for (var k=0; k<part.Part_Processes.length; k++)
			{
				var part_process = part.Part_Processes[k];
				if (part_process != null && part_process.Amount > 0 && part_process.Material_ID != 0)
				{
					listItems.push({name: part_process.Material_Name, color: null});
				}
			}
		}

		// Set the color
		var startCol = colorMap[i];
		var myColor	 = new Color(startCol);
		for (var j=0; j<listItems.length; j++)
		{
			listItems[j].color = myColor.getHex();
			myColor.lighten(100/listItems.length);
		}
		
		// Now drawn the legend box
		var html = '';
		html += "<h1>"+assembly.Assembly_Name+"</h1>";
		html += "<ul>";
		
		for (var j=listItems.length-1; j>=0; j--)
		{
			html += "<li style='color: "+listItems[j].color+"'><span>"+listItems[j].name+"</span></li>";
		}
		html += "</ul>";	
		legends.push(html);
	}

	// Place the legend items in table cells
	var legendHtml = "<table cellpadding=0 cellspacing=0 width=100%>";
	for (var i=0; i<legends.length; i=i+2)
	{
		legendHtml += "<tr>";
		legendHtml += "<td class='leftcell' valign=top>" + legends[i] + "</td>";
		if (i + 2 > legends.length)
		{
			legendHtml += "<td class='rightcell blankcell'>&nbsp;</td>";
		}
		else
		{
			legendHtml += "<td class='rightcell' valign=top>" + legends[i+1] + "</td>";
		}
		legendHtml += "</tr>";
	}
	legendHtml += "</table>";

	
	$(legendDiv).update(legendHtml);
}

function RAT_RenderEndOfLifeBarLegend(id, legendDiv, colorMap)
{
	var legends = Array();

	for (var i=0; i<RAT_Assemblies.length; i++)
	{
		var listItems = Array();
		var assembly = RAT_Assemblies[i];			

		for (var j=0; j<assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];	
			if(part.Amount > 0 && part.Destination_ID != 0)
			{
				listItems.push({name: part.Part_Name + " - " +part.Material_Name + " (" + part.Destination_Name + ")"});
			}
		}

		for (var j=0; j<assembly.Parts.length; j++)
		{
			var part = assembly.Parts[j];
			for (var k=0; k<part.Part_Processes.length; k++)
			{
				var part_process = part.Part_Processes[k];
				if (part_process != null && part_process.Amount > 0 && part_process.Destination_ID != 0)
				{
					listItems.push({name: part_process.Material_Name + " (" + part_process.Destination_Name + ")"});
				}
			}
		}
		
		// Now fix the colors
		var startCol = colorMap[i];
		var myColor	 = new Color(startCol);
		for (var j=0; j<listItems.length; j++)
		{
			listItems[j].color = myColor.getHex();
			myColor.lighten(100/listItems.length);
		}
		var html = '';
		html += "<h1>"+assembly.Assembly_Name+"</h1>";	
		html += "<ul>";
		for (var j=listItems.length-1; j>=0; j--)
		{
			html += "<li style='color: "+listItems[j].color+"'>"+listItems[j].name+"</li>";
		}
		html += "</ul>";
		legends.push(html);
	}

	var listItemsExtra    = Array();	
	for (var i=0; i<RAT_EndOfLife.length; i++)
	{
		listItemsExtra.push({name: RAT_EndOfLife[i].EndOfLife_Name + " (" + RAT_EndOfLife[i].Material_Name + ")", color: colorMap[RAT_Assemblies.length]});
	}
	var startCol = colorMap[RAT_Assemblies.length];
	var myColor	 = new Color(startCol);
	for (var j=0; j<listItemsExtra.length; j++)
	{
		listItemsExtra[j].color = myColor.getHex();
		myColor.lighten(100/listItemsExtra.length);
	}	

	// Now drawn the legend box
	var html = '';
	html += "<div class='legend'>";
	html += "<h1>Additional Processes</h1>";	
	html += "<ul>";
	for (var j=listItemsExtra.length-1; j>=0; j--)
	{
		html += "<li style='color: "+listItemsExtra[j].color+"'><span>"+listItemsExtra[j].name+"</span></li>";
	}
	html += "</ul>";
	legends.push(html);
	
	// Place the legend items in table cells
	var legendHtml = "<table cellpadding=0 cellspacing=0>";
	for (var i=0; i<legends.length; i=i+2)
	{
		legendHtml += "<tr>";
		legendHtml += "<td class='leftcell' valign=top>" + legends[i] + "</td>";
		if (i + 2 > legends.length)
		{
			legendHtml += "<td class='rightcell blankcell'>&nbsp;</td>";
		}
		else
		{
			legendHtml += "<td class='rightcell'>" + legends[i] + "</td>";
		}
		legendHtml += "</tr>";
	}
	legendHtml += "</table>";	
	
	$(legendDiv).update(legendHtml);
}


/* 
------------------------------------------
Guidelines functionality
------------------------------------------
*/

function RAT_RenderGuidelines(id)
{
	new Ajax.Request(RAT_AJAX_SCRIPT,
        {
            parameters: {f: 'GetMaterialTypes', id: id},
            onComplete: function(transport)
            {
				var html = '';
                RAT_Material_Types = transport.responseText.evalJSON();

				for (var i=0; i<RAT_Material_Types.length; i++)
				{
					html += RAT_RenderGroupGuideline(id, RAT_Material_Types[i]);
				}
				$('guidelinesCanvas').update(html);
				
				// Now get specific materials used and render their guidelines
				new Ajax.Request(RAT_AJAX_SCRIPT,
					{
						parameters: {f: 'GetMaterials', id: id},
						onComplete: function(transport) 
						{
							RAT_Materials = transport.responseText.evalJSON();					
							var material_html = RAT_RenderSpecificGuidelines(id, RAT_Materials);
							new Insertion.Bottom($('guidelinesCanvas'), material_html);
						}
					});
				
			}
		}
	);
}

function RAT_RenderSpecificGuidelines(scenario_id, materials)
{
	var html = '';
	
	html += "<div id='material_selected' class='displayWidget'>"
	html += "<div class='displayWidgetHeader'><h2>Specific materials you have selected</h2><span>&nbsp;</span></div>";
	
	html += "<div class='displayWidgetContent'>"
	html += "<table class='grid' cellpadding=0 cellspacing=0>";
	html += "<tr><th width=25%>Material</th><th width=25%>Pros</th><th width=25%>Cons</th><th width=25%>Your response</th></tr>";
	
	for (var i=0; i<materials.length; i++)
	{
		var material = materials[i];
		if (!material.Material_Description) {material.Material_Description = '';}

		html += "<tr>";
		html += "<td valign=top><b>"+material.Material_Name+"</b><br>"+material.Material_Description+"</td>";
		html += "<td valign=top><ul class='pros'>";

		for (var j=0; j<material.Pros.length; j++)
		{
			html += "<li>"+material.Pros[j]+"</li>";
		}
		html += "</ul></td>";
		
		html += "<td valign=top><ul class='cons'>";
		for (var j=0; j<material.Cons.length; j++)
		{
			html += "<li>"+material.Cons[j]+"</li>";
		}
		html += "</ul></td>";

		html += "<td valign=top>";
		for (var j=0; j<material.Questions.length; j++)
		{	
			var question = material.Questions[j];
		//	RAT_Debug(question);		
			html += "<span class='question'>"+question.Question_Text+"</span><br>";
			html += RAT_DrawQuestion(question.Response_Text, question.Question_Response_ID, question.Question_ID, scenario_id, 'Question');		
		}	
		html += "</td>";
		html += "</tr>";
	}
	
	html += "</table>";
	html += "</div>";
	
	html += "</div>";
	
	return html;
}

function RAT_RenderGroupGuideline(scenario_id, material_type)
{
	var html = '';
	
	html += "<div id='group_guideline_"+material_type.Material_Type_ID+"' class='displayWidget'>"
	html += "<div class='displayWidgetHeader'><h2>";
	html += material_type.Material_Type_Name;
	html += " in general</h2><span>&nbsp;</span></div>";
	
	html += "<div class='displayWidgetContent'>";
	html += "<table class='grid' cellpadding=0 cellspacing=0>";
	html += "<tr><th width=45%>Background</th><th width=27%>Question</th><th width=27%>Your Response</th></tr>";
	
	for (var i=0; i<material_type.Descriptions.length; i++)
	{
		var description = material_type.Descriptions[i];
		
		for (var j=0; j<description.Questions.length; j++)
		{	
			var question = description.Questions[j];
			//RAT_Debug(question);		
			html += "<tr>";
			html += "<td valign=top><b>"+description.Background_Header+"</b><br>"+description.Background_Text+"</td>";
			html += "<td valign=top><span class='question'>"+question.Question_Text+"</span></td>";
			html += "<td valign=top>"+RAT_DrawQuestion(question.Response_Text, question.Question_Response_ID, question.Question_ID, scenario_id, 'Question')+"</td>";		
			html += "</tr>";
		}	
	}
	
	html += "</table>";
	html += "</div>";
	
	html += "</div>";
	
	return html;
}

function RAT_DrawQuestion(text, responseID, questionID, scenarioID, questionType)
{
	var html = '';
	var className = 'formValue';
	var linkText = text;
	
	if (text.length == 0)
	{
	 	linkText = "edit...";
		className = 'formValue formValueDefault';
	}

	if (!responseID)
	{
		responseID = 'null';
	}

	var fieldName = 'question_'+questionID+'_'+questionType;

	linkText = linkText.replace(/\n/g, '<br>');

	html += "<div id='"+fieldName+"_View'>";
	html += "<a id='"+fieldName+"_Link' href='javascript:void(0)' onClick=\"RAT_EditableField('"+fieldName+"')\"  class='"+className+"'>"+linkText+"</a>";
	html += "</div>";
	
	html += "<div style='display: none' id='"+fieldName+"_Edit'>";
	html += "<textarea id='"+fieldName+"_Fld' class='autoheight' style='overflow: hidden;' rows=3 cols=20 wrap name='"+fieldName+"' ";
	html += "onBlur=\"RAT_SaveQuestion('"+fieldName+"', this, "+responseID+", "+questionID+", "+scenarioID+", '"+questionType+"')\">";
	html += text;
	html += "</textarea>";
	html += "</div>";
	
	html += "<script>RAT_ResizeTextbox($('"+fieldName+"_Fld'), false);\n";
    html += "new Form.Element.Observer($('"+fieldName+"_Fld'), 0.2, function(x) { RAT_ResizeTextbox(x, false)})\n";
	html += "</script>";	
	
	return html;
}

function RAT_SaveQuestion(divID, fld, responseID, questionID, scenarioID, questionType)
{
	if (fld.value.length == 0)
	{
		$(divID+"_Link").update('edit...');
		$(divID+"_Link").addClassName('formValueDefault');
		//fld.focus();
	}
	else
	{
		$(divID+"_Link").removeClassName('formValueDefault');
		var newValue = fld.value;
		newValue = newValue.replace(/\n/g, '<br>');
		$(divID+"_Link").update(newValue);
	}
	
	// If we have been asked to 'trim' the last number from the field name, then apply this
	fieldName = new String(divID);
	fieldName = fieldName.replace(/\_\d+/, '');
	
	// Now call ajax to save the data in the database
	new Ajax.Request(RAT_AJAX_SCRIPT,
	{
		parameters: {f: 'SaveQuestion', responseID: responseID, questionID: questionID, 
										scenarioID: scenarioID, value: fld.value, questionType: questionType},
		onComplete: function(transport) {
			var responseID = transport.responseText.evalJSON();
			
			if (questionID)
			{
				var html = '';
				html += "<textarea id='"+divID+"_Fld' class='autoheight' style='overflow: hidden;' rows=3 cols=20 wrap name='"+divID+"' ";
				html += "onBlur=\"RAT_SaveQuestion('"+divID+"', this, "+responseID+", "+questionID+", "+scenarioID+")\">";
				html += fld.value;
				html += "</textarea>";
				
				$(divID+"_Edit").update(html);
			}
		}
	});
	
	$(divID+"_Edit").hide();
	$(divID+"_View").show();
}

/* 
------------------------------------------
Transport functionality
------------------------------------------
*/

function RAT_RenderTransportSteps(id, transportDiv)
{
	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'GetTransportSteps', id: id},
		onComplete: function(transport) 
		{
			RAT_Transport_Steps = transport.responseText.evalJSON();
			
			var html = '';

			html += "<div id='transportSteps' class='displayWidget'>";
			html += "<div class='displayWidgetHeader'><h2>Transports steps</h2><span>&nbsp;</span></div>";
			html += "<div class='displayWidgetContent'>";
			html += "<table width=100% cellpadding=0 cellspacing=0>";
			html += "<tr id='transport_step_header'><th>Description</th><th>Tranport Mode</th><th>Distance</th><th width=1%>&nbsp;</th></tr>";
			for (var i=0; i<RAT_Transport_Steps.length; i++)
			{
				html += RAT_DrawTransportStep(RAT_Transport_Steps[i]);
			}
			html += "</table>";
			html += "</div>";
			html += "</div>";

			$(transportDiv).update(html);	
			
			// Now update the grpahs
			RAT_RenderTransportOnChange(id, 'transportBarGraph', 'transportBarLegend', 'transport');
		}
	});
}

function RAT_DrawTransportStep(step)
{
	var html = '';
	
	html += "<tr id='transport_step_"+step.Transport_Step_ID+"'>";
	html += "<td class='description' width=300px>"+RAT_DrawField('Transport_Step', step.Transport_Step_ID, 'Transport_Step_Name_'+step.Transport_Step_ID, step.Transport_Step_Name, 'RAT_RenderTransportOnChange')+"</td>";
	
	var step_material_name = step.Material_Name;
	if (!step_material_name)
	{
		step_material_name = 'Select transport mode...';
	}
	html += "<td><a href='javascript:void(0)' onClick=\"RAT_SelectTransportStep(this, "+step.Transport_Step_ID+", 'Distance_"+step.Transport_Step_ID+"_Post')\">"+step_material_name+"</a></td>";	
	
	html += "<td width=30px>"+RAT_DrawField('Transport_Step', step.Transport_Step_ID, 'Distance_'+step.Transport_Step_ID, step.Distance, 'RAT_RenderTransportOnChange', 'number', null, " "+step.Unit_Type)+"</td>";
	html += "<td class='rightcell'><a href='javascript:void(0)' class='xlink' onclick=\"RAT_DeleteTransportStep("+step.Transport_Step_ID+")\">x</a></td>"
	html += "</tr>";
	
	return html;
}

function RAT_AddTransportStep(id, divID)
{
	var step = 
	{
		Scenario_ID: id, 
		Transport_Step_Name: 'Add description here...',
//		Material_ID: 48,
//		Material_Name: 'Air Freight Domestic',
		Unit_Type: '',
		Distance: 0
	};

	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'Insert', d: $H(step).toJSON(), t: 'Transport_Step', i: $H({'Material_Name': 1, 'Unit_Type': 1}).toJSON()},
		onComplete: function(transport) 
		{
			step.Transport_Step_ID = transport.responseText.evalJSON();
			
			var html = RAT_DrawTransportStep(step);
			if(RAT_Transport_Steps.length == 0)
			{
				new Insertion.After($('transport_step_header'), html);
			}
			else
			{
				var max_step = RAT_GetMaxTransportStep();
				new Insertion.After($('transport_step_'+max_step.Transport_Step_ID), html);
			}
			
			RAT_Transport_Steps.push(step);
			RAT_RenderTransportOnChange(id);
		}
	});
}

function RAT_DeleteTransportStep(step_id)
{
	if(confirm('Are you sure you want to delete this Transport Step?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({Transport_Step_ID: step_id}).toJSON(), t: 'Transport_Step'},
				onComplete: function(transport)
				{
					// Remove the part and all sub items from the page
					$('transport_step_'+step_id).remove();
					
					// Update javascript object and remove part
					for (var i=0; i<RAT_Transport_Steps.length; i++)
					{
						if (RAT_Transport_Steps[i].Transport_Step_ID == step_id)
						{
							// Remove the part from the array 
							RAT_Transport_Steps.splice(i, 1);
							break;
						}
					}		
					RAT_RenderTransportOnChange();
				}
			});
	}
}

function RAT_GetTransportStep(step_id)
{
	for (var i=0; i<RAT_Transport_Steps.length; i++)
	{
		if (RAT_Transport_Steps[i].Transport_Step_ID == step_id)
		{
			return RAT_Transport_Steps[i];
		}
	}
}

function RAT_GetMaxTransportStep()
{
	var max = null;
	for (var i=0; i<RAT_Transport_Steps.length; i++)
	{
		if (max == null || parseInt(RAT_Transport_Steps[i].Transport_Step_ID) > parseInt(max.Transport_Step_ID))
		{
			max = RAT_Transport_Steps[i];
		}
	}
	return max;
}

/* 
------------------------------------------
Consumables functionality
------------------------------------------
*/

function RAT_RenderConsumables(id, divID)
{
	var html = '';
	
	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'GetConsumables', id: id},
		onComplete: function(transport) 
		{
			RAT_Consumables = transport.responseText.evalJSON();
		
			var html = '';

			html += "<table width=100% cellpadding=0 cellspacing=0>";
			html += "<tr id='consumables_header'><th>Your Description</th><th>Consumable</th><th width=10%>Amount Consumed</th><th width=1%>&nbsp;</th></tr>";
			for (var i=0; i<RAT_Consumables.length; i++)
			{
				html += RAT_DrawConsumable(RAT_Consumables[i]);
			}
			html += "</table>";

			$(divID).update(html);		
			RAT_RenderUseOnChange(id);				
		}
	});	
}

function RAT_DrawConsumable(consumable)
{
	var html = '';

	html += "<tr id='consumable_"+consumable.Consumable_ID+"'>";
	html += "<td>"+RAT_DrawField('Consumable', consumable.Consumable_ID, 'Consumable_Name_'+consumable.Consumable_ID, consumable.Consumable_Name, 'RAT_RenderUseOnChange')+"</td>";
	
	var consumable_material_name = consumable.Material_Name;
	if (!consumable_material_name)
	{
		consumable_material_name = 'Select consumable...';
	}
	html += "<td><a href='javascript:void(0)' onClick=\"RAT_SelectConsumable(this, "+consumable.Consumable_ID+", 'Amount_9856"+consumable.Consumable_ID+"_Post')\">"+consumable_material_name+"</a></td>";	
	
	html += "<td>"+RAT_DrawField('Consumable', consumable.Consumable_ID, 'Amount_9856'+consumable.Consumable_ID, consumable.Amount, 'RAT_RenderUseOnChange', 'number', null, consumable.Unit_Type)+"</td>";
	html += "<td class='rightcell'><a href='javascript:void(0)' class='xlink' onclick=\"RAT_DeleteConsumable("+consumable.Consumable_ID+")\">x</a></td>"
	html += "</tr>";

	return html;
}

function RAT_AddConsumable(id, divID)
{
	var consumable = 
	{
		Scenario_ID: id, 
		Consumable_Name: 'Add description here...',
		Amount: 1
	};

	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'Insert', d: $H(consumable).toJSON(), t: 'Consumable'},
		onComplete: function(transport) 
		{
			consumable.Consumable_ID = transport.responseText.evalJSON();
			
			var html = RAT_DrawConsumable(consumable);

			if(RAT_Consumables.length == 0)
			{
				new Insertion.After($('consumables_header'), html);
			}
			else
			{
				var max_consumable = RAT_GetMaxConsumable();
				
				new Insertion.After($('consumable_'+max_consumable.Consumable_ID), html);
			}
			
			RAT_Consumables.push(consumable);
			RAT_RenderUseOnChange(id);
		}
	});
}

function RAT_DeleteConsumable(consumable_id)
{
	if(confirm('Are you sure you want to delete this Consumable?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({Consumable_ID: consumable_id}).toJSON(), t: 'Consumable'},
				onComplete: function(transport)
				{
					// Remove the part and all sub items from the page
					$('consumable_'+consumable_id).remove();
					
					// Update javascript object and remove part
					for (var i=0; i<RAT_Consumables.length; i++)
					{
						if (RAT_Consumables[i].Consumable_ID == consumable_id)
						{
							// Remove the part from the array 
							RAT_Consumables.splice(i, 1);
							break;
						}
					}	
					RAT_RenderUseOnChange();			
				}
			});
	}
}

function RAT_GetConsumable(consumable_id)
{
	for (var i=0; i<RAT_Consumables.length; i++)
	{
		if (RAT_Consumables[i].Consumable_ID == consumable_id)
		{
			return RAT_Consumables[i];
		}
	}
}

function RAT_GetMaxConsumable()
{
	var max = null;
	for (var i=0; i<RAT_Consumables.length; i++)
	{
		if (max == null || parseInt(RAT_Consumables[i].Consumable_ID) > parseInt(max.Consumable_ID))
		{
			max = RAT_Consumables[i];
		}
	}
	return max;
}


/* 
------------------------------------------
EndOfLife functionality
------------------------------------------
*/

function RAT_RenderEndOfLife(id, assemblyDiv, endoflifeDiv)
{
	RAT_RenderAssemblies(id, assemblyDiv, null, 'readonly', 'hideProcesses');
	RAT_RenderEndoflifeDiv(id, endoflifeDiv);
}


function RAT_RenderEndoflifeDiv(id, divID)
{
	var html = '';
	
	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'GetEndOfLife', id: id},
		onComplete: function(transport) 
		{
			RAT_EndOfLife = transport.responseText.evalJSON();

			var html = '';

			html += "<table width=100% cellpadding=0 cellspacing=0>";
			html += "<tr id='endoflife_header'><th>Description</th><th>Process</th><th>Amount</th><th width=1%>&nbsp;</th></tr>";
			for (var i=0; i<RAT_EndOfLife.length; i++)
			{
				html += RAT_DrawEndOfLife(RAT_EndOfLife[i]);
			}
			html += "</table>";

			$(divID).update(html);	
			
			RAT_RenderEndoflifeOnChange(id);		
		}
	});	
}

function RAT_DrawEndOfLife(endoflife)
{
	var html = '';

	html += "<tr id='endoflife_"+endoflife.EndOfLife_ID+"'>";
	html += "<td class='description' width=300px>"+RAT_DrawField('EndOfLife', endoflife.EndOfLife_ID, 'EndOfLife_Name_'+endoflife.EndOfLife_ID, endoflife.EndOfLife_Name, 'RAT_RenderEndoflifeOnChange')+"</td>";
	
	var endoflife_processname = (endoflife.Material_Name) ? endoflife.Material_Name : 'Select process...';
	html += "<td><a href='javascript:void(0)' onClick=\"RAT_SelectEndOfLifeProcess(this, "+endoflife.EndOfLife_ID+", 'Amount_1111"+endoflife.EndOfLife_ID+"_Post')\">"+endoflife_processname+"</a></td>";	
	
	html += "<td>"+RAT_DrawField('EndOfLife', endoflife.EndOfLife_ID, 'Amount_1111'+endoflife.EndOfLife_ID, endoflife.Amount, 'RAT_RenderEndoflifeOnChange', 'number', null, endoflife.Unit_Type)+"</td>";
	html += "<td class='rightcell'><a href='javascript:void(0)' class='xlink' onclick=\"RAT_DeleteEndOfLife("+endoflife.EndOfLife_ID+")\">x</a></td>"
	html += "</tr>";

	return html;
}

function RAT_AddEndOfLife(id, divID)
{
	var endoflife = 
	{
		Scenario_ID: id, 
		EndOfLife_Name: 'Add description here...',
		Amount: 1
	};

	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'Insert', d: $H(endoflife).toJSON(), t: 'EndOfLife'},
		onComplete: function(transport) 
		{
			endoflife.EndOfLife_ID = transport.responseText.evalJSON();
			
			var html = RAT_DrawEndOfLife(endoflife);

			if(RAT_EndOfLife.length == 0)
			{
				new Insertion.After($('endoflife_header'), html);
			}
			else
			{		
				var max_endoflife = RAT_GetMaxEndOfLife();

				new Insertion.After($('endoflife_'+max_endoflife.EndOfLife_ID), html);
			}
			
			RAT_EndOfLife.push(endoflife);
			RAT_RenderEndoflifeOnChange(id);
		}
	});
}

function RAT_DeleteEndOfLife(endoflife_id)
{
	if(confirm('Are you sure you want to delete this End Of Life Process?'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'Delete', w: $H({EndOfLife_ID: endoflife_id}).toJSON(), t: 'EndOfLife'},
				onComplete: function(transport)
				{
					// Remove the part and all sub items from the page
					$('endoflife_'+endoflife_id).remove();
					
					// Update javascript object and remove part
					for (var i=0; i<RAT_EndOfLife.length; i++)
					{
						if (RAT_EndOfLife[i].EndOfLife_ID == endoflife_id)
						{
							// Remove the part from the array 
							RAT_EndOfLife.splice(i, 1);
							break;
						}
					}	
					RAT_RenderEndoflifeOnChange();			
				}
			});
	}
}

function RAT_GetEndOfLife(endoflife_id)
{
	for (var i=0; i<RAT_EndOfLife.length; i++)
	{
		if (RAT_EndOfLife[i].EndOfLife_ID == endoflife_id)
		{
			return RAT_EndOfLife[i];
		}
	}
}

function RAT_GetMaxEndOfLife()
{
	var max = null;
	for (var i=0; i<RAT_EndOfLife.length; i++)
	{
		if (max == null || parseInt(RAT_EndOfLife[i].EndOfLife_ID) > parseInt(max.EndOfLife_ID))
		{
			max = RAT_EndOfLife[i];
		}
	}
	return max;
}

/* 
------------------------------------------
Guidelines functionality
------------------------------------------
*/

function RAT_RenderGuidelinePage(id, jumpDiv, mainDiv)
{
	new Ajax.Request(RAT_AJAX_SCRIPT, 
	{
		parameters: {f: 'GetGuidelines', id: id},
		onComplete: function(transport) 
		{
			RAT_Guidelines = transport.responseText.evalJSON();
//alert(transport.responseText);
			RAT_RenderGuidelineJump(id, RAT_Guidelines, jumpDiv);
			RAT_RenderGuidelineQuestions(id, RAT_Guidelines, mainDiv);
		}
	});
}

function RAT_RenderGuidelineJump(id, guidelines, div)
{
	var html = '';
	html += "<div class='content_nav'><span class='content_nav_heading'>Jump to:</span>";
	html += "<span id='content_nav_list'><ul>";
	for (var i=0; i<guidelines.length; i++)
	{
		html += "<li ";
		if (i == 0) { html += "class='first'"; }
		if (i == 1) { html += "class='second'"; }	
		html += "><a href='#"+guidelines[i].Code+"'>"+guidelines[i].Title+"</a></li>";
	}
	html += "</ul>";
	html += "</span>";
	html += "</div>";
	
	$(div).update(html);
}

function RAT_RenderGuidelineQuestions(id, RAT_Guidelines, div)
{
	var html = '';

	for (var i=0; i<RAT_Guidelines.length; i++)
	{
		var guideline = RAT_Guidelines[i];
		html += "<a name='"+guideline.Code+"'></a>"
		html += "<div class='box'>";
		html += "	<div class='header'><h2>"+guideline.Title+" </h2><span><a href='javascript:void(0)' onClick=\"Effect.toggle('guidelineContent"+guideline.Code+"', 'appear')\">+/-</a></span></div>";
		var displayStyle = 'none';
		if (RAT_GuidelineHasResponses(guideline))
		{
			// Show the full section for the guideline if it has a response
			displayStyle = 'block';
		}
		html += "   <div id='guidelineContent"+guideline.Code+"' style='display: "+displayStyle+"'>";
		html += "	<h3>"+guideline.Title+" ~ ";
		html += "		<span>"+guideline.Subtitle+"</span></h3>";
		html += "    <table class='box_nobg overview' width=100% cellpadding=0 cellspacing=0>";
		html += "  		<tr><td valign=top><p><b>Overview:</b> "+guideline.Overview+"</p></td>";
		html += "       <td valign=top><div class='question'><span><span>Q</span></span>";
		if (guideline.Overview_Question)
		{
			html += "	"+guideline.Overview_Question.Question_Text+"</div>";
			var response_text = (guideline.Overview_Question.Response) ? guideline.Overview_Question.Response.Response_Text : '';
			var response_id = (guideline.Overview_Question.Response) ? guideline.Overview_Question.Response.Question_Response_ID : null;
			var value = "Response Text: " + response_text +", Response ID: "+response_id+", Overview Qn ID: "+guideline.Overview_Question.Question_ID+", ID: "+id;
			//alert(value);
			html += "<div class='answer'><span><span>A</span></span>" +
					RAT_DrawQuestion(response_text, response_id, guideline.Overview_Question.Question_ID, id, 'Guideline')+"</div>";
		}
		html += "		</td></tr></table>";
		
		html += "<table class='guidelineq' width=100% cellpadding=0 cellspacing=0>";
		html += "<tr><th>Prompts</th><th>Your response</th></tr>";
		for(var j=0; j<guideline.Questions.length; j++)
		{
			var question = guideline.Questions[j];
			if (question.Is_Overview == 'N')
			{
				html += "<tr>";
				html += "<td valign=top width=50%><div>"+question.Question_Text+"</div></td>";
				html += "<td valign=top>";
				var response_text = (question.Response) ? question.Response.Response_Text : '';
				var response_id = (question.Response) ? question.Response.Question_Response_ID : null;
				html += RAT_DrawQuestion(response_text, response_id, question.Question_ID, id, 'Guideline');
				html += "</td>";
			}
		}
		html += "</table>";
		html += "</div>";
		html += "</div>";
		html += "<a href='#top' class='backtotop'>Back to top</a>"
	}

	$(div).update(html);
}

function RAT_GuidelineHasResponses(guideline)
{
	var hasResponses = 0;
	for(var j=0; j<guideline.Questions.length; j++)
	{
		var question = guideline.Questions[j];
		if (question.Response)
		{
			hasResponses = 1;
			break;
		}
	}
	return hasResponses;
}

/* 
------------------------------------------
Tip of the day functionality
------------------------------------------
*/
function RAT_RenderTipOfTheDay(phase, force)
{
	var html = '';
	RAT_Phase = phase;

	if(RAT_Tips[phase] && !force)
	{
		$('tipoftheday').update(RAT_Tips[phase]);
	}
	else
	{
		new Ajax.Request(RAT_AJAX_SCRIPT, 
		{
			parameters: {f: 'GetTips', phase: phase},
			onComplete: function(transport) 
			{
				var tips = transport.responseText.evalJSON();
		//alert(transport.responseText);
		
				var html = '';
			
				if(tips.length > 0)
				{
					var randomIndexs = RAT_RandomNumbers(tips.length-1, 4);
					html += "<ul>";
					for (var i=0; i<randomIndexs.length; i++)
					{
						if (tips[randomIndexs[i]])
						{
							html += "<li>"+tips[randomIndexs[i]].Question_Text+"</li>";
						}
					}
					html += "</ul>";
				}
				RAT_Tips[phase] = html;
				$('tipoftheday').update(RAT_Tips[phase]);	
			}
		});	
	}
}

function RAT_RandomNumbers(max, noreq)
{
	var result = new Array();
	while(result.length < noreq)
	{
		var found = 0;
		var rand = Math.floor(Math.random() * max);
		for (var i=0; i<result.length; i++)
		{
			if(rand == result[i])
			{
				found = 1;
				break;
			}
		}
		if (!found)
		{
			result.push(rand);
		}
	}
	return result;
}

function RAT_ValidateNumber(num)
{
	return !isNaN(num);
}

/* 
------------------------------------------
Report functionality
------------------------------------------
*/
function RAT_RenderReport()
{
	var date = new Date();
	var url = "report.php?id="+Scenario.Scenario_ID+"&msecs="+date.getTime();
	new Ajax.Updater('reportContent', url,
	{
		parameters: {}
	});
}

/* 
------------------------------------------
Scenario functionality
------------------------------------------
*/

function RAT_DeleteScenario(scenario_id)
{
	if(confirm('Are you sure you want to permanently delete this Scenario? You will lose all data you have entered into it.'))
	{
		new Ajax.Request(RAT_AJAX_SCRIPT,
			{
				parameters: {f: 'SoftDelete', w: $H({Scenario_ID: scenario_id}).toJSON(), t: 'Scenario'},
				onComplete: function(transport)
				{
					$('Scenario_'+scenario_id).remove();
				}
			});
	}
}

/* 
------------------------------------------
Breadcrumbs functionality
------------------------------------------
*/

function RAT_UpdateBreadcrumbs(value)
{
	$('breadcrumb_4').update(value);
}

/* 
------------------------------------------
Save As functionality
------------------------------------------
*/
function RAT_SaveAsDialog()
{
	new Ajax.Request('saveas.php', {
		parameters: {Scenario_ID: Scenario.Scenario_ID},
		evalScripts: true,
		onComplete: function(transport) {
			var divContent = transport.responseText;
			Modalbox.show(divContent, {width: 470, height: 300, title: '<h2>Save As</h2>', overlayDuration: 0, slideDownDuration: 0, slideUpDuration: 0});
		}
	});
}

function RAT_SaveAsProcess()
{
	// Get the new name
	//var New_Name = $F('Scenario_SaveAs_Name');
	var New_Name = document.getElementById('Scenario_SaveAs_Name').value;
	RAT_Dialog_Hide();

	// Now redirect to the processing page
	document.location.href = "scenario.php?Scenario_ID="+Scenario.Scenario_ID+"&mode=saveas&newname="+URLEncode(New_Name);
}

// Utility function
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

/* 
------------------------------------------
Print functionality
------------------------------------------
*/
function RAT_PrintReport(id)
{
	window.print();
}


/* 
------------------------------------------
Sign-up functionality
------------------------------------------
*/
function RAT_SignupUser()
{
	var data = {first_name: $('first_name').value,
				last_name: $('last_name').value,
				email: $('email').value,
				title: $('title').value,
				company: $('company').value,
				industry: $('00N20000001Kaw8').value,
				comments: $('description').value};

	new Ajax.Request(RAT_AJAX_SCRIPT,
		{
			parameters: {f: 'SignupUser', d: $H(data).toJSON()},
			onComplete: function(transport)
			{
				var result = transport.responseText.evalJSON();
			
				// Check result of signup process
				if (result.Success == 1)
				{
					// submit to salesforce
					$('login_id').value = data.email;
					$('password').value = result.password;
					$('retURL').value += "Login_ID="+ escape(data.email) + "&Password=" + escape(result.password);
					document.signupForm.submit();
				}
				else
				{
					if (result.AccountExists == 1)
					{
						alert("An account already exists with the email address: '"+data.email+"'.\n\nIf you've lost your password or your account has expired, please email us at greenfly@greenflyonline.org.");
					}
					else
					{
						alert("An unknown error has occured.  Please try reloading the page and trying again.");
					}
				}
			}
		});		
						
}


