//Filename: cookies.js

/**
 * **************************************************************** 
 * Custom Cookie Script for WCB                                   *
 * ****************************************************************
 * 
 * This script is used throughout the WCB Safety Calculator form to
 * store form information on the client side using Cookies.  This
 * script should be referenced in all html pages relating to the 
 * calculator.
 *
 * @author Vu Ha, IT Progressions Inc.
 * @email vuha@telus.net
 * @version 1.0
 * @copyright 2001-10-04
 */
 
//////////////////////////////////////////////////////////////////////////////
// Static Date Variables
//////////////////////////////////////////////////////////////////////////////
var TODAY  = new Date();
var EXPIRY = new Date(TODAY.getTime() + 24 * 60 * 60 * 1000); // expires today
//var EXPIRY = new Date(TODAY.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days

//////////////////////////////////////////////////////////////////////////////
// Main Cookie Functions
//////////////////////////////////////////////////////////////////////////////

/**
 * Retrieves the "value" of a name/value pair from the cookie file
 *
 * @param name 
 * @returns value
 */

function getCookie(name) {
	//Retrieve the start position of the cookie name in the text file
	var index = document.cookie.indexOf(name + "=");
	
	//If cannot find value, then return null
	if (index == -1) {
		return null;
	}

	//Set new location of to start value follow "="	
	index = document.cookie.indexOf("=", index) + 1;
	
	//Set the end position of the cookie value in the text file
	var endstr = document.cookie.indexOf(";", index);
	
	//If the value is empty, use the length of the cookie file
	if (endstr == -1) {
		endstr = document.cookie.length;
	}
	
	//Return the value of the cookie name	
	return unescape(document.cookie.substring(index, endstr));
}

/**
 * Sets a name/value pair in the cookie file
 *
 * @param name
 * @param value
 */
 
function setCookie(name, value) {
	if (value != null && value != "") {
		document.cookie=name + "=" + escape(value) + "; expires=" + EXPIRY.toGMTString();
	}
}
 
//////////////////////////////////////////////////////////////////////////////
// Static Variables
//////////////////////////////////////////////////////////////////////////////

/* Arrays for form input values used in cookies
   Note: Arrays follow a sequence pattern of [ x, y, x, y, ......] where
   x = time in hours and y = rate in dollars */

var INCIDENT 			= new Array();					
var INVESTIGATION 		= new Array();			
var DAMAGE 				= new Array();					
var REPLACEMENT 		= new Array();				
var PRODUCTIVITY 		= new Array();

//Number of rows in form page
var INCIDENT_ROWS 		= 8;						
var INVESTIGATION_ROWS 	= 8;
var DAMAGE_ROWS 		= 8;
var REPLACEMENT_ROWS 	= 6;
var PRODUCTIVITY_ROWS 	= 4;

//Number of fixed rows in form page
var INCIDENT_FIXED_ROWS 		= 3;						
var INVESTIGATION_FIXED_ROWS 	= 1;
var DAMAGE_FIXED_ROWS 			= 4;
var REPLACEMENT_FIXED_ROWS 		= 2;
var PRODUCTIVITY_FIXED_ROWS 	= 1;

//Names for pages used in cookies
var INCIDENT_LBL 			= "incident";						
var INVESTIGATION_LBL   	= "investigation";
var DAMAGE_LBL 				= "damage";
var REPLACEMENT_LBL 		= "replacement";
var PRODUCTIVITY_LBL 		= "productivity";
var SCENARIO_LBL 			= "scenario";
var SCENARIO_DESC_LBL		= "scenarioDescription";
var PAGE_DEFAULT_VALUES_LBL = "pageDefaultValues";
var ICON_DETAILS_LBL		= "iconDetailsPage";
var COST_RECOVERY_LBL		= "costRecovery";

//Names for pages used in cookies
var INCIDENT_OC				= 0;
var INVESTIGATION_OC		= 1;
var DAMAGE_OC				= 2;
var REPLACEMENT_OC			= 3;
var PRODUCTIVITY_OC			= 4;
var OTHER_COST_LBL			= "otherCost";

//Names for pages used in cookies
var INCIDENT_PRODUCT_LBL		= "incidentProduct";						
var INVESTIGATION_PRODUCT_LBL   = "investigationProduct";
var DAMAGE_PRODUCT_LBL 			= "damageProduct";
var REPLACEMENT_PRODUCT_LBL		= "replacementProduct";
var PRODUCTIVITY_PRODUCT_LBL	= "productivityProduct";

//Other Cost Null Values
var OTHER_COST			= "!!!!";

//Icon and Details Page Value
var ICON_DETAILS = "!";

//Icon and Details Page Value
var COST_RECOVERY = "!";

//Cost Recovery Values
var PROFIT_MARGIN = 0;
var SALES		  = 0;

//Section totals
var INCIDENT_TOTAL 		 = 0;
var INVESTIGATION_TOTAL  = 0;
var DAMAGE_TOTAL 		 = 0;
var REPLACEMENT_TOTAL 	 = 0; 
var PRODUCTIVITY_TOTAL 	 = 0;

//Total Cost
var TOTAL 				 = 0;

//Default Text Values for Scenario and Scenario Descriptions
var BACK_TXT			= ["Housekeeper Sprains Back",
						   "A motel housekeeper sprained her back while turning a mattress.<br><br>Costs are based on a 1 employer and 5 worker shift.<br><br>Estimated Wage Rates:<br><br>Workers = $12/hr<br>Employer = $20/hr<br>" ];
var BURN_TXT			= ["Worker Burns Ankle and Foot with Hot Oil",
						   "A worker was draining hot oil from a deep fryer into a bucket. The worker picked up the full bucket and splashed hot oil onto her ankle and upper part of her foot causing 2nd degree burns to both areas.<br><br>Costs are based on a 1 employer, 1 supervisor and 9 worker shift.<br><br>Estimated Wage Rates:<br><br>Workers = $10/hr<br>Supervisor = $15/hr<br>Employer = $25/hr"];
var CUT_TXT				= ["Deli Worker Cuts Finger",
						   "While slicing the small end of a cold cut with a meat slicer, a worker sliced off the tip of his left hand's ring finger.<br><br>Costs are based on a 1 employer and 4 worker shift.<br><br>Estimated Wage Rates:<br><br>Workers = $10/hr<br>Employer = $20/hr<br>"];
var FALL_TXT			= ["Worker Slips Fracturing Ankle",
						   "A worker slipped on a wet kitchen floor fracturing his right ankle.<br><br>Costs are based on a 1 employer, 1 supervisor and 15 worker shift.<br><br>Estimated Wage Rates:<br><br>Workers = $10/hr<br>Supervisor = $15/hr<br>Employer = $25/hr"];
var VIOLENCE_TXT		= ["Cashier Traumatized by Armed Robber",
						   "A cashier at a bakery cafe was confronted by an armed robber. The robber made threats, but left without physically injuring any of the staff. The cashier experienced post-traumatic stress after the incident.<br><br>Costs are based on a 1 employer and 9 worker shift. <br><br>Estimated Wage Rates:<br><br>Workers = $10/hr<br>Employer = $25/hr<br>"];

//////////////////////////////////////////////////////////////////////////////
// Form Functions
////////////////////////////////////////////////////////////////////////////// 

/**
* Sets the "!" deliminated value for the cookie pageName that will be used
* in the forms to display the values
*
* @param numRows
* @param fixedRows 
* @param arrayValues
* @param pageName
* @param pageNameProduct
*/

function setCookieValue(numRows, fixedRows, arrayValues, pageName, pageNameProduct) {

	var subtotal = 0;				//Subtotal for the section
	var valuestring = "";			//Value string holder
	var productValueString = "";	//Value string holder	

	//Loop through the array and populate the value string
	for( i=0; i < (numRows - fixedRows) ; i++ ) {
	
		var time = arrayValues[2*i];   		//Note the "2" multiplication is used to skip
		var rate = arrayValues[(2*i)+1];	//through the arrays so there is no conflict
		var product = time * rate;

		productValueString += product + "!";		
				
		subtotal += product;
		valuestring += time + "!" + rate + "!";

	}	
	
	//Loop through the array for the fixed costs and add it too the subtotal
	for( i=2*(numRows - fixedRows); i < arrayValues.length ; i++ ) {	
		var fc = arrayValues[i];	  //Fixed costs rows 
		subtotal += fc;
		valuestring += fc + "!";
		productValueString += fc + "!";				
	}
	
	//Append the subtotal to the end of the value string
	valuestring += subtotal;
	
	//Set the pageName and valuestring to the cookie for use in the forms
	setCookie(pageName, valuestring);
	
	//Set a cookie that uses the pageName to store the values to be used to reset the page scope form
	setCookie(pageName + 'Default', valuestring);	
	
	//Set the pageNameProduct and productValueString to the cookie for use in the print preview summary screen
	setCookie(pageNameProduct, productValueString);	
}

/**
* Sets the Incident cookie value
*/

function setIncident() {
	setCookieValue(INCIDENT_ROWS, INCIDENT_FIXED_ROWS, INCIDENT, INCIDENT_LBL, INCIDENT_PRODUCT_LBL);									
}		

/**
* Sets the Investigation cookie value
*/

function setInvestigation() {
	setCookieValue(INVESTIGATION_ROWS, INVESTIGATION_FIXED_ROWS, INVESTIGATION, INVESTIGATION_LBL, INVESTIGATION_PRODUCT_LBL);									
}

/**
* Sets the Damage cookie value
*/

function setDamage() {
	setCookieValue(DAMAGE_ROWS, DAMAGE_FIXED_ROWS, DAMAGE, DAMAGE_LBL, DAMAGE_PRODUCT_LBL );									
}		

/**
* Sets the Replacement cookie value
*/

function setReplacement() {
	setCookieValue(REPLACEMENT_ROWS, REPLACEMENT_FIXED_ROWS, REPLACEMENT, REPLACEMENT_LBL, REPLACEMENT_PRODUCT_LBL);									
}		

/**
* Sets the Productivity cookie value
*/

function setProductivity() {
	setCookieValue(PRODUCTIVITY_ROWS, PRODUCTIVITY_FIXED_ROWS, PRODUCTIVITY, PRODUCTIVITY_LBL, PRODUCTIVITY_PRODUCT_LBL );									
}		

/**
* Sets the all cookie values for five form pages
*/

function setFormCookieValues() {
	setIncident();
	setInvestigation();
	setDamage();
	setReplacement();
	setProductivity();
}

/**
 * Sets the all cookie values for five form pages
 */
function resetFormCookieValues() {

	//Empty current input values 
	INCIDENT = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
	INVESTIGATION = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
	DAMAGE = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];			
	REPLACEMENT = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];						
	PRODUCTIVITY = [ 0, 0, 0, 0, 0, 0, 0 ];		
	
	//Reset the other costs text boxes
	resetOtherCostTxt();	
	
	//Reset the cookie values using empty array values
	setFormCookieValues();
	
	//Reset the icons and details page
	resetIconDetailsPage();
}

/**
 * Sets the all other costs text boxes to be blank
 */
function resetOtherCostTxt() {

	//Reset the other cost label
	OTHER_COST = "!!!!"
				
	//Now reset the cookies associate w/ them
	setCookie(OTHER_COST_LBL, OTHER_COST);

}

/**
 * Sets the icon and details page to be blank
 */
function resetIconDetailsPage() {

	//Reset the other cost label
	ICON_DETAILS = "!"
				
	//Now reset the cookies associate w/ them
	setCookie(ICON_DETAILS_LBL, ICON_DETAILS);

}

/**
* Sets the default values of the forms based on what the user selects on the homepage
*/

function setDefaultValues(scenarioId) {
		
	switch (scenarioId) {
		//If "Custom" is selected then
		case 0:										

			resetFormCookieValues();			
			setIconDetailsPage('iYourOwn.gif', 'blank_page.html');
			setDefaultCostRecovery(0,0);
			resetOtherCostTxt();			
			break;
		
		//If "Back Injury" is selected then			
		case 1:		
	
			INCIDENT = [ 2, 12, 3.5, 20, 12, 12, 1, 20, 0, 0, 10, 25, 0 ];			
			INVESTIGATION = [ 2, 20, 1, 20, 1, 20, 1, 20, 0, 0, 2, 12, 1, 20, 0 ];
			DAMAGE = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];			
			REPLACEMENT = [ 0, 0, 0, 0, 1, 20, 5, 12, 0, 0 ];						
			PRODUCTIVITY = [ 0, 0, 5, 20, 40, 12, 0 ];
			
			resetOtherCostTxt();
			setFormCookieValues();
			setIconDetailsPage('iBackInjury.gif', 'detailsBackInjury.html');																		
			setDefaultCostRecovery(20,1500);
			setDefaultScenario(BACK_TXT);
			resetOtherCostTxt();												
			break;

		//If "Burn" is selected then
		case 2:

			INCIDENT = [ 2, 15, 3.5, 15, 3, 10, 1, 25, 1, 10, 10, 20, 6.25 ];
			INVESTIGATION = [ 1, 25, 1, 25, 1, 25, 1, 25, 0, 0, 4, 10, 0.5, 25, 7.50 ];
			DAMAGE = [ 1, 25, 0, 0, 1, 25, 0, 0, 0, 0, 300, 0 ];			
			REPLACEMENT = [ 0, 0, 1, 15, 0, 0, 0, 0, 0, 0 ];						
			PRODUCTIVITY = [ 1.5, 10, 2, 25, 20, 10, 32.5 ];
			
			resetOtherCostTxt();
			setFormCookieValues();
			setIconDetailsPage('iBurn.gif', 'detailsBurn.html');																								
			setDefaultCostRecovery(5,1700);
			setDefaultScenario(BURN_TXT);
			resetOtherCostTxt();															
			break;
			
		//If "Cut" is selected then			
		case 3:

			INCIDENT = [ 1.5, 20, 3.5, 10, 6.5, 10, 0, 20, 0.5, 10, 10, 20, 0 ];
			INVESTIGATION = [ 1, 20, 1, 20, 1, 20, 1, 20, 0, 20, 1.5, 10, 0.5, 20, 0 ];
			DAMAGE = [ 0.5, 10, 0.25, 10, 0, 0, 1, 10, 0, 0, 0, 0 ];			
			REPLACEMENT = [ 4, 20, 0, 0, 1, 20, 2, 10, 0, 0 ];						
			PRODUCTIVITY = [ 4.5, 10, 2, 20, 16, 10, 0 ];
			
			resetOtherCostTxt();
			setFormCookieValues();
			setIconDetailsPage('iCut.gif', 'detailsCut.html');						
			setDefaultCostRecovery(10,500);
			setDefaultScenario(CUT_TXT);
			resetOtherCostTxt();																											
			break;

		//If "Slip & Fall" is selected then									
		case 4:	
	
			INCIDENT = [ 2, 15, 3.5, 15, 7.75, 10, 1, 25, 0.25, 10, 5, 20, 6.25 ];
			INVESTIGATION = [ 0.5, 25, 1, 25, 1, 25, 1, 25, 0, 20, 3.5, 10, 0.25, 25, 3.75 ];
			DAMAGE = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];			
			REPLACEMENT = [ 0, 0, 1, 15, 0, 0, 0, 0, 0, 0 ];						
			PRODUCTIVITY = [ 1, 10, 2, 25, 20, 10, 32.50 ];
			
			resetOtherCostTxt();
			setFormCookieValues();
			setIconDetailsPage('iSlipFall.gif', 'detailsSlipFall.html');						
			setDefaultCostRecovery(7,3000);
			setDefaultScenario(FALL_TXT);
			resetOtherCostTxt();																					
			break;
			
		//If "Violence" is selected then				
		case 5:	

			INCIDENT = [ 0, 10, 0, 10, 36, 10, 4, 25, 0, 10, 0, 0, 0 ];
			INVESTIGATION = [ 15, 25, 1, 25, 1, 25, 1.5, 25, 5, 25, 4.5, 10, 1, 25, 0 ];
			DAMAGE = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2700, 0 ];			
			REPLACEMENT = [ 16, 25, 0, 0, 24, 25, 16, 10, 0, 0 ];						
			PRODUCTIVITY = [ 36, 10, 5, 25, 20, 10, 0 ];
			
			resetOtherCostTxt();
			setFormCookieValues();
			setIconDetailsPage('iViolence.gif', 'detailsViolence.html');						
			setDefaultCostRecovery(10,2000);
			setDefaultScenario(VIOLENCE_TXT);
			resetOtherCostTxt();																									
			break;

		//If something else is selected			
		default:
			//Do nothing
			break;			
	}
}

/**
 * Updates the form as well as the cookie values for the calculator
 * 
 * @param numRows
 * @param fixedRows
 * @param pageName 
 * @param pageNameProduct
 */
function updateAll(numRows, fixedRows, pageName, pageNameProduct) {

	//Iterate through the rows, calculate and populate the row totals		
	for( i=0; i < (numRows - fixedRows); i++ ) {
		var time = document.getElementById("time" + i).value;
		var rate = document.getElementById("rate" + i).value;
		document.getElementById("product" + i).value = time * rate;
	}
	
	// Iterate through the rows and calculate the subtotal
	var subtotal = 0;
	for( i=0; i < numRows; i++ ) {
		subtotal += parseInt(document.getElementById("product" + i).value);
	}
	
	//Set the subtotal box to the calculated value
	document.getElementById("subtotal").value = subtotal;
	
	//Loop through the form and populate the value string
	var valuestring = "";
	for( i=0; i < (numRows - fixedRows); i++ ) {
		var time = document.getElementById("time" + i).value;
		var rate = document.getElementById("rate" + i).value;
		valuestring += time + "!" + rate + "!";
	}
	
	//Loop through the form for the fixed costs and append to the value string
	for( i=(numRows - fixedRows); i < numRows ; i++ ) {	
		var fc = document.getElementById("product" + i).value;	  //Fixed costs rows 
		valuestring += fc + "!";		
	}
	
	//Loop through the form and retrieve the product values of each row and store into productValueString
	var productValueString = "";
	for( i=0; i < numRows; i++ ) {
		var product = document.getElementById("product" + i).value;
		productValueString += product + "!";
	}	
	
	//Append the subtotal to the end of the value string
	valuestring += subtotal;
	
	//Update the cookie name value
	setCookie(pageName, valuestring);	

	//Update the cookie name value
	setCookie(pageNameProduct, productValueString);	
}

/**
 * Populates the form w/ the cookie values
 * 
 * @param numRows
 * @param fixedRows
 * @param arrayValue
 * @param pageName 
 * @param pageNameProduct 
 */
function populate(numRows, fixedRows, pageName, pageNameProduct) {

	var rawcookie = getCookie(pageName);
	var theArray = rawcookie.split("!");
	var time = 0;
	var rate = 0;

	//Iterate through the rows and populate the form
	for( i=0; i < (numRows - fixedRows); i++ ) {
		time = theArray[2*i];
		rate = theArray[(2*i)+1];
		document.getElementById('time' + i).value = time;
		document.getElementById('rate' + i).value = rate;
	}
	
	//Temporary variable used to properly populate the form
	var productLabelNumber = numRows - fixedRows;

	//Iterate through the fixed costs rows and populate the form
	for( i=2*(numRows-fixedRows); i < (theArray.length - 1); i++ ) {
		var product = theArray[i];
		document.getElementById('product' + productLabelNumber).value = product;
		productLabelNumber = productLabelNumber+1;
	}
	
	//Update the cookie 
	updateAll(numRows, fixedRows, pageName, pageNameProduct);
}

/**
 * Resets the page values to the default values using the populate() function and setting
 * the pageName to pageNameDefault
 * 
 *@param name
 */
function restoreDefaultValues(numRows, fixedRows, pageName, pageNameProduct) {

	//Refreshes the default values for the page
	var rawcookie = "";
	rawcookie = getCookie(pageName + 'Default');	
	var theArray = rawcookie.split("!");
	var time = 0;
	var rate = 0;

	//Iterate through the rows and populate the form
	for( i=0; i < (numRows - fixedRows); i++ ) {
		time = theArray[2*i];
		rate = theArray[(2*i)+1];
		document.getElementById('time' + i).value = time;
		document.getElementById('rate' + i).value = rate;
	}
	
	//Temporary variable used to properly populate the form
	var productLabelNumber = numRows - fixedRows;

	//Iterate through the fixed costs rows and populate the form
	for( i=2*(numRows-fixedRows); i < (theArray.length - 1); i++ ) {
		var product = theArray[i];
		document.getElementById('product' + productLabelNumber).value = product;
		productLabelNumber = productLabelNumber+1;
	}

	//Update the cookie 
	updateAll(numRows, fixedRows, pageName, pageNameProduct);			
	
	//Restore the OtherCost box to empty	
	document.getElementById("otherCost").value = "";	
	
}

/**
 * Calculates totals for all sub-sections as well as the grand total
 */
function calculateTotals() {

	var rawcookie = getCookie(INCIDENT_LBL);
	var theArray = rawcookie.split("!");
	INCIDENT_TOTAL = parseInt(theArray[theArray.length-1]);
	
	rawcookie = getCookie(INVESTIGATION_LBL);
	theArray = rawcookie.split("!");
	INVESTIGATION_TOTAL = parseInt(theArray[theArray.length-1]);
	
	rawcookie = getCookie(DAMAGE_LBL);
	theArray = rawcookie.split("!");
	DAMAGE_TOTAL = parseInt(theArray[theArray.length-1]);
	
	rawcookie = getCookie(REPLACEMENT_LBL);
	theArray = rawcookie.split("!");
	REPLACEMENT_TOTAL = parseInt(theArray[theArray.length-1]);
	
	rawcookie = getCookie(PRODUCTIVITY_LBL);
	theArray = rawcookie.split("!");
	PRODUCTIVITY_TOTAL = parseInt(theArray[theArray.length-1]);
	
	TOTAL = INCIDENT_TOTAL + INVESTIGATION_TOTAL + DAMAGE_TOTAL + REPLACEMENT_TOTAL + PRODUCTIVITY_TOTAL;
}

/**
 * Populates the print summary page w/ the cookie values
 * 
 */
function populatePrintSummary() {

	//Patch Code to display rate and time values in summary page

	//Variables for cookies that need to be retrieved to display values
	var incidentCookie = getCookie(INCIDENT_LBL); 
	var investigationCookie = getCookie(INVESTIGATION_LBL);
	var damageCookie = getCookie(DAMAGE_LBL);
	var replacementCookie = getCookie(REPLACEMENT_LBL);
	var productivityCookie = getCookie(PRODUCTIVITY_LBL);
	
	//Arrays for cookie values to loop through
	var incidentArray = incidentCookie.split('!');
	var investigationArray = investigationCookie.split('!');
	var damageArray = damageCookie.split('!');
	var replacementArray = replacementCookie.split('!');
	var productivityArray = productivityCookie.split('!');
	
	//Loop through each of the arrays and only retrieve the rate and time values
	//Start at 0 and go until 48
	
	//Incident Array
	for ( i = 0; i < 10; i++) {
		var rateTime = incidentArray[i];
		document.getElementById('summary' + i).value = rateTime;
	}
	
	//Investigation Array
	for ( i = 0; i < 14; i++) {
		var j = i + 10;
		var rateTime = investigationArray[i];
		document.getElementById('summary' + j).value = rateTime;
	}
	
	//Damage Array
	for ( i = 0; i < 8; i++) {
		var j = i + 24;
		var rateTime = damageArray[i];
		document.getElementById('summary' + j).value = rateTime;
	}
	
	//Replacement Array
	for ( i = 0; i < 10; i++) {
		var j = i + 32;
		var rateTime = replacementArray[i];
		document.getElementById('summary' + j).value = rateTime;
	}	
	
	//Productivity Array
	for ( i = 0; i < 6; i++) {
		var j = i + 42;
		var rateTime = productivityArray[i];
		document.getElementById('summary' + j).value = rateTime;
	}	
	
	//Code now to output the product values for the form
	
	var totalRows = INCIDENT_ROWS + INVESTIGATION_ROWS + DAMAGE_ROWS + REPLACEMENT_ROWS + PRODUCTIVITY_ROWS;
	var productNames = [ INCIDENT_PRODUCT_LBL, INVESTIGATION_PRODUCT_LBL, DAMAGE_PRODUCT_LBL, REPLACEMENT_PRODUCT_LBL, PRODUCTIVITY_PRODUCT_LBL ];
	var rawcookie = "";				
		
	//Loop through all the Product cookies and add them to one main text string
	for ( i = 0; i < 5; i++) {
		rawcookie += getCookie(productNames[i]);
	}
	
	//Now we take the text string and split it up into an array
	var theArray = rawcookie.split("!");			
	
	//Iterate through the rows and populate the form
	for( i=0; i < totalRows; i++ ) {
		var product = theArray[i];
		document.getElementById('product' + i).value = product;
	}	
}


//////////////////////////////////////////////////////////////////////////////
// Miscellaneous Functions
//////////////////////////////////////////////////////////////////////////////

/**
 * Sets the icon image and detailsPage location for the file
 *
 *@param iconName
 *@param detailsPage
*/

function setIconDetailsPage(iconName, detailsPage) {
	//Set the values of the icons and details page
	var tempArray = [iconName, detailsPage];	
	var updateIconDetailsPage = tempArray[0] + "!" + tempArray[1];		
	
	//Set the cookie file
	setCookie(ICON_DETAILS_LBL, updateIconDetailsPage );
}

/**
 * Gets the icon image 
 * @param otherCostPageName
*/

function getIcon() {

	//Set the values of the other Cost
	var tempIconDetails = getCookie(ICON_DETAILS_LBL);
	var tempArray = tempIconDetails.split("!");
	
	//Set the form value
	return tempArray[0];
	
}

/**
 * Gets the details page
 * @param otherCostPageName
*/

function getDetailsPage() {

	//Set the values of the other Cost
	var tempIconDetails = getCookie(ICON_DETAILS_LBL);
	var tempArray = tempIconDetails.split("!");
	
	//Set the form value
	return tempArray[1];
	
}

/**
* Sets the scenario and scenario description into the cookie text file
*/

function setScenario() {
	resetFormCookieValues();

	//Set the cookie file
	setCookie(SCENARIO_LBL, document.getElementById(SCENARIO_LBL).value );
	setCookie(SCENARIO_DESC_LBL, document.getElementById(SCENARIO_DESC_LBL).value );
}


/**
* Sets the default scenario and scenario description into the cookie text file
*/

function setDefaultScenario(arrayName) {

	//Set the values of the scenario and scenario description
	document.getElementById(SCENARIO_LBL).value = arrayName[0];
	document.getElementById(SCENARIO_DESC_LBL).value = arrayName[1];

	//Set the cookie file
	setCookie(SCENARIO_LBL, document.getElementById(SCENARIO_LBL).value );
	setCookie(SCENARIO_DESC_LBL, document.getElementById(SCENARIO_DESC_LBL).value );
}

/**
 * Sets the other cost values into the cookie text file
 * 
 *@param otherCostPageName
*/

function setOtherCost(otherCostPageName) {

	//Set the values of the other Cost
	var tempOtherCost = getCookie(OTHER_COST_LBL);
	var tempArray = tempOtherCost.split("!");
	
	tempArray[otherCostPageName] = document.getElementById('otherCost').value;
	
	var updatedOtherCost = tempArray[0] + "!" + tempArray[1] + "!" + tempArray[2] + "!" + tempArray[3] + "!" + tempArray[4];		
	
	//Set the cookie file
	setCookie(OTHER_COST_LBL, updatedOtherCost );
	
}

/**
 * Gets the other cost values from the cookie text file and puts it into the form
 * 
 *@param otherCostPageName
*/

function getOtherCost(otherCostPageName) {

	//Set the values of the other Cost
	var tempOtherCost = getCookie(OTHER_COST_LBL);
	var tempArray = tempOtherCost.split("!");
	
	//Set the form value
	document.getElementById('otherCost').value = tempArray[otherCostPageName];
	
}

/**
 * Resets the other cost values into the cookie text file
 * 
 *@param otherCostPageName
*/

function resetOtherCost(otherCostPageName) {

	//Reset the form value
	document.getElementById('otherCost').value = "";
	
	//Update the cookie value
	setOtherCost(otherCostPageName);
	
}

/**
 * Outputs the Other Costs Values
 * 
 *@param otherCostPageName
*/

function printOtherCost(otherCostPageName) {

	//Get the other cost from the cookie
	var tempOtherCost = getCookie(OTHER_COST_LBL);
	var tempArray = tempOtherCost.split("!");
	
	//Write the other cost out in the html page if it exists
	if (tempArray[otherCostPageName] == "") {
		//Do Nothing
	} else {	
		document.writeln('(' + tempArray[otherCostPageName] + ')' );	
	}

}

/**
* Validates input to make sure it is numeric
*
* @param input
* @param numRows
* @param fixedRows
* @param pageName
* @param pageNameProduct
*/
function validate(input, numRows, fixedRows, pageName, pageNameProduct) {

	var validNumbers = "1234567890.";					//Valid numerical input values
	var text = document.getElementById(input).value;	//Input text
		
	//Loop through the input and extract each character and compare it to the validNumbers set
	for ( i = 0; i < text.length; i++ ) {	
	  var tempStr = text.substring(i, i+1);

	  if ( validNumbers.indexOf(tempStr) == -1 ) {
		alert("Please enter a valid number");
		break;
	  } else {
	  	updateAll(numRows, fixedRows, pageName, pageNameProduct);
	  }
	  	
	}
}

/**
 * Re-populates cookie values that strangely dissappear during links
 *
 * Note: This is a code patch to the system that must be called when clicking on links
 * that leave the page.
 */

function repopulateCookies() {

	setCookie('incident', getCookie('incident'));
	setCookie('investigation', getCookie('investigation'));
	setCookie('damage', getCookie('damage'));
	setCookie('replacement', getCookie('replacement'));
	setCookie('productivity', getCookie('productivity'));	

	setCookie('incidentDefault', getCookie('incidentDefault'));
	setCookie('investigationDefault', getCookie('investigationDefault'));
	setCookie('damageDefault', getCookie('damageDefault'));
	setCookie('replacementDefault', getCookie('replacementDefault'));
	setCookie('productivityDefault', getCookie('productivityDefault'));
	
	setCookie('incidentProduct', getCookie('incidentProduct'));
	setCookie('investigationProduct', getCookie('investigationProduct'));
	setCookie('damageProduct', getCookie('damageProduct'));
	setCookie('replacementProduct', getCookie('replacementProduct'));
	setCookie('productivityProduct', getCookie('productivityProduct'));			
	
	setCookie('iconDetailsPage', getCookie('iconDetailsPage'));
	setCookie('costRecovery', getCookie('costRecovery'));	
	setCookie('scenario', getCookie('scenario'));
	setCookie('scenarioDescription', getCookie('scenarioDescription'));	

}

//////////////////////////////////////////////////////////////////////////////
// Add-on: Cost Recovery Functions
//////////////////////////////////////////////////////////////////////////////

/**
 * Sets the default cost recovery values
 *
 *@param profit
 *@param sales
 */

function setDefaultCostRecovery(profit, sales) {
	//Set the values of the average profits and sales
	var tempArray = [profit, sales];	
	var updateCostRecovery = tempArray[0] + "!" + tempArray[1];		
	
	//Set the cookie file
	setCookie(COST_RECOVERY_LBL, updateCostRecovery );
}

/**
* Validates cost recovery input to make sure it is numeric
*
* @param input
*/
function validateCostRecoveryValues(input) {

	var validNumbers = "1234567890.";					//Valid numerical input values
	var text = document.getElementById(input).value;	//Input text
		
	//Loop through the input and extract each character and compare it to the validNumbers set
	for ( i = 0; i < text.length; i++ ) {	
	  var tempStr = text.substring(i, i+1);

	  if ( validNumbers.indexOf(tempStr) == -1 ) {
		alert("Please enter a valid number");
		break;
	  } else {
	  	updateCostRecovery();
	  }
	  	
	}
}

/**
 * Updates the cost recovery values
 */

function updateCostRecovery() {

	//Get the new values from the form
	var newProfit = document.getElementById('profit').value;
	var newSales = document.getElementById('sales').value;
	
	//Update the cookie values
	setDefaultCostRecovery(newProfit, newSales);
	
	//Re-populate the form
	populateCostRecovery();	
	
}

/**
 * Rounds number to X places
 *
 */


function round(number,X) {
	// rounds number to X decimal places, defaults to 2
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

/**
 * Populate the Cost Recovery Table
 *
 */

function populateCostRecovery() {
	
	var total = TOTAL;
	
	//Populate editable regions
	document.getElementById('profit').value = getAverageProfit();
	document.getElementById('sales').value = getAverageSales();
	
	//Populate Recovery Cost row
	document.getElementById('avgMargin1').value = Math.round(getAverageProfit()) - 2;
	document.getElementById('avgMargin2').value = Math.round(getAverageProfit());
	document.getElementById('avgMargin3').value = Math.round(getAverageProfit()) + 2;	
	
	/*
	//Populate Average Gross Sales row
	document.getElementById('avgSales1').value = Math.round(getAverageSales() * 0.98);
	document.getElementById('avgSales2').value = Math.round(getAverageSales());
	document.getElementById('avgSales3').value = Math.round(getAverageSales() * 1.02);
	*/
	
	//Populate Gross Sales required to recover accident cost row
	document.getElementById('grossSales1').value = Math.round(total/((getAverageProfit()/100) - 0.02));
	document.getElementById('grossSales2').value = Math.round(total/(getAverageProfit()/100));
	document.getElementById('grossSales3').value = Math.round(total/((getAverageProfit()/100) + 0.02));
	
	//Populate Gross Sales required to recover accident cost row
	document.getElementById('days1').value = round(Math.round(total/((getAverageProfit()/100) - 0.02))/getAverageSales(), 1);
	document.getElementById('days2').value = round(Math.round(total/(getAverageProfit()/100))/getAverageSales(), 1);
	document.getElementById('days3').value = round(Math.round(total/((getAverageProfit()/100) + 0.02))/getAverageSales(), 1);				
}

/**
 * Gets the average profit value image 
 */

function getAverageProfit() {

	//Set the values of the cost recovery
	var tempCostRecoveryDetails = getCookie(COST_RECOVERY_LBL);
	var tempArray = tempCostRecoveryDetails.split("!");
	
	//Set the form value
	return tempArray[0];
	
}

/**
 * Gets the average sales value image 
 */

function getAverageSales() {

	//Set the values of the cost recovery
	var tempCostRecoveryDetails = getCookie(COST_RECOVERY_LBL);
	var tempArray = tempCostRecoveryDetails.split("!");
	
	//Set the form value
	return tempArray[1];
	
}

