


//=============================
//
// Drying Area (Measurements) Control/Navigation
//


// Update Outside Conditions
function updateOutsideConditions(projectID,dateIndex,useCelsius) {

	
	// create input values
	
	// Get the form
	var myForm = createForm(window,'myForm');
	
	// Project ID
	addPostToForm(myForm,'pid',projectID);
	
	
	// Date
	var dateField = "date[" + dateIndex + "]";
	var dateObject = window.document.getElementsByName(dateField);
	var date = dateObject[0].value;

	var dateInput = window.document.createElement('input');
	dateInput.type = 'hidden';
	dateInput.id = 'date';
	dateInput.name = 'date';
	dateInput.value = date;
	myForm.appendChild(dateInput);
	
	// Get Temperature ID
	var temperatureIDObj = window.document.getElementsByName('temperatureID');
	temperatureID = 1;
	if(temperatureIDObj.length > 0) {
		temperatureID = temperatureIDObj[0].value;	
	}
	addPostToForm(myForm,'temperatureID',temperatureID);
	
	
	// Get Temperature
	var temperatureField = "outsideTemp[" + dateIndex + "]";
	var temperatureObject = window.document.getElementsByName(temperatureField);
	var tempValue = temperatureObject[0].value;
	if(isNaN(tempValue)){
		if(temperature != "") {
			tempValue = 0;
			temperatureObject[0].value = 0;
		} else {
			temperatureObject[0].value = "";	
		}
	}

	
	// Get Humidity
	var humidityField = "outsideRH[" + dateIndex + "]";
	var humidityObject = window.document.getElementsByName(humidityField);
	var rhValue = humidityObject[0].value;
	if(isNaN(rhValue)) {
		if(rhValue != "") {
			rhValue = 0;
			humidityObject[0].value = 0;
		} else {
			humidityObject[0].value = "";	
		}
	}
	
	var humidityID = $("#humidityID").val();
	var gppPure = calcGPP_withTempCheck(tempValue,rhValue);
	if(humidityID == 2) { gppPure = gppToGpkg(gppPure); }
	var gpp = gppPure.toFixed(1);
	var gppField = "outsideGPP[" + dateIndex + "]";
	var gppObject = window.document.getElementsByName(gppField);
	gppObject[0].value = gpp;
	
	
	// Flag the GPP RED if:
	// The Inside Conditions had not been entered
	if(tempValue == null || rhValue == null || tempValue == "" || rhValue == ""){
		gppObject[0].style.backgroundColor = '#FF9999';	
		gppObject[0].value = "";
	} else {
		gppObject[0].style.backgroundColor = '#FFFFFF';
	}
	
	
	// Dew Points
	var dewField = "insideDew[" + dateIndex + "]";
	var insideTempValue = window.document.getElementsByName('insideTemp[' + dateIndex + ']')[0].value;
	var insideRHValue = window.document.getElementsByName('insideRH[' + dateIndex + ']')[0].value;
	updateDewPointField(dewField, tempValue, insideTempValue, insideRHValue, temperatureID);
	
	
	// Grain Dep
	var grainDepFieldName = "insideGD[" + dateIndex + "]";
	var insideGPPValue = window.document.getElementsByName("insideGPP[" + dateIndex + "]")[0].value;
	updateInsideVsOutsideGrainDepression(grainDepFieldName, dewField, gpp, insideGPPValue);
	
	
	// Set the temperature/humidity
	addPostToForm(myForm,'temperature',tempValue);
	addPostToForm(myForm,'humidity',rhValue);
	
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	// Go to the Code to Update the Database
	var location = '/site/projects/dryingArea/updateOutsideConditions.php';
	myForm.target = 'hiddenFrame';
	myForm.action = location;
	myForm.submit();
}

//=============================
//
// Update Inside Conditions
//
function updateInsideConditions(projectID,roomid,dateIndex) {

	
	
	// Get the form
	var myForm = createForm(window,'myForm');
	
	
	// Project ID / Room ID
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	
	// Date
	var dateField = "date[" + dateIndex + "]";
	var dateObject = window.document.getElementsByName(dateField);
	var date = dateObject[0].value;

	addPostToForm(myForm,'date',date);

	
	// Get Temperature ID
	var temperatureIDObj = window.document.getElementsByName('temperatureID');
	temperatureID = 1;
	if(temperatureIDObj.length > 0) {
		temperatureID = temperatureIDObj[0].value;	
	}
	addPostToForm(myForm,'temperatureID',temperatureID);
	
	
	
	// Get Temperature
	var temperatureField = "insideTemp[" + dateIndex + "]";
	var temperatureObject = window.document.getElementsByName(temperatureField);
	var tempValue = temperatureObject[0].value;
	if(isNaN(tempValue)){
		if(temperature != "") {
			tempValue = 0;
			temperatureObject[0].value = 0;
		} else {
			temperatureObject[0].value = "";	
		}
	}
	
	
	// Get Humidity
	var humidityField = "insideRH[" + dateIndex + "]";
	var humidityObject = window.document.getElementsByName(humidityField);
	var rhValue = humidityObject[0].value;
	if(isNaN(rhValue)) {
		if(rhValue != "") {
			rhValue = 0;
			humidityObject[0].value = 0;
		} else {
			humidityObject[0].value = "";	
		}
	}
	
	
	
	// GPP
	var humidityID = $("#humidityID").val();
	var gppPure = calcGPP_withTempCheck(tempValue,rhValue);
	if(humidityID == 2) { gppPure = gppToGpkg(gppPure); }
	var gpp = gppPure.toFixed(1);
	var gppField = "insideGPP[" + dateIndex + "]";
	var gppObject = window.document.getElementsByName(gppField);
	gppObject[0].value = gpp;
	
	
	

	// Flag the GPP RED if:
	// The Inside Conditions had not been entered
	if(tempValue == null || rhValue == null || tempValue == "" || rhValue == ""){
		gppObject[0].style.backgroundColor = '#FF9999';	
		gppObject[0].value = "";
	} else {
		gppObject[0].style.backgroundColor = '#FFFFFF';
	}
	
	
	
	// Dew Points
	var dewField = "insideDew[" + dateIndex + "]";
	var outsideTempValue = window.document.getElementsByName('outsideTemp[' + dateIndex + ']')[0].value;
	updateDewPointField(dewField, outsideTempValue, tempValue, rhValue, temperatureID);
	
	
	// Grain Dep
	var grainDepFieldName = "insideGD[" + dateIndex + "]";
	var outsideGPPValue = window.document.getElementsByName("outsideGPP[" + dateIndex + "]")[0].value;
	updateInsideVsOutsideGrainDepression(grainDepFieldName, dewField, outsideGPPValue, gpp);
	
	
	// Set the temperature
	addPostToForm(myForm,'temperature',tempValue);
	
	// Set the humidity
	addPostToForm(myForm,'humidity',rhValue);
	
	
	// Update any Grain Depressions values for the day
	var numDHsArray = window.document.getElementsByName("numDHs");
	var numDHs = numDHsArray[0].value;

	for(var dhIndex=0;dhIndex<numDHs;dhIndex++) {
		
			
			// Get the DH Temp
			var outputTempField = "dhOutputTemp[" + dhIndex + "][" + dateIndex + "]";
			var outputTempObject = window.document.getElementsByName(outputTempField);
			var outputTemp = outputTempObject[0].value;
			
			
			// Get the DH RH
			var outputRHField = "dhOutputRH[" + dhIndex + "][" + dateIndex + "]";
			var outputRHObject = window.document.getElementsByName(outputRHField);
			var outputRH = outputRHObject[0].value;
			
			
			// Set values zero if data has not been entered
			if(tempValue == null || 
				rhValue == null ||
				outputTemp == null || 
				outputRH == null ||
				tempValue == "" ||
				rhValue == "" ||
				outputTemp == "" ||
				outputRH == ""
			) {
				var outputGPP = 0;
				var gdPure = 0;	
			} else {
			
				// Get the DH GPP
				var outputGPP = calcGPP_withTempCheck(outputTemp,outputRH);
				if(humidityID == 2) outputGPP = gppToGpkg(outputGPP);
				outputGPP = outputGPP.toFixed(1);
				
				// Recalculate GPP
				var gdPure = gpp - outputGPP;
			}
			var gd = gdPure.toFixed(1);
			if(gd == -0.0) {
				gd = 0.0;	
			}
	
			// Update the GD Field
			var outputGDField = "grainDepression[" + dhIndex + "][" + dateIndex + "]";		
			var outputGDObject = window.document.getElementsByName(outputGDField);
			outputGDObject[0].value = gd;
			
			
			// Flag the GD RED if:
			// 1) The GD is negative
			// 2) The Inside Conditions had not been entered
			// 3) The Output Conditions had not been entered
			if(gd < 0 ||
				tempValue == null || 
				rhValue == null ||
				outputTemp == null || 
				outputRH == null ||
				tempValue == "" ||
				rhValue == "" ||
				outputTemp == "" ||
				outputRH == ""
			){
				outputGDObject[0].style.backgroundColor = '#FF9999';	
			} else {
				outputGDObject[0].style.backgroundColor = '#FFFFFF';
			}
			
			if(	tempValue == null ||
			   	rhValue == null ||
				outputTemp == null || 
				outputRH == null ||
				tempValue == "" ||
				rhValue == "" ||
				outputTemp == "" ||
				outputRH == ""
			){
				outputGDObject[0].value = "";	
			}



	}
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	// Go to the Code to Update the Database
	myForm.method = 'post';
	myForm.target = 'hiddenFrame';
	myForm.action = '/site/projects/dryingArea/updateInsideConditions.php';
	
	myForm.submit();
}




//=================================
//
// Update Dew Point FIeld
//
function updateDewPointField(dewPointFieldName, outsideTempValue, insideTempValue, insideRHValue, temperatureID) {
	
	// Dew Points
	var dewPointObject = window.document.getElementsByName(dewPointFieldName);
	if(dewPointObject.length > 0) {
		var dewPointValue = -9999;
		if(insideTempValue != null && insideRHValue != null && insideTempValue != "" && insideRHValue != "") {
			var dewPointPure = dewPoint_withTempCheck(insideTempValue,insideRHValue);
			dewPointValue = dewPointPure.toFixed(1);
			dewPointObject[0].style.backgroundColor = "#FFFFFF";
		} else {
			dewPointValue = "";	
			dewPointObject[0].style.backgroundColor = "#FF9999";
		}
		
		dewPointObject[0].value = dewPointValue;
		
		// Set coloring for 'inside dew point vs outside temperature' flagging.
		var dewDiff = 5;	
		if(temperatureID == 2 || temperatureID == 3) {
			dewDiff = rankineToKelvin(5);
		}
		if(outsideTempValue != null && outsideTempValue != "") {
			if(dewPointValue > outsideTempValue - dewDiff) {
				dewPointObject[0].style.backgroundColor = "#AAAAFF";
			} else {
				if(insideTempValue == null || insideTempValue == "" || insideRHValue == null || insideRHValue == "") {
					dewPointObject[0].style.backgroundColor = "#FF9999";
				} else {
					dewPointObject[0].style.backgroundColor = "#FFFFFF";
				}
			}
		} else {
			if(dewPointObject[0].value == "") {
				dewPointObject[0].style.backgroundColor = "#FF9999";
			} else {
				dewPointObject[0].style.backgroundColor = "#AAAAFF";
			}
		}
	}
	
}


//===============================================
//
// Update Inside v. Outside Grain Depression
//
function updateInsideVsOutsideGrainDepression(grainDepFieldName, dewPointFieldName, outsideGPPValue, insideGPPValue) {


	// skip if there is no grain dep field
	var grainDepObject = window.document.getElementsByName(grainDepFieldName);
	if(grainDepObject.length == 0) {
		return;
	}

	// calc gd
	var gd = '';
	if(outsideGPPValue != "" && insideGPPValue != "" && !isNaN(outsideGPPValue) && !isNaN(insideGPPValue)) {
		gd = outsideGPPValue - insideGPPValue;
		gd = gd.toFixed(1);
	}
	
	// set gd
	grainDepObject[0].value = gd;
	
	// set color
	if(gd == '' || gd < 0) {
		grainDepObject[0].style.backgroundColor = '#FF9999';	
	} else {
		var dewPointObject = window.document.getElementsByName(dewPointFieldName);
		if(dewPointObject.length > 0) {
			var dewBackgroundColor = dewPointObject[0].style.backgroundColor;
			grainDepObject[0].style.backgroundColor = dewBackgroundColor;
			
		}
	}
}


//===============================================
//
// Update Moisture Content Point
//
function updateMoistureContentPoint(projectID,roomid,mcPointIndex,dateIndex) {	
	
	// mcPoint
	var mcField = "mcPoint[" + mcPointIndex + "]";
	var mcObject = window.document.getElementsByName(mcField);
	var mcPoint = mcObject[0].value;
	
	
	// Date
	var dateField = "date[" + dateIndex + "]";
	var dateObject = window.document.getElementsByName(dateField);
	var date = dateObject[0].value;

	
	// WME
	var wmeField = "wme[" + mcPointIndex + "][" + dateIndex + "]"; 
	var wmeObject = window.document.getElementsByName(wmeField);
	var wme = wmeObject[0].value;
	if(isNaN(wme) && wme != null) {
		wme = '';
		wmeObject[0].value = '';
	}
	
	// Get Post Data
	var myForm = createForm(window,'myForm');
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'mcPoint',mcPoint);
	addPostToForm(myForm,'date',date);
	addPostToForm(myForm,'wme',wme);
	
	//
	var uid = window.document.getElementsByName('uid')[0].value;
	
	
	// Go to the Code to Update the Database
	createFrame(window,'hiddenFrame');
	myForm.target = 'hiddenFrame';
	myForm.action = '/site/projects/dryingArea/updateMoistureContentPoint.php';
	myForm.submit();
	

}


//=================================
//
// Update Moisture Content Details
// (Standard / Location)
//
function updateMoistureContentDetails(projectID,roomid,mcPointIndex) {


	
	// mcPoint
	var mcField = "mcPoint[" + mcPointIndex + "]";
	var mcObject = window.document.getElementsByName(mcField);
	var mcPoint = mcObject[0].value;
	
	
	// Location 
	var locationField = "location[" + mcPointIndex + "]";
	var locationObject = window.document.getElementsByName(locationField);
	var locationValue = locationObject[0].value;
	if(locationValue == "") {
		locationValue = "Point " + mcPoint;
		locationObject[0].value = locationValue;
	}
	
	
	
	// Standard
	var standardField = "mdsStandard[" + mcPointIndex + "]";
	var standardObject = window.document.getElementsByName(standardField);
	var standardValue = standardObject[0].value;
	if(standardValue == "" || standardValue == undefined || isNaN(standardValue)) {
		standardValue = 0;
		standardObject[0].value = 0;
	}



	// Get Post Data
	var myForm = createForm(window,'myForm');
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'mcPoint',mcPoint);
	addPostToForm(myForm,'location',locationValue);
	addPostToForm(myForm,'standard',standardValue);
	

	
	// Go to the Code to Update the Database
	createFrame(window,'hiddenFrame');
	myForm.target = 'hiddenFrame';
	myForm.action = '/site/projects/dryingArea/updateMoistureContentDetails.php';
	myForm.submit();
	
}






//===========================================
//
// Update Moisture Map Additional Information
//
function updateMoistureMapAdditionalInformation(projectID,roomid) {

	// Get the form
	var myForm = createForm(window,'myForm');
	
	// Flush TinyMCE
	try {flushDryingAreaMoistureMapTinyMCE();} catch(err) {}
	
	// Get data
	var instrumentUsed = window.document.getElementsByName('instrumentUsed')[0].value;
	var notes = window.document.getElementsByName('notes')[0].value;
	
	// Project ID / Room ID
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'instrumentUsed',instrumentUsed);
	addPostToForm(myForm,'notes',notes);
	
	
	// Go to the Code to Update the Database
	createFrame(window,'hiddenFrame');
	var location = '/site/projects/dryingArea/updateMoistureContentAdditionalInformation.php';
	myForm.target = 'hiddenFrame';
	myForm.action = location;
	myForm.submit();
	
	$.post("/site/projects/dryingArea/updateMoistureContentAdditionalInformation.php",$("#moistureMapForm").serialize(), function(data) {if(data!="") alert(data);});
	
}



//========================================================
//
// Functions
//
function gotoDryingAreaPage(roomid) {
	var modeOptions = window.document.dryingArea.dryingAreaMode;
	var selectedIndex = modeOptions.selectedIndex;
	var pageType = modeOptions.options[selectedIndex].value;
	if(pageType == 'dryingAreaDetails') {
		address = '/site/projects/dryingArea/dryingAreaDetails.php';
	} else if(pageType == 'dryingAreaDesign') {
		address = '/site/projects/dryingArea/dryingAreaDesign.php';
	} else if(pageType == 'dryingAreaPhotos') {
		address = '/site/projects/dryingArea/dryingAreaPhotos.php';
	} else {
		address = '/site/projects/dryingArea/dryingAreaMoistureMap.php';
	}
	window.location = address + '?id=' + roomid;
	
	return false;
}

//==========================================
//
// Flip Between Drying Area Designs 
//
function gotoDryingAreaDesign() {
	var roomOptions = window.document.dryingAreas.dryingAreaSelect;
	var selectedIndex = roomOptions.selectedIndex;
	var roomid = roomOptions.options[selectedIndex].value;

	var basePage = '/site/projects/dryingArea/dryingAreaDesign.php';
	
	if(roomid == -1) {
		var address = '/site/projects/projectView.php?show=rooms';
	} else if(roomid != "") {
		var address = basePage + '?id=' + roomid;
	} else  {
		var address = basePage;
	}
	window.location = address;
}


//==========================================
//
// Flip Between Drying Area Photos 
//
function gotoDryingAreaPhotos() {
	var roomOptions = window.document.dryingAreas.dryingAreaSelect;
	var selectedIndex = roomOptions.selectedIndex;
	var roomid = roomOptions.options[selectedIndex].value;

	var basePage = '/site/projects/dryingArea/dryingAreaPhotos.php';
	
	if(roomid == -1) {
		var address = '/site/projects/projectView.php?show=rooms';
	} else if(roomid != "") {
		var address = basePage + '?id=' + roomid;
	} else  {
		var address = basePage;
	}
	window.location = address;
}


//==========================================
//
// Flip Between Drying Area Details 
//
function gotoDryingAreaDetails() {
	var roomOptions = window.document.dryingAreas.dryingAreaSelect;
	var selectedIndex = roomOptions.selectedIndex;
	var roomid = roomOptions.options[selectedIndex].value;

	var basePage = '/site/projects/dryingArea/dryingAreaDetails.php';
	
	if(roomid == -1) {
		var address = '/site/projects/projectView.php?show=rooms';
	} else if(roomid != "") {
		var address = basePage + '?id=' + roomid;
	} else  {
		var address = basePage;
	}
	window.location = address;
}


//==========================================
//
// Flip Between Drying Area Moisture Maps
//
function gotoDryingAreaMoistureMap() {
	var roomOptions = window.document.dryingAreas.dryingAreaSelect;
	var selectedIndex = roomOptions.selectedIndex;
	var roomid = roomOptions.options[selectedIndex].value;

	var basePage = '/site/projects/dryingArea/dryingAreaMoistureMap.php';
	
	if(roomid == -1) {
		var address = '/site/projects/projectView.php?show=rooms';
	} else if(roomid != "") {
		var address = basePage + '?id=' + roomid;
	} else  {
		var address = basePage;
	}
	window.location = address;
}


//==========================================
//
// Add Moisture Content Points
//
function addMoistureContentPoints(projectID,roomid,addEdit) {
	
	
	// Get the form
	var myForms = window.document.getElementsByName('moistureMapForm');
	var myForm = myForms[0];
	
	
	// Project ID / Room ID
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	// Add/Edit
	addPostToForm(myForm,'addEdit',addEdit);
	
	
	
	// Num Points
	// If an invalid value is given, reset field to '1' and ignore the call.
	var numNewPoints = myForm.numNewPoints.value;
	var pointsInput = window.document.createElement('input');
	pointsInput.type = 'hidden';
	pointsInput.id = 'numPoints';
	pointsInput.name = 'numPoints';
	if(numNewPoints == "" || numNewPoints == undefined || isNaN(numNewPoints) || numNewPoints <= 0 ) {
		myForm.numNewPoints.value = 1;
		return false;
	}
	numNewPoints = Math.floor(numNewPoints);
	if(numNewPoints > 50) {
		numNewPoints = 50;	
	}
	myForm.numNewPoints.value = numNewPoints;
	if(numNewPoints > 10) {
		var answer2 = confirm("Double Check:\n\nAre you sure you wish to add " + numNewPoints + " new points?");
		if(answer2 == false) {
			return false;
		}
	}
	pointsInput.value = numNewPoints;
	myForm.appendChild(pointsInput);
	
	
	// Add the Points to the Database
	myForm.target = '_top';
	myForm.action = '/site/projects/dryingArea/addMoistureContentPoint.php';
	myForm.submit();
}



//==========================================
//
// Add Moisture Content Points
//
function addNewMoistureContentPoints(projectID,roomid) {
	
	
	// Get the form
	var myForms = window.document.getElementsByName('moistureMapForm');
	var myForm = myForms[0];
	
	
	
	// Project ID / Room ID
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	// Add/Edit
	addPostToForm(myForm,'addEdit','Add');
	
	
	// Num Points
	// If an invalid value is given, reset field to '1' and ignore the call.
	var numNewPoints = myForm.numNewPoints.value;
	var pointsInput = window.document.createElement('input');
	pointsInput.type = 'hidden';
	pointsInput.id = 'numPoints';
	pointsInput.name = 'numPoints';
	if(numNewPoints == "" || numNewPoints == undefined || isNaN(numNewPoints) || numNewPoints <= 0 ) {
		myForm.numNewPoints.value = 1;
		return false;
	}
	numNewPoints = Math.floor(numNewPoints);
	if(numNewPoints > 50) {
		numNewPoints = 50;	
	}
	myForm.numNewPoints.value = numNewPoints;
	if(numNewPoints > 10) {
		var answer2 = confirm("Double Check:\n\nAre you sure you wish to add " + numNewPoints + " new points?");
		if(answer2 == false) {
			return false;
		}
	}
	pointsInput.value = numNewPoints;
	myForm.appendChild(pointsInput);
	
	
	// Add the Points to the Database
	myForm.target = '_top';
	myForm.action = '/site/projects/dryingArea/addMoistureContentPoint.php';
	myForm.submit();
}




//==========================================
//
// Remove Moisture Content Point
//
function deleteMoistureContentPoint(projectID, roomid, mcPointIndex,addEdit) {
	
	
	// Get the form
	var myForms = window.document.getElementsByName('moistureMapForm');
	var myForm = myForms[0];
	
	
	// Location 
	var locationField = "location[" + mcPointIndex + "]";
	var locationObject = window.document.getElementsByName(locationField);
	var locationValue = locationObject[0].value;
	
	
	var answer = confirm("Are you sure you wish to permanently delete '" + locationValue + '"?');
	
	if(answer == true) {
		
					
		// Project ID / Room ID
		addPostToForm(myForm,'pid',projectID);
		addPostToForm(myForm,'roomid',roomid);
		
		
			
			
		
		// Add/Edit
		addPostToForm(myForm,'addEdit',addEdit);
		
			
		// mcPoint
		var mcField = "mcPoint[" + mcPointIndex + "]";
		var mcObject = window.document.getElementsByName(mcField);
		var mcPoint = mcObject[0].value;
		addPostToForm(myForm,'mcPoint',mcPoint);
		
		
		
		// Remove the Points to the Database
		myForm.target = '_top';
		myForm.action = '/site/projects/dryingArea/deleteMoistureContentPoint.php';
		myForm.submit();
	}
}





//=============================
//
// Update Dehumidifier Conditions
//
function updateDHConditions(projectID,roomid,dateIndex,dhIndex,mdsID) {

	
	// Get the form
	var temperatureID = window.document.getElementsByName('temperatureID')[0].value;
	
	
	//
	// Set Form Data
	//
	var myForm = createForm(window,'myForm');
	
	
	// Date
	var dateField = "date[" + dateIndex + "]";
	var dateObject = window.document.getElementsByName(dateField);
	var date = dateObject[0].value;
	addPostToForm(myForm,'date',date);


	
	// Equipment ID
	var equipmentField = "dhID[" + dhIndex + "]";
	var equipmentObject = window.document.getElementsByName(equipmentField);
	var eqid = equipmentObject[0].value;
	addPostToForm(myForm,'eqid',eqid);
	
	
	// Get Temperature
	var temperatureField = "dhOutputTemp[" + dhIndex + "][" + dateIndex + "]";
	var temperatureObject = window.document.getElementsByName(temperatureField);
	var tempValue = temperatureObject[0].value;
	if(isNaN(tempValue)){
		if(temperature != "") {
			tempValue = 0;
			temperatureObject[0].value = 0;
		} else {
			temperatureObject[0].value = "";	
		}
	}

	
	// Get Humidity
	var humidityField = "dhOutputRH[" + dhIndex + "][" + dateIndex + "]";
	var humidityObject = window.document.getElementsByName(humidityField);
	var rhValue = humidityObject[0].value;
	if(isNaN(rhValue)) {
		if(rhValue != "") {
			rhValue = 0;
			humidityObject[0].value = 0;
		} else {
			humidityObject[0].value = "";
		}
	}
	
	
	// Set outputGPP
	var humidityID = $("#humidityID").val();
	var gppPure = calcGPP_withTempCheck(tempValue,rhValue);
	if(humidityID == 2) { gppPure = gppToGpkg(gppPure);	}
	var outputGPP = gppPure.toFixed(1);
	
	var gppField = "dhOutputGPP[" + dhIndex + "][" + dateIndex + "]";
	var gppObject = window.document.getElementsByName(gppField);
	gppObject[0].value = outputGPP;
	
	
	// Get Inside Temp
	var insideTempField = "insideTemp[" + dateIndex + "]";
	var insideTempObject = window.document.getElementsByName(insideTempField);
	var insideTemp = insideTempObject[0].value;
	
	
	// Get Inside Humidity
	var insideRHField = "insideRH[" + dateIndex + "]";
	var insideRHObject = window.document.getElementsByName(insideRHField);
	var insideRH = insideRHObject[0].value;
	
	// Get inside GPP
	var insideGPP = calcGPP_withTempCheck(insideTemp,insideRH);
	if(humidityID == 2) insideGPP = gppToGpkg(insideGPP);
	
	
	
	
	// Flag the GPP RED if:
	// The output conditions had not been entered.
	if(tempValue == null || rhValue == null || tempValue == "" || rhValue == "") {
		gppObject[0].style.backgroundColor = '#FF9999';	
		gppObject[0].value = "";
	} else {
		gppObject[0].style.backgroundColor = '#FFFFFF';
	}
	
	
	// Set the Grain Depression
	var gdPure = insideGPP - outputGPP;
	var outputGDField = "grainDepression[" + dhIndex + "][" + dateIndex + "]";
	if(isNaN(gdPure)) {
		gdPure = 0;
	}
	var outputGDObject = window.document.getElementsByName(outputGDField);
	gd = gdPure.toFixed(1);
	if(gd == -0.0) {
		gd = 0.0;	
	}
	outputGDObject[0].value = gd;
	
	
	// Flag the GD RED if:
	// 1) The GD is negative
	// 2) The Inside conditions had not been entered.
	// 3) The output conditions had not been entered.
	if(gd < 0 ||
		tempValue == null ||
		rhValue == null ||
		insideTemp == null || 
		insideRH == null ||
		tempValue == "" ||
		rhValue == "" ||
		insideTemp == "" ||
		insideRH == ""
	){
		outputGDObject[0].style.backgroundColor = '#FF9999';	
	} else {
		outputGDObject[0].style.backgroundColor = '#FFFFFF';
	}
	
	
	
	// If the GD is red due to missing data (not negative gd)
	// display value as zero
	if(
		tempValue == null ||
		rhValue == null ||
		insideTemp == null || 
		insideRH == null ||
		tempValue == "" ||
		rhValue == "" ||
		insideTemp == "" ||
		insideRH == ""
	) {
		outputGDObject[0].value = "";	
	}
	
	
	
	
	
	// Post
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'temperature',tempValue);
	addPostToForm(myForm,'temperatureID',temperatureID);
	addPostToForm(myForm,'humidity',rhValue);
	addPostToForm(myForm,'mdsID',mdsID);
	
	
	// Go to the Code to Update the Database
	createFrame(window,'hiddenFrame');
	myForm.target = 'hiddenFrame';
	myForm.action = '/site/projects/dryingArea/updateDHConditions.php';
	myForm.submit();
}



//=====================================================================================
//=====================================================================================
//
// Drying Area Details
//


//
// Use the Estimated Linear Wall Affected
//
function dryingAreaDetailsUseEstimatedLinearWall(projectID,roomid) {


	// Get the estimated values
	var estimatedLinearWallObj = window.document.getElementsByName('estimatedLinearWall')[0];
	var estimatedLinearWallShortObj = window.document.getElementsByName('estimatedLinearWallShort')[0];
	
	// Get the current values
	var linearLengthObj = window.document.getElementsByName('linearLength')[0];
	var linearLengthShortObj = window.document.getElementsByName('linearLengthShort')[0];
	
	// copy estimated in current
	linearLengthObj.value = estimatedLinearWallObj.value;
	linearLengthShortObj.value = estimatedLinearWallShortObj.value;
	
	// update the drying area details in the database
	if(roomid != 0 || projectID != 0) {
		updateDryingAreaDetailsGeneralInformation(projectID,roomid,0);
	}
}



//
// Update Drying Area Details General Information
//
function updateDryingAreaDetailsGeneralInformation(projectID,roomid,refreshFlag) {


	// Get the form
	var myForms = window.document.getElementsByName('dryingAreaDetailsForm');
	var myForm = myForms[0];
	
	// Original Room Name
	var currentRoomNameField = "currentRoomName";
	var currentRoomNameObject = window.document.getElementsByName(currentRoomNameField);
	var currentRoomName = currentRoomNameObject[0].value;
	
	// Get the length conversion value
	var lengthID = window.document.getElementsByName('lengthID')[0].value;
	
	
	// Room Name
	var roomNameField = "roomName";
	var roomNameObject = window.document.getElementsByName(roomNameField);
	var roomName = roomNameObject[0].value;
	if(roomName == "" || roomName == undefined) {
		alert("Drying Areas must be named.");
		roomNameObject[0].value = currentRoomName;
		return false;
	}
	
	
	// Build-out Density
	var buildOutDensityObj = window.document.getElementsByName('buildOutDensity');
	if(buildOutDensityObj.length > 0) {
		var buildOutDensity = buildOutDensityObj[0].value;
		addPostToForm(myForm,'buildOutDensity',buildOutDensity);
	}
	
	
	// Building Construction
	var buildingConstructionObj = window.document.getElementsByName('buildingConstruction');
	if(buildingConstructionObj.length > 0) {
		var buildingConstruction = buildingConstructionObj[0].value;
		addPostToForm(myForm,'buildingConstruction',buildingConstruction);
	}
	
	
	// HVAC
	var hvacObj = window.document.getElementsByName('hvac');
	if(hvacObj.length > 0) {
		var hvac = hvacObj[0].value;
		addPostToForm(myForm,'hvac',hvac);
	}
	
	
	// Envelope
	var envelopeObj = window.document.getElementsByName('envelope');
	if(envelopeObj.length > 0) {
		var envelope = envelopeObj[0].value;
		addPostToForm(myForm,'envelope',envelope);
	}
	
	
	// Weather Conditions
	var weatherConditionsObj = window.document.getElementsByName('weatherConditions');
	if(weatherConditionsObj.length > 0) {
		var weatherConditions = weatherConditionsObj[0].value;
		addPostToForm(myForm,'weatherConditions',weatherConditions);
	}
	
	// CFM Error
	var cfmErrorObj = window.document.getElementsByName('cfmError');
	var cfmError = 10;
	if(cfmErrorObj.length > 0) {	
		cfmError = parseInt(cfmErrorObj[0].value);
		addPostToForm(myForm,'cfmError',cfmError);
	}
	
	
	// Project Mode
	var projectModeObj = window.document.getElementsByName('projectMode');
	var projectMode = 0;
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}
	addPostToForm(myForm,'projectMode',projectMode);
	
	
	// Air Change Rate
	var airChangeResults = calculateAirChangeRate();
	addPostToForm(myForm,'minutesPerVolumeChange',airChangeResults['ACR'].toFixed(0));
	
	
	//
	// Get Dimensions
	//
	
	// Small unit fractional
	var smallFractional;
	if(lengthID == 1) {
		smallFractional = 12.;
	} else if(lengthID == 2) {
		smallFractional = 100.;	
	}
	
	
	// length
	var lengthObject = window.document.getElementsByName("roomLength");
	var lengthInObject = window.document.getElementsByName("roomLengthIn");
	var length = parseFloat(lengthObject[0].value) + (parseFloat(lengthInObject[0].value) / smallFractional);
	var lengthInput = window.document.createElement('input');
	addPostToForm(myForm,'length',length);
	
	// width
	var widthObject = window.document.getElementsByName("roomWidth");
	var widthInObject = window.document.getElementsByName("roomWidthIn");
	var width = parseFloat(widthObject[0].value) + (parseFloat(widthInObject[0].value) / smallFractional);
	var widthInput = window.document.createElement('input');
	addPostToForm(myForm,'width',width);
	
	// height
	var heightObject = window.document.getElementsByName("roomHeight");
	var heightInObject = window.document.getElementsByName("roomHeightIn");
	var height = parseFloat(heightObject[0].value) + (parseFloat(heightInObject[0].value) / smallFractional);
	var heightInput = window.document.createElement('input');
	addPostToForm(myForm,'height',height);

	
	// linear wall
	var linearWallObject = window.document.getElementsByName("linearLength")[0];
	if(isNaN(linearWallObject.value) || linearWallObject.value == "") {
		linearWallObject.value = 0;
	}
	var linearWall = parseFloat(linearWallObject.value);
	var linearWallShortObject = window.document.getElementsByName("linearLengthShort")[0];
	if(isNaN(linearWallShortObject.value) || linearWallShortObject.value == "") {
		linearWallShortObject.value = 0;
	}
	var linearWallShort = parseFloat(linearWallShortObject.value);
	var linearWallLength = linearWall + (linearWallShort / smallFractional);
	addPostToForm(myForm,'linearWall',linearWallLength);

	 
	//Flooring Savable
		if(document.getElementsByName("flooringSavable")!=null && document.getElementsByName("flooringSavable").length>0)
	{
	var flooringSavableObject = window.document.getElementsByName("flooringSavable")[0];
	if(flooringSavableObject != null) {
		var flooringSavable = 'No';
		if(flooringSavableObject) {
			flooringSavable = flooringSavableObject.options[flooringSavableObject.selectedIndex].value;
		}
		addPostToForm(myForm,'flooringSavable',flooringSavable);
	}
	}
	
	//Flooring Savable Reason
	if(document.getElementsByName("flooringSavableReason")!=null && document.getElementsByName("flooringSavableReason").length>0)
	{
		var flooringSavableReasonObject = window.document.getElementsByName("flooringSavableReason")[0];
		if(flooringSavableReasonObject != null) {
			var flooringSavableReason = '';
			if(flooringSavableReasonObject) {
				flooringSavableReason = flooringSavableReasonObject.options[flooringSavableReasonObject.selectedIndex].value;
			}
			addPostToForm(myForm,'flooringSavableReason',flooringSavableReason);
		}
	}
	
	//Flooring Saved
		if(document.getElementsByName("flooringSaved")!=null && document.getElementsByName("flooringSaved").length>0)
	{
	var flooringSavedObject = window.document.getElementsByName("flooringSaved")[0];
	if(flooringSavedObject != null) {
		var flooringSaved = 'No';
		if(flooringSavedObject) {
			flooringSaved = flooringSavedObject.options[flooringSavedObject.selectedIndex].value;
		}
		addPostToForm(myForm,'flooringSaved',flooringSaved);
	}
	}
	
	//Flooring Not Saved Reason
		if(document.getElementsByName("flooringNotSavedReason")!=null && document.getElementsByName("flooringNotSavedReason").length>0)
	{
	var flooringNotSavedReasonObject = window.document.getElementsByName("flooringNotSavedReason")[0];
	if(flooringNotSavedReasonObject != null){
		var flooringNotSavedReason = '';
		if(flooringNotSavedReasonObject) {
			flooringNotSavedReason = flooringNotSavedReasonObject.options[flooringNotSavedReasonObject.selectedIndex].value;
		}
		addPostToForm(myForm,'flooringNotSavedReason',flooringNotSavedReason);	
	}
	}
	
	//NonFloor Material Trim Object
		if(document.getElementsByName("nonFloorMaterialTrim")!=null && document.getElementsByName("nonFloorMaterialTrim").length>0)
	{
	var nonFloorMaterialTrimObject = window.document.getElementsByName("nonFloorMaterialTrim")[0];
	if(nonFloorMaterialTrimObject != null) {
		var nonFloorMaterialTrim = '';
		if(nonFloorMaterialTrimObject) {
			nonFloorMaterialTrim = nonFloorMaterialTrimObject.checked ? 'Trim' : '';
		}
		addPostToForm(myForm,'nonFloorMaterialTrim',nonFloorMaterialTrim);
	}
	}
	
	//NonFloor Material Cabinet
		if(document.getElementsByName("nonFloorMaterialCabinets")!=null && document.getElementsByName("nonFloorMaterialCabinets").length>0)
	{
	var nonFloorMaterialCabinetsObject = window.document.getElementsByName("nonFloorMaterialCabinets")[0];
	if(nonFloorMaterialCabinetsObject != null) {
		var nonFloorMaterialCabinets = '';
		if(nonFloorMaterialCabinetsObject) {
			nonFloorMaterialCabinets = nonFloorMaterialCabinetsObject.checked ? 'Cabinets' : '';
		}
		addPostToForm(myForm,'nonFloorMaterialCabinets',nonFloorMaterialCabinets);
	}
	}
	//NonFloor Material Wall
		if(document.getElementsByName("nonFloorMaterialWall")!=null && document.getElementsByName("nonFloorMaterialWall").length>0)
	{
	var nonFloorMaterialWallObject = window.document.getElementsByName("nonFloorMaterialWall")[0];
	if(nonFloorMaterialWallObject != null) {
		var nonFloorMaterialWall = '';
		if(nonFloorMaterialWallObject) {
			nonFloorMaterialWall = nonFloorMaterialWallObject.checked ? 'Wall' : '';
		}
		addPostToForm(myForm,'nonFloorMaterialWall',nonFloorMaterialWall);
	}
	}
	
    if(document.getElementsByName("nonFlooringSavable")!=null && document.getElementsByName("nonFlooringSavable").length>0)
	{
	  var nonFlooringSavableObject = window.document.getElementsByName("nonFlooringSavable")[0];
	  if(nonFlooringSavableObject.selectedIndex =! null) {
		var nonFlooringSavable = 'No';
		if(nonFlooringSavableObject) {
			nonFlooringSavable = nonFlooringSavableObject.options[nonFlooringSavableObject.selectedIndex].value;
		}
		addPostToForm(myForm,'nonFlooringSavable',nonFlooringSavable);
	  }
	}
	
		if(document.getElementsByName("nonFlooringNotSavedReason")!=null && document.getElementsByName("nonFlooringNotSavedReason").length>0)
	{
	var nonFlooringNotSavedReasonObject = window.document.getElementsByName("nonFlooringNotSavedReason")[0];
	if(nonFlooringNotSavedReasonObject != null) {
		var nonFlooringNotSavedReason = '';
		if(nonFlooringNotSavedReasonObject) {
			nonFlooringNotSavedReason = nonFlooringNotSavedReasonObject.options[nonFlooringNotSavedReasonObject.selectedIndex].value;
		}
		addPostToForm(myForm,'nonFlooringNotSavedReason',nonFlooringNotSavedReason);
	}
	}
	
	// Post Data
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	
	// Update Recommendations
	calcDryingAreaS500();
	
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	// Go to the Code to Update the Database
	var location = '/site/projects/dryingArea/updateDryingAreaDetails.php';
	myForm.target = 'hiddenFrame';
	myForm.action = location;
	myForm.method = 'post';
	
	
	
	flushTinyMCE('areaDescription');
	
	$.post("/site/projects/dryingArea/updateDryingAreaDetails.php", $("#dryingAreaDetailsForm").serialize(),
		function(data) {
			if(data != "") alert(data);
		}
	);
	
	
	
	// Refresh screen
	if(refreshFlag == 1) {
		var msDelay = 1000;
		setTimeout("forceRefresh();",msDelay);
	}
}

//
// At least zero
//
function atLeastZero(objName) {

	var obj = document.getElementsByName(objName);
	var value = obj[0].value;
	if(value == "" || isNaN(value)) {
		value = 0;
		obj[0].value = 0;
	}
}

//
// Calculate Drying Area's S500 Recommendations
//
function calcDryingAreaS500() {

	// project mode
	var projectMode = 0;
	var projectModeObj = window.document.getElementsByName('projectMode');
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}


	// Class
	var classFactor = parseInt(document.getElementsByName("classFactor")[0].value);
	
	// Get the fluid conversion value
	var fluidID = window.document.getElementsByName('fluidID')[0].value;
	
	// Get the Drying Area Sizes
	var dryingAreaResults = getDryingAreaSizes();

	var volume = dryingAreaResults['volume'];
	var area = dryingAreaResults['area'];
	var fullVolume = dryingAreaResults['fullVolume'];
	var fullArea = dryingAreaResults['fullArea'];
	var linearWall = dryingAreaResults['linearWall'];
	var lengthID = dryingAreaResults['lengthID'];
	
	

	// Get the spread
	var ACHdelta = .3;
	var cfmErrorObj = window.document.getElementsByName('cfmError');
	if(cfmErrorObj.length > 0) {
		ACHdelta = parseFloat(cfmErrorObj[0].value) / 100.0;
	}
	
	
	
	// change Change Rate (CFMs)
	var airChangesObjects = document.getElementsByName("airChangesPerMinute");
	var ACRobj = calculateAirChangeRate();
	airChangesObjects[0].value = "Every " + ACRobj['ACR'].toFixed(0) + " minutes (" + ACRobj['mult'].toFixed(2) + " times an hour)";
	
	// Desiccant CFMs
	var desiccantCFMresults = calculateDesiccantCFMs(fullVolume, ACRobj['mult'], ACHdelta);
	window.document.getElementsByName("CFM")[0].value = desiccantCFMresults['print'];
	var usedDesiccantCFMsObj = window.document.getElementsByName('desiccantCFMUsedValue');
	if(usedDesiccantCFMsObj.length > 0) setRowColor('usedCFMrow',desiccantCFMresults,usedDesiccantCFMsObj[0].value);	

	
	// Conventional/LGR AHAMs
	var AHAMresults = calculateAHAMconventional(classFactor, fullVolume, fluidID);
	window.document.getElementsByName("AHAM")[0].value = AHAMresults['print'];
	var AHAMlgrResults = calculateAHAMlgr(classFactor, fullVolume, fluidID);
	window.document.getElementsByName("AHAMLGR")[0].value = AHAMlgrResults['print'];
	
	var AHAMmergedResults = [];
	if(AHAMresults['min'] < AHAMlgrResults['min']) {
		AHAMmergedResults['min'] = AHAMresults['min'];
	} else {
		AHAMmergedResults['min'] = AHAMlgrResults['min'];
	}
	AHAMmergedResults['max'] = 9999999999999999999.999999;
	
	var AHAMobj = window.document.getElementsByName('AHAMUsedValue');
	if(AHAMobj.length > 0) setRowColor('usedAHAMrow',AHAMmergedResults,AHAMobj[0].value);	
	
	
	// Air Scrubbers
	var ASresults = calculateAirScrubbers(volume, ACRobj['mult'],ACHdelta);
	window.document.getElementsByName("AS")[0].value = ASresults['print'];
	var ASobj = window.document.getElementsByName('ASUsedValue');
	if(ASobj.length > 0) setRowColor('usedASrow',ASresults,ASobj[0].value);	
	

	// Air Movers
	

	var AMresults = calculateAirMovers(linearWall, area);
	window.document.getElementsByName("AM")[0].value = AMresults['print'];
	var AMS500results = calculateS500AirMovers(linearWall);
	window.document.getElementsByName("AMS500")[0].value = AMS500results['print'];
	var AMobj = window.document.getElementsByName('AMUsedValue');
	var AMS500mergedResults = calculateAirMoversProjectMode(linearWall, area, projectMode);
	
	if(AMobj.length > 0) setRowColor('usedAMrow',AMS500mergedResults,AMobj[0].value);	
	

	return true;
}

//===============================
//
// Get Drying Area Sizes
//
function getDryingAreaSizes() {


	// Get the length conversion value
	var lengthID = window.document.getElementsByName('lengthID')[0].value;
	var smallFractional = 0;
	if(lengthID == 1) {
		smallFractional = 12.;	
	} else if(lengthID == 2) {
		smallFractional = 100.;	
	}
	
	// Dimensions
	atLeastZero("roomLength");
	atLeastZero("roomLengthIn");
	atLeastZero("roomWidth");
	atLeastZero("roomWidthIn");
	atLeastZero("roomHeight");
	atLeastZero("roomHeightIn");
	
	var roomWidth 			= parseFloat(document.getElementsByName("roomWidth")[0].value);
	var roomWidthIn			= parseFloat(document.getElementsByName("roomWidthIn")[0].value);
	var roomLength 			= parseFloat(document.getElementsByName("roomLength")[0].value);
	var roomLengthIn		= parseFloat(document.getElementsByName("roomLengthIn")[0].value);
	var roomHeight 			= parseFloat(document.getElementsByName("roomHeight")[0].value);
	var roomHeightIn		= parseFloat(document.getElementsByName("roomHeightIn")[0].value);
	
	// Merge Dimensions
	var length = roomLength + roomLengthIn/smallFractional;
	var width = roomWidth + roomWidthIn/smallFractional;
	var height = roomHeight + roomHeightIn/smallFractional;
	
	
	// Get number of inset/offsets
	var numInsetOffsets = window.document.getElementsByName('numRoomOffIn')[0].value;
	
	
	// For each inset/offset
	var fullArea = length * width;
	var fullVolume = fullArea * height;
	var fullEstimatedLinearValue = 2 * (length + width);
	for(var i=0;i<numInsetOffsets;i++) {
		var id = window.document.getElementsByName('roomOffIn_' + i)[0].value;
		var type = window.document.getElementsByName('roomOffInSwitch_' + id)[0].value;
		var setValue = 1;
		if(type == "Inset") {
			setValue = -1;	
		}
		atLeastZero("roomLength_" + id);
		atLeastZero("roomLengthIn_" + id);
		atLeastZero("roomWidth_" + id);
		atLeastZero("roomWidthIn_" + id);
		atLeastZero("roomHeight_" + id);
		atLeastZero("roomHeightIn_" + id);
		
		var insetOffsetLength = parseFloat(window.document.getElementsByName("roomLength_" + id)[0].value);
		var insetOffsetLengthIn = parseFloat(window.document.getElementsByName("roomLengthIn_" + id)[0].value);
		insetOffsetLength = insetOffsetLength + (insetOffsetLengthIn / smallFractional);
		var insetOffsetWidth = parseFloat(window.document.getElementsByName("roomWidth_" + id)[0].value);
		var insetOffsetWidthIn = parseFloat(window.document.getElementsByName("roomWidthIn_" + id)[0].value);
		insetOffsetWidth = insetOffsetWidth + (insetOffsetWidthIn / smallFractional);
		var insetOffsetHeight = parseFloat(window.document.getElementsByName("roomHeight_" + id)[0].value);
		var insetOffsetHeightIn = parseFloat(window.document.getElementsByName("roomHeightIn_" + id)[0].value);
		insetOffsetHeight = insetOffsetHeight + (insetOffsetHeightIn / smallFractional);
		
		fullArea = fullArea + (insetOffsetLength * insetOffsetWidth * setValue);
		fullVolume = fullVolume + (insetOffsetLength * insetOffsetWidth * insetOffsetHeight * setValue);
		
		fullEstimatedLinearValue = fullEstimatedLinearValue + (2 * (insetOffsetLength + insetOffsetWidth));
	}
	
	
	// Percentage Area Affected
	var ratioAreaAffected	= parseFloat(document.getElementsByName("percentageAreaAffected")[0].value);
	
	// Area/Volume/Linear
	var area = fullArea * ratioAreaAffected;
	var volume = fullVolume * ratioAreaAffected;
	var estimatedLinearValue = fullEstimatedLinearValue * ratioAreaAffected;
	
	// Update the area/volume displayed
	var areaObj = window.document.getElementsByName('roomArea')[0];
	var volumeObj = window.document.getElementsByName('roomVolume')[0];
	areaObj.value = area.toFixed(1);
	volumeObj.value = fullVolume.toFixed(1);

	
	// Linear
	atLeastZero('linearLength');
	atLeastZero('linearLengthShort');
	var linearWall = parseFloat(window.document.getElementsByName("linearLength")[0].value);
	var linearWallShort = parseFloat(window.document.getElementsByName("linearLengthShort")[0].value);
	linearWall = linearWall + (linearWallShort/smallFractional);
	
	
	
	//
	// See if the linear wall estimation fields exist
	// (update values if they do)
	//
	var estimatedLinearWallObjList = window.document.getElementsByName('estimatedLinearWall');
	if(estimatedLinearWallObjList.length > 0) {
		var estimatedLinearWallObj = estimatedLinearWallObjList[0];
		var estimatedLinearWallShortObj = window.document.getElementsByName('estimatedLinearWallShort')[0];
		var estimatedLinearWallMiddle = Math.floor(estimatedLinearValue);
		var estimatedLinearWallShort = Math.round((estimatedLinearValue - estimatedLinearWallMiddle) * smallFractional);
		
		estimatedLinearWallObj.value = estimatedLinearWallMiddle;
		estimatedLinearWallShortObj.value = estimatedLinearWallShort;
	
	}
	
	// convert to imperical, if needed
	// (feet, square feet, cubic feet)
	if(lengthID == 2) {
		area = area * 10.764;
		fullArea = fullArea * 10.764;
		volume = volume * 35.3146;
		fullVolume = fullVolume * 35.3146;
		linearWall = linearWall * 3.28;
	}
	
	// Results
	var resultObj = [];
	resultObj['area'] = area;
	resultObj['fullArea'] = fullArea;
	resultObj['volume'] = volume;
	resultObj['fullVolume'] = fullVolume;
	resultObj['linearWall'] = linearWall;
	resultObj['lengthID'] = lengthID;
	
	return resultObj;

}

//===============================
//
// Set Row Color
//
function setRowColor(rowName, resultObj, usedValue) {
	
	var flag = "green";
	if((usedValue > Math.ceil(resultObj['max'].toFixed(0))) || (usedValue < Math.floor(resultObj['min'].toFixed(0)) )) {
		flag = "red";	
	}
	var rowObject = window.document.getElementsByName(rowName);
	if(rowObject.length > 0) {
		if(flag == "red") {
			rowObject[0].style.backgroundColor = "#FF8888";	
		} else {
			rowObject[0].style.backgroundColor = "#DEFFDE";
		}
	}
}


//===============================================
//
// Calculate Desiccant CFMs
//
function calculateDesiccantCFMs(volume, ach, ratioSpread) {
	
	
	// Project Mode
	var projectMode = 0;
	var projectModeObj = window.document.getElementsByName('projectMode');
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}
	
	var value = Math.ceil(ach * volume / 60);
	
	var deviation = value * ratioSpread;
	var minValue = Math.ceil(value - deviation);
	var maxValue = Math.ceil(value + deviation);
	var printLine = "";
	if(projectMode == 1) {
		printLine = minValue.toFixed(0) + " to " + maxValue.toFixed(0) + " CFMs (" + value.toFixed(0) + " ± " + deviation.toFixed(0) + " CFMs)";
	} else {
		printLine = value.toFixed(0) + " CFMs (minimum)";	
		maxValue = 99999999999999999999999999999999.999;
		deviation = 0;
	}
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = Math.ceil(deviation);
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
	
}


//===============================================
//
// Calculate AHAM Conventional
//
function calculateAHAMconventional(classFactor, volume, fluidID) {
	
	
	if (classFactor == 1) {
		var value = Math.ceil(volume / 100);
	} else if (classFactor == 2) {
		var value = Math.ceil(volume / 40);
	} else if (classFactor == 3) {
		var value = Math.ceil(volume / 30);
	} else if (classFactor == 4) {
		var value = "N/A";
	}
	
	var fluidUnit = "pts.";
	if(fluidID == 2) {
		fluidUnit = "l.";
		if(classFactor != 4) {
			value =  0.473176473 * value;	
		}
	}
	
	
	var deviation = 0;
	var minValue = Math.ceil(value - deviation);
	var maxValue = Math.ceil(value + deviation);
	
	var printLine = value.toFixed(0) + " AHAM " + fluidUnit +" (minimum)";
	if(value == "N/A") {
		printLine = "Recommendation not available for this class of damage";
	}
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = deviation;
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
	
}


//===============================================
//
// Calculate AHAM LGR
//
function calculateAHAMlgr(classFactor, volume, fluidID) {
	
	
	if (classFactor == 1) {
		var value = Math.ceil(volume / 100);
	} else if (classFactor == 2) {
		var value = Math.ceil(volume / 50);
	} else if (classFactor == 3) {
		var value = Math.ceil(volume / 40);
	} else if (classFactor == 4) {
		var value = Math.ceil(volume / 50);
	}
	
	
	var fluidUnit = "pts.";
	if(fluidID == 2) {
		fluidUnit = "l.";
		if(classFactor != 4) {
			value =  0.473176473 * value;	
		}
	}
	
	var deviation = 0;
	var minValue = Math.floor(value - deviation);
	var maxValue = Math.ceil(value + deviation);
	
	
	var printLine = value.toFixed(0) + " AHAM " + fluidUnit +" (minimum)";
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = deviation;
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
	
}


//===============================================
//
// Calculate Air Scrubbers
//
function calculateAirScrubbers(volume, ach, ratioSpread) {
	
	
	// Project Mode
	var projectMode = 0;
	var projectModeObj = window.document.getElementsByName('projectMode');
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}
	
	// Air Scrubbers
	var value	= Math.ceil(volume / (15 * ach)) ;
	var deviation = value * ratioSpread;
	var minValue = Math.ceil(value - deviation);
	var maxValue = Math.ceil(value + deviation);
	
	
	var printLine = "";
	if(projectMode == 1) {
		printLine = minValue.toFixed(0) + " to " + maxValue.toFixed(0) + " CFMs (" + value.toFixed(0) + " ± " + deviation.toFixed(0) + " CFMs)";
	} else {
		printLine = value.toFixed(0) + " CFMs (minimum)";	
		maxValue = 99999999999999999999999999999999.999;
		deviation = 0;
	}
	
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = Math.ceil(deviation);
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
	
}



//===============================================
//
// Calculate Air Movers
//
function calcAirMovers(linearWall, area) {


	// Basic Calculations
	var amNS500Res = calculateAirMovers(linearWall, area);
	var amS500Res = calculateS500AirMovers(linearWall);

	var amRes = [];
	if(amNS500Res['min'] < amS500Res['min']) {
		amRes['min'] = amNS500Res['min'];
	} else {
		amRes['min'] = amS500Res['min'];
	}
	
	
	if(amNS500Res['max'] > amS500Res['max']) {
		amRes['max'] = amNS500Res['max'];
	} else {
		amRes['max'] = amS500Res['max'];
	}
	
	amRes['value'] = Math.ceil((amNS500Res['value'] + amS500Res['value'])/2);
	amRes['dev'] = Math.ceil(amRes['max'] - amRes['value']);
	
	if(amRes['min'] == amRes['max']) {
		amRes['print'] = amRes['min'] + " units";	
	} else {
		amRes['print'] = amRes['min'] + " to " + amRes['max'] + " units";
	}
	
	return amRes;
}


//===============================================
//
// Calculate Air Movers
//
function calculateAirMovers(linearWall, area) {


	// Air Movers
	var maxValue = Math.ceil(linearWall/10 + area/250);
	var minValue = Math.ceil(linearWall/16 + area/250);
	if(minValue == maxValue) {
		var printLine = minValue + " units";	
	} else {
		var printLine =  minValue + " to " + maxValue + " units";
	}
	var value = Math.ceil((maxValue + minValue)/2);
	var deviation = maxValue - value;
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = Math.ceil(deviation);
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
}


//===============================================
//
// Calculate Air Movers
//
function calculateS500AirMovers(linearWall) {

	var maxValue = Math.ceil(linearWall/10);
	var minValue = Math.ceil(linearWall/16);
	if(minValue == maxValue) {
		var printLine = minValue + " units";	
	} else {
		var printLine =  minValue + " to " + maxValue + " units";
	}
	var value = Math.ceil((maxValue + minValue)/2);
	var deviation = maxValue - value;
	
	var returnObj = [];
	returnObj['value'] = value;
	returnObj['dev'] = Math.ceil(deviation);
	returnObj['min'] = minValue;
	returnObj['max'] = maxValue;
	returnObj['print'] = printLine;
	
	return returnObj;
}




//===============================================
//
// Calculate Air Movers Project Mode
//
function calculateAirMoversProjectMode(linearWall, area, projectMode) {

	if(projectMode == 1) {
		var results = calculateAirMoversResCom(linearWall, area, "Com");
	} else {
		var results = calculateAirMoversResCom(linearWall, area, "Res");
	}
	
	return results;

}

//===============================================
//
// Calculate Air Movers ResCom
//
function calculateAirMoversResCom(linearWall, area, resCom) {

	if(resCom == "Com" || resCom == "com") {
		var results = calcAirMovers(linearWall, area);	
	} else {
		var results = calculateS500AirMovers(linearWall);
	}
	
	return results;

}

//===============================================
//
// Calculate ACR
//
function calculateAirChangeRate() {
	
	// Get the class factor index
	var classFactorIndex = parseInt(document.getElementsByName("classFactor")[0].value);
	
	var result = calcAirChangeRate(classFactorIndex);
	return result;
}


//===============================================
//
// Calculate ACR
//
function calcAirChangeRate(classFactorIndex) {
	
	
	// Project Mode
	var projectMode = 0;
	var projectModeObj = window.document.getElementsByName('projectMode');
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}

	var classFactorIndex = parseInt(classFactorIndex);
	
	//
	// Commercial Calculation
	//
	if(projectMode == 1) {
		
		// Class
		var classFactor = 1.0;
		if(classFactorIndex == 1) {
			classFactor = 1.0;
		} else if(classFactorIndex == 2) {
			classFactor = 1.5;	
		} else if(classFactorIndex == 3) {
			classFactor = 2.0;	
		} else if(classFactorIndex == 4) {
			classFactor = 2.3;
		}
		
		// Build-out Density
		var buildOutDensityIndex = parseInt(document.getElementsByName("buildOutDensity")[0].value);
		var buildOutDensityFactor = 1.0;
		if(buildOutDensityIndex == 1) {
			buildOutDensityFactor = 0.6;
		} else if(buildOutDensityIndex == 2) {
			buildOutDensityFactor = 0.8;
		} else if(buildOutDensityIndex == 3) {
			buildOutDensityFactor = 1.0;
		} else if(buildOutDensityIndex == 4) {
			buildOutDensityFactor = 1.2;
		}
		
		// Building Construction
		var buildingConstructionIndex = parseInt(document.getElementsByName("buildingConstruction")[0].value);
		var buildingConstructionFactor = 1.0;
		if(buildingConstructionIndex == 1) {
			buildingConstructionFactor = 1.0;
		} else if(buildingConstructionIndex = 2) {
			buildingConstructionFactor = 1.5;
		}
		
		// HVAC
		var hvacIndex = parseInt(document.getElementsByName("hvac")[0].value);
		var hvacFactor = 1.0;
		if(hvacIndex == 1) {
			hvacFactor = 1.5;
		} else if(hvacIndex == 2) {
			hvacFactor = 1.0;
		}
		
		// Weather Impact Factor (Envelope & Weather Conditions)
		var envelopeIndex = parseInt(document.getElementsByName('envelope')[0].value);
		var weatherConditionIndex = parseInt(document.getElementsByName('weatherConditions')[0].value);
		var weatherImpactFactor = 1.0;
		if(envelopeIndex == 1 || weatherConditionIndex == 2) {
			weatherImpactFactor = 1.0;	// Neutral Weather OR Tight Building
		} else if(envelopeIndex == 2 && weatherConditionIndex == 1) {
			weatherImpactFactor = 0.8; // Moderate Env ; Favorable Conditions	
		} else if(envelopeIndex == 3 && weatherConditionIndex == 1) {
			weatherImpactFactor = 0.5; // Loose Env ; Favorable Conditions
		} else if(envelopeIndex == 2 && weatherConditionIndex == 3) {
			weatherImpactFactor = 1.2; // Moderate Env ; Unfavorable Conditions
		} else if(envelopeIndex == 3 && weatherConditionIndex == 3) {
			weatherImpactFactor = 1.5; // Loose Env ; Unfavorable Conditions
		}
		
		var multiplier = classFactor * buildOutDensityFactor * buildingConstructionFactor * hvacFactor * weatherImpactFactor;
		
	
	} else {
	
		// Class Factor
		var classFactor = 1.0;
		if(classFactorIndex == 2) {
			classFactor = 2.0;	
		} else if(classFactorIndex == 3) {
			classFactor = 3.0;	
		}
		var multiplier = classFactor;
	}
	
	var ACR = 60.0 / multiplier;
	var resultObj = [];
	resultObj['ACR'] = ACR;
	resultObj['mult'] = multiplier;
	
	return resultObj;
	
	
}


//===============================================
//
// Calculate Drying Area S500 Implimentation
//
function calcDryingAreaS500Implimentation() {
	
	// Get the form
	var myForms = window.document.getElementsByName("dryingAreaDetailsForm");
	var myForm = myForms[0];
	
	// Get the number of generic equipment
	var genericObj = window.document.getElementsByName("numGenerics");
	var numGenerics = genericObj[0].value;
	
	// Used CFM (Desiccant)
	var usedCFM_DD = 0.0;
	
	// Used AHAM (Conventional/LGR)
	var usedAHAM_ConvLGR = 0.0;
	
	// Used CFM (AS)
	var usedCFM_AS = 0.0;
	
	// Air Mover
	var numAM = 0.0;
	
	

	// Get the spread
	var ACHdelta = .3;
	var cfmErrorObj = window.document.getElementsByName('cfmError');
	if(cfmErrorObj.length > 0) {
		ACHdelta = parseFloat(cfmErrorObj[0].value) / 100.0;
	}
	
	// Project Mode
	var projectModeObj = window.document.getElementsByName('projectMode');
	var projectMode = 0;
	if(projectModeObj.length > 0) {
		projectMode = projectModeObj[0].value;
	}
	
	// Class
	var classFactor = parseInt(document.getElementsByName("classFactor")[0].value);
	
	// Get the fluid conversion value
	var fluidID = window.document.getElementsByName('fluidID')[0].value;
	
	// Get the quantities
	for(var i=0;i<numGenerics;i++) {
		
	
		// Get the equipment ID
		var eqidObj = window.document.getElementsByName("equipment_" + i);
		var equipmentID = eqidObj[0].value;
		
	
		// Get the qty
		var qtyObj = window.document.getElementsByName("qty_" + equipmentID);
		var qty = qtyObj[0].value;
		if(qty == "" || isNaN(qty)) {
			qtyObj[0].value = 0;
			qty = 0;
		} else {
			qty = parseInt(qty);	
		}
		
		
		
		// Get the power
		var eqUnitPowerObj = window.document.getElementsByName("eqType_Power_" + equipmentID);
		if(eqUnitPowerObj.length > 0) {
			var eqUnitPower = parseFloat(eqUnitPowerObj[0].value);
			
			var eqPowerObj = window.document.getElementsByName("eqPower_" + equipmentID);
			if(eqPowerObj.length > 0) {
				var eqPower = eqUnitPower * qty / 1000;
				eqPowerObj[0].value = eqPower.toFixed(2);
				if(eqPowerObj[0].value < 0.01) {
					eqPowerObj[0].style.color = "transparent";	
				} else {
					eqPowerObj[0].style.color = "#000000";	
				}
			}
		}
		
		// Don't bother if there is no quantity
		if(qty > 0) {
			
			// Check the equipment type
			var eqTypeObj = window.document.getElementsByName("eqType_" + equipmentID);
			var eqType = eqTypeObj[0].value;
			

			// Air Mover Calculator
			if(eqType == "Air Mover") {
				numAM += qty;
			}
			
			if(eqType == "Air Scrubber") {
				var CFM_AS_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_AS = parseFloat(CFM_AS_Obj[0].value);
				usedCFM_AS = usedCFM_AS + (qty * CFM_AS);
			} 
			
			if(eqType == "Desiccant Dehumidifier") {
				var CFM_DD_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_DD = parseFloat(CFM_DD_Obj[0].value);
				usedCFM_DD = usedCFM_DD + (qty * CFM_DD);
			}
			
			if(eqType == "Refrigerant Dehumidifier") {
			
				var AHAM_Obj = window.document.getElementsByName("eqPerf_GOMRPD_" + equipmentID);
				var AHAM = parseFloat(AHAM_Obj[0].value);
				usedAHAM_ConvLGR = usedAHAM_ConvLGR + (qty * AHAM);
			}
			
		}
	
	}
	
	
	// Get the Drying Area S500 Recommendations
	var dryingAreaResults = getDryingAreaSizes();
	
	var volume = dryingAreaResults['volume'];
	var area = dryingAreaResults['area'];
	var fullVolume = dryingAreaResults['fullVolume'];
	var fullArea = dryingAreaResults['fullArea'];
	var linearWall = dryingAreaResults['linearWall'];
	var lengthID = dryingAreaResults['lengthID'];
	
	var ACRobj = calculateAirChangeRate();
	var desiccantCFMresults = calculateDesiccantCFMs(volume, ACRobj['mult'], ACHdelta);
	var AHAMresults = calculateAHAMconventional(classFactor, volume, fluidID);
	var AHAMlgrResults = calculateAHAMlgr(classFactor, volume, fluidID);
	
	var ASresults = calculateAirScrubbers(volume, ACRobj['mult'], ACHdelta);
	var AMS500results = calculateS500AirMovers(linearWall);
	
	var AMresComResults = calculateAirMoversProjectMode(linearWall, area, projectMode);
	
	
	
	//
	// Update the Recommendations
	//
	
	// Used CFM (Desiccant)
	window.document.getElementsByName('desiccantCFMUsedValue')[0].value = usedCFM_DD;
	var desiccantCFMUsedObj = window.document.getElementsByName("CFMUsed");
	if(usedCFM_DD == 1) {
		desiccantCFMUsedObj[0].value = usedCFM_DD.toFixed(0) + " CFM in use";
	} else if(usedCFM_DD > 0) {
		desiccantCFMUsedObj[0].value  = usedCFM_DD.toFixed(0) + " CFMs in use";
	} else {
		desiccantCFMUsedObj[0].value  = "N/A";
	}
	setRowColor('usedCFMrow',desiccantCFMresults,usedCFM_DD);
	
	
	// Used CFM (Conv/LGR)
	window.document.getElementsByName('AHAMUsedValue')[0].value = usedAHAM_ConvLGR;
	var cfmConvLGRUsedObj = window.document.getElementsByName("AHAMUsed");
	var fluidSymbol;
	if(fluidID == 2) {
		usedAHAM_ConvLGR = usedAHAM_ConvLGR * 0.473176473;
		fluidSymbol = "l.";
	} else {
		fluidSymbol = "pt.";
	}
	if(usedAHAM_ConvLGR > 0) { 
		cfmConvLGRUsedObj[0].value  = usedAHAM_ConvLGR.toFixed(0) + " AHAM " + fluidSymbol + " in use";
	} else {
		cfmConvLGRUsedObj[0].value  = "N/A";
	}
	
	var AHAMmergedResults = [];
	if(AHAMresults['min'] < AHAMlgrResults['min']) {
		AHAMmergedResults['min'] = AHAMresults['min'];
	} else {
		AHAMmergedResults['min'] = AHAMlgrResults['min'];
	}
	AHAMmergedResults['max'] = 99999999999999999999999.9;
	
	setRowColor('usedAHAMrow',AHAMlgrResults,usedAHAM_ConvLGR);
	
	
	// Used CFM (Air Scrubbers)
	window.document.getElementsByName('ASUsedValue')[0].value = usedCFM_AS;
	var airScrubbersCFMUsedObj = window.document.getElementsByName("ASUsed");
	if(usedCFM_AS == 1) {
		airScrubbersCFMUsedObj[0].value  = usedCFM_AS.toFixed(0) + " CFM in use.";
	} else if(usedCFM_AS > 0) {
		airScrubbersCFMUsedObj[0].value  = usedCFM_AS.toFixed(0) + " CFMs in use.";
	} else {
		airScrubbersCFMUsedObj[0].value  = "N/A";
	}
	
	setRowColor('usedASrow',ASresults,usedCFM_AS);
	
	
	// Air Movers Used
	window.document.getElementsByName('AMUsedValue')[0].value = numAM;
	var airMoversUsedObj = window.document.getElementsByName("AMUsed");
	if(numAM > 1) {
		airMoversUsedObj[0].value  = numAM.toFixed(0) + " in use.";
	} else if(numAM == 1) {
		airMoversUsedObj[0].value  = numAM.toFixed(0) + " in use.";
	} else {
		airMoversUsedObj[0].value  = "N/A";	
	}
	setRowColor('usedAMrow',AMresComResults,numAM);
	
	
	return true;
}




//==============================
//
// drying area add inset offset
//
function dryingAreaInsetOffsetAdd(projectID,roomid) {
	var myForm = addFormToWindow(window,'myForm');
	var sourcePage = window.location;
	
	addPostToForm(myForm,'projectID',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'sourcePage',sourcePage);
	
	myForm.method = 'POST';
	myForm.target = "_top";
	myForm.action = "/site/projects/dryingArea/dryingAreaDetailsInsetOffsetAdd.php";
	myForm.submit();
}


//================================
//
// drying area remove inset offset
//
function dryingAreaInsetOffsetUpdate(ioid,visible) {
	var myForm = addFormToWindow(window,'hiddenForm');
	var sourcePage = window.location;
	
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	
	// Check to see if something is being deleted.
	// If so, confirm.
	if(visible == 'No') {
		var answer = confirm('Are you sure you wish to permanently remove this section?');
		if(answer == false) {
			return;	
		}
	}
	
	// Get the length ID
	var lengthID = window.document.getElementsByName('lengthID')[0].value;
	
	// Get the data
	var type = window.document.getElementsByName('roomOffInSwitch_' + ioid)[0].value;
	
	var lengthObj = window.document.getElementsByName('roomLength_' + ioid)[0];
	if(isNaN(lengthObj.value) || lengthObj.value == "") {
		lengthObj.value = 0;	
	}
	var length = parseFloat(lengthObj.value);
	
	var widthObj = window.document.getElementsByName('roomWidth_' + ioid)[0];
	if(isNaN(widthObj.value) || widthObj.value == "") {
		widthObj.value = 0;	
	}
	var width = parseFloat(widthObj.value);
	
	var heightObj = window.document.getElementsByName('roomHeight_' + ioid)[0];
	if(isNaN(heightObj.value) || heightObj.value == "") {
		heightObj.value = 0;	
	}
	var height = parseFloat(heightObj.value);
	
	var lengthInObj = window.document.getElementsByName('roomLengthIn_' + ioid)[0];
	if(isNaN(lengthInObj.value) || lengthInObj.value == "") {
		lengthInObj.value = 0;	
	}
	var lengthIn = parseFloat(lengthInObj.value);
	
	var widthInObj = window.document.getElementsByName('roomWidthIn_' + ioid)[0];
	if(isNaN(widthInObj.value) || widthInObj.value == "") {
		widthInObj.value = 0;	
	}
	var widthIn = parseFloat(widthInObj.value);
	
	var heightInObj = window.document.getElementsByName('roomHeightIn_' + ioid)[0];
	if(isNaN(heightInObj.value) || heightInObj.value == "") {
		heightInObj.value = 0;	
	}
	var heightIn = parseFloat(heightInObj.value);
	
	var name = window.document.getElementsByName('roomName_' + ioid)[0].value;
	
	// Merge values
	if(lengthID == 1) {
		var fractional = 12.;	
	} else {
		var fractional = 100.;	
	}
	length = length + (lengthIn / fractional);
	width = width + (widthIn / fractional);
	height = height + (heightIn / fractional);
	
	// Convert if need be
	if(lengthID == 2) {
		length = metersToFeet(length);
		width = metersToFeet(width);
		height = metersToFeet(height);
	}
	
	// Add Post Information
	addPostToForm(myForm,'insetOffsetID',ioid);
	addPostToForm(myForm,'type',type);
	addPostToForm(myForm,'length',length);
	addPostToForm(myForm,'width',width);
	addPostToForm(myForm,'height',height);
	addPostToForm(myForm,'visible',visible);
	addPostToForm(myForm,'name',name);
	addPostToForm(myForm,'sourcePage',sourcePage);
	
	
	// Submit form
	myForm.method = 'POST';
	if(visible == 'No') {
		myForm.target = '_top';
	} else {
		myForm.target = 'hiddenFrame';	
	}
	myForm.action = '/site/projects/dryingArea/dryingAreaDetailsInsetOffsetUpdate.php';
	myForm.submit();
	
}


//===============================================
//
// Drying Area Photos
//

// Add Photo
function addDryingAreaPhoto(projectID, roomid, openClose) {
	
	var openCode = "<a href='javascript:addDryingAreaPhoto(" + projectID + "," + roomid + ",\"close\");' class='text' style='color:red;'>Close Add Box</a>";
	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=3 style='border:thin black solid;width:500px;text-align:center;background-color:#DEDEFF;'>";
	openCode = openCode + "<tr><td class='text' colspan=2><h3>Add New Photo</h3></td></tr>";
	openCode = openCode + "<tr><td class='text' colspan=2><div id='x-small'>Photos will be scaled down to maximum 400x300<br /><b>(All images combined can't exceed 5MB)</b></div></td></tr>";
//	openCode = openCode + "<tr valign=bottom><td width=200>";
//	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=1 width=100%>";
//	openCode = openCode + "<tr><td class='text'><b>Image Description:</b><br /><div id='x-small'>Example:'Living room, West wall'</div></td></tr>";
//	openCode = openCode + "<tr><td class='text'><input type='text' class='text' name='photoDescription' size=30></td></tr>";
//	openCode = openCode + "</table>";
//	openCode = openCode + "</td>";
//	openCode = openCode + "<td width=200>";
//	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=1 width=100%>";
//	openCode = openCode + "<tr><td class='text'><b>Choose File:</b></td></tr>";
//	openCode = openCode + "<tr><td class='text'><input type='file' class='text' name='photoFile'></td></tr>";
//	openCode = openCode + "</table>";
	
//	openCode = openCode + "</td></tr>";
	openCode = openCode + "<tr valign=bottom><td  width=200>";
	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=1 width=100%>";
	openCode = openCode + "<tr><td class='text' width=50%><b>Image Description:</b><br /><div id='x-small'>Example:'Living room, West wall.'</div></td>";
	openCode = openCode + "<td class='text' width=50%>Choose File:</td></tr>";
	openCode = openCode + "<tr><td class='text' colspan=2>";
	openCode = openCode + "<p id='uploadArea'>";
	openCode = openCode + "<input id='nmb99' name='nmbx' type='text' value='' onchange='titleChanged();' size='30' class='txtBoxGray' maxlength='99' /><input name='userFile99' type='file' id='userFile99' size='10' class='txtBoxGray' onblur='titleChanged(this);' />";
	openCode = openCode + "<input id='AddFile' type='button' value='Add' onclick='addFileUploadBox();' style='position: relative; top: 0px; left: 0px;' class='btnBoxGray' />";
	openCode = openCode + "</p><input type='hidden' name='hdnTitles' id='hdnTitles' />";
	openCode = openCode + "<input type='button' value='Add Photo(s)' class='textCenter' onclick='javascript:addDryingAreaPhotoReally(" + projectID + "," + roomid + ",\"Edit\");' ></td></tr>";
	openCode = openCode + "</table>";
	
	openCode = openCode + "</td></tr>";
//	openCode = openCode + "<tr><td class='textCenter' colspan=2>";
//	openCode = openCode + "<input type='button' value='Add Photo' class='textCenter' onclick='javascript:addDryingAreaPhotoReally(" + projectID + "," + roomid + ",\"Edit\");'>&nbsp;&nbsp;&nbsp;&nbsp;";
//	openCode = openCode + "<input type='reset' class='textCenter'>"
//	openCode = openCode + "</td></tr>";
	openCode = openCode + "</table>";
	
	var closedCode = "<a href='javascript:addDryingAreaPhoto(" + projectID + "," + roomid + ",\"open\");' class='text' style='color:red;'>Add New Photo</a>";

	var addPhotoArea = window.document.getElementsByName("addPhotoArea")[0];
	if(openClose == "close") {
		addPhotoArea.innerHTML = closedCode;
	} else {
		addPhotoArea.innerHTML = openCode;	
	}	
	return;
}





// Add Photo
function addNewDryingAreaPhoto(projectID, roomid, openClose) {
	
	var openCode = "<a href='javascript:addDryingAreaPhoto(" + projectID + "," + roomid + ",\"close\");' class='text' style='color:red;'>Close Add Box</a>";
	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=3 style='border:thin black solid;width:500px;text-align:center;background-color:#DEDEFF;'>";
	openCode = openCode + "<tr><td class='text' colspan=2><h3>Add New Photo</h3></td></tr>";
	openCode = openCode + "<tr><td class='text' colspan=2><div id='x-small'>Photos will be scaled down to maximum 400x300<br /><b>(All images combined can't exceed 5MB)</b></div></td></tr>\n";
	openCode = openCode + "<tr valign=bottom><td width=200>";
	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=1 width=100%>";
	openCode = openCode + "<tr><td class='text'><b>Image Description:</b><br /><div id='x-small'>Example:'Living room, West wall'</div></td></tr>";
	openCode = openCode + "<tr><td class='text'><input type='text' class='text' name='photoDescription' size=30></td></tr>";
	openCode = openCode + "</table>";
	openCode = openCode + "</td>";
	openCode = openCode + "<td width=200>";
	openCode = openCode + "<table border=0 cellspacing=0 cellpadding=1 width=100%>";
	openCode = openCode + "<tr><td class='text'><b>Choose File:</b></td></tr>";
	openCode = openCode + "<tr><td class='text'><input type='file' class='text' name='photoFile'></td></tr>";
	openCode = openCode + "</table>";
	
	openCode = openCode + "<div>";
	openCode = openCode + "<div style='position: absolute;'>";
	openCode = openCode + "<div style='top: -17px; left: 0px; position: relative; width: 208px'>";
	openCode = openCode + "<b>Image Description:</b><br /><div id='x-small'>Example:'Living room, West wall.'</div></div>";
	openCode = openCode + "<div style='top: -17px; left: 220px; position: absolute; white-space: nowrap'>";
	openCode = openCode + "<b>Choose File:</b></div>";
	openCode = openCode + "<p id='uploadArea'>";
	openCode = openCode + "<input id='nmb99' name='nmbx' type='text' value='' onchange='titleChanged();' size='30' class='txtBoxGray' maxlength='99' /><input name='File1' type='file' id='File1' size='10' class='txtBoxGray' />";
	openCode = openCode + "</p><div style='position: absolute;'>";
	openCode = openCode + "<input id='AddFile' type='button' value='Add Another File' onclick='addFileUploadBox();' style='position: relative; top: 0px; left: 0px;' class='btnBoxGray' />";
	openCode = openCode + "</div></div><input type='hidden' name='hdnTitles' id='hdnTitles' />";
	
	openCode = openCode + "</td></tr>";
	openCode = openCode + "<tr><td class='textCenter' colspan=2>";
	openCode = openCode + "<input type='button' value='Add Photo'  class='textCenter' onclick='javascript:addDryingAreaPhotoReally(" + projectID + "," + roomid + ",\"Add\");'>&nbsp;&nbsp;&nbsp;&nbsp;";
	openCode = openCode + "<input type='reset' class='textCenter'>"
	openCode = openCode + "</td></tr></table>";
	
	var closedCode = "<a href='javascript:addNewDryingAreaPhoto(" + projectID + "," + roomid + ",\"open\");' class='text' style='color:red;'>Add New Photo</a>";

	var addPhotoArea = window.document.getElementsByName("addPhotoArea")[0];
	if(openClose == "close") {
		addPhotoArea.innerHTML = closedCode;
	} else {
		addPhotoArea.innerHTML = openCode;	
	}	
	return;
}

function postTest(projectID,roomid,addEdit){
	var myForms = window.document.getElementsByName('dryingAreaPhotosForm');
	var myForm = myForms[0];
	
	// Post Data
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'addEdit',addEdit);
	
	myForm.action = "/site/projects/dryingArea/dryingAreaPhotosAdd.php";
	myForm.method = 'post';
	myForm.submit();
}

// Add Photo... ReALLY
function addDryingAreaPhotoReally(projectID,roomid,addEdit) {
	
	// Get the form
	var myForms = window.document.getElementsByName('dryingAreaPhotosForm');
	var myForm = myForms[0];
	
	var numMaxPhotos = 25;
	var subscription = window.document.getElementsByName('subType')[0].value;
	if(subscription == "Corp") {
		numMaxPhotos = 50;	
	}
	
	
	// Check for blanks
//	var fileName = myForm.photoFile.value;
//	if(fileName == "") {
//		return;
//	}
	
//	var newDescription = myForm.photoDescription.value;
//	if(newDescription == "") {
//		alert("Description required.");
//		return;
//	}
	
	
	// Check number of images
	var numPhotos = myForm.numPhotos.value;
	if(numPhotos > numMaxPhotos) {
		alert("A maximum of " + numMaxPhotos + " photos per drying area allowed.");
		return;
	}
	
	
	// Post Data
	addPostToForm2(myForm,'pid',projectID);
	addPostToForm2(myForm,'roomid',roomid);
	addPostToForm2(myForm,'addEdit',addEdit);
	
	
	// show the mmWait box ("Uploading")
	//
	// This assumes that the reloading of the page after the 
	// upload finishes (successful or not) will result in
	// the box going away.
	displayMMwait('30d_uploading',true);
	
	
	// Submit
	myForm.action = "/site/projects/dryingArea/dryingAreaPhotosAdd.php";
	myForm.method = 'post';
	myForm.submit();
	
}

function addPostToForm2(formObj,elementName,elementValue) {
	var input = window.document.createElement('input');
	input.type = 'hidden';
	input.id = elementName;
	input.name = elementName;
	input.value = elementValue;
	
	formObj.appendChild(input);
}


//======================================
//
// Delete Drying Area Photo
//
function deleteDryingAreaPhoto(projectID, roomid, id, addEdit) {
	
	var answer = confirm("Are you sure you wish to delete this image?");
	if(answer == false) {
		return;	
	}
	
	// Get the form
	var myForms = window.document.getElementsByName('dryingAreaPhotosForm');
	var myForm = myForms[0];
	
	// Project ID
	var idInput = window.document.createElement('input');
	idInput.type = 'hidden';
	idInput.id = 'projectID';
	idInput.name = 'projectID';
	idInput.value = projectID;
	myForm.appendChild(idInput);
	
	
	// Room ID
	var roomidInput = window.document.createElement('input');
	roomidInput.type = 'hidden';
	roomidInput.id = 'roomid';
	roomidInput.name = 'roomid';
	roomidInput.value = roomid;
	myForm.appendChild(roomidInput);
	
	
	// ID
	var idInput = window.document.createElement('input');
	idInput.type = 'hidden';
	idInput.id = 'id';
	idInput.name = 'id';
	idInput.value = id;
	myForm.appendChild(idInput);
	
	
	// Add/Edit
	var addEditInput = window.document.createElement('input');
	addEditInput.type = 'hidden';
	addEditInput.id = 'addEdit';
	addEditInput.name = 'addEdit';
	addEditInput.value = addEdit;
	myForm.appendChild(addEditInput);
	
	
	myForm.action = "/site/projects/dryingArea/dryingAreaPhotosDelete.php";
	myForm.method = 'post';
	myForm.submit();
}


//======================================
//
// Delete Drying Area Photo
//
function updateDryingAreaPhotos(projectID, roomid, id) {
	
	// Get the form
	var myForms = window.document.getElementsByName('dryingAreaPhotosForm');
	var myForm = myForms[0];
	
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	
	// Project ID
	addPostToForm(myForm,'projectID',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'photoID',id);
	
	// Get New Description
	var descriptionName = 'photoDesc_' + id;
	var descriptionObject = window.document.getElementsByName('photoDesc_' + id);
	var description = descriptionObject[0].value;
	
	var descriptionOriginalName = 'photoDescOriginal_' + id;
	var descriptionOriginalObject = window.document.getElementsByName('photoDescOriginal_' + id);
	var descriptionOriginal = descriptionOriginalObject[0].value;
	
	
	
	if(description == "") {
		alert("Description required.");
		descriptionObject[0].value = descriptionOriginal;
		return;
	}
	
	
	myForm.action = "/site/projects/dryingArea/updateDryingAreaPhotos.php";
	myForm.target = 'hiddenFrame';
	myForm.method = 'post';
	myForm.submit();
}



//==========================================================
//
// Get Checked Value
//
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


//==========================================================
//
// select Drying Area Design Template
//
function selectDryingAreaDesignTemplate(projectID, roomid) {
	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaDesignForm')[0];
	
	// Get Chooser Info
	var chooserObject = window.document.getElementsByName('chooser');
	var choice = getCheckedValue(chooserObject);
	
	
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	
	
	// Add New Template
	myForm.method = 'post';
	if(choice != "custom") {
		myForm.action = "/site/projects/dryingArea/dryingAreaDesignNew.php";
	} else {
		myForm.action = "/site/projects/dryingArea/dryingAreaDesignCustom.php";
	}
	myForm.submit();
}


//==========================================================
//
// select Drying Area Design Template
//
function selectNewDryingAreaDesignTemplate(projectID, roomid) {
	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaDesignForm')[0];
	
	// Get Chooser Info
	var chooserObject = window.document.getElementsByName('chooser');
	var choice = getCheckedValue(chooserObject);
	
	
	// Project ID
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	
	
	// Add New Template
	myForm.method = 'post';
	if(choice != "custom") {
		myForm.action = "/site/projects/dryingArea/newDryingArea/newDesignAdd.php";
	} else {
		myForm.action = "/site/projects/dryingArea/newDryingArea/newDesignUpload.php";
	}
	myForm.submit();
}


//=======================================================
//
//
//
function uploadCustomDryingAreaDesign(projectID,roomid,addEdit) {

	
	// Get the form
	var myForms = window.document.getElementsByName('dryingAreaDesignForm');
	var myForm = myForms[0];
	
	var fileObject = window.document.getElementsByName('chosenUpload');
	var fileName = fileObject[0].value;
	
	if(fileName == undefined || fileName == "") {
		return;	
	}
	
	
	// Add Post Data
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'addEdit',addEdit);
	
	
	// show the mmWait box ("Uploading")
	//
	// This assumes that the reloading of the page after the 
	// upload finishes (successful or not) will result in
	// the box going away.
	displayMMwait('30d_uploading',true);

	
	// Add file to db
	myForm.action = "/site/projects/dryingArea/dryingAreaDesignCustomAdd.php";
	myForm.method = 'post';
	myForm.submit();
}



//==================================================================
//==================================================================
//
// Drying Area Equipment Page
//


// Set the Equipment Types Viewed
function setViewEquipmentType(roomid) {
	
	var obj = window.document.getElementsByName('viewEquipmentType');
	var value = obj[0].value;
	
	var equipmentPage = '/site/projects/dryingArea/dryingAreaEquipment.php?id=' + roomid;

	if(value == -1) {
		var address = equipmentPage;	
	} else {
		var address = equipmentPage + '&eqType=' + value;	
	}
	
	window.location = address;

}



// Set the Equipment Types Viewed
function setViewClosedEquipmentType(roomid) {
	
	var obj = window.document.getElementsByName('viewEquipmentType');
	var value = obj[0].value;
	
	var equipmentPage = '/site/projects/dryingArea/closedDryingArea/closedEquipment.php?id=' + roomid;

	if(value == -1) {
		var address = equipmentPage;	
	} else {
		var address = equipmentPage + '&eqType=' + value;	
	}
	
	window.location = address;

}





// Update Equipment Usage
function updateEquipmentUsage(projectID, roomid, eqid, addEdit, visible) {
	
	
	// Get the form
	var myForm = window.document.dryingAreaEquipmentForm;
	
	
	// Create the hidden frame
	createFrame(window,'hiddenFrame');
	
	// Get equipment name
	var fieldName = "equipment_" + eqid;
	var equipmentObj = window.document.getElementsByName(fieldName);
	var equipmentName = equipmentObj[0].value;
	
	// Check to see if this is a deletion
	if(visible == "No" || visible == "no") {
		var answer = confirm("Are you sure you wish to permanently delete:\n" + equipmentName + "?");
		if(answer == false) {
			return;	
		}
	}
	
	
	// Get Rental Rate
	var fieldName = "defaultRentalRate_" + eqid;
	var rateObj = window.document.getElementsByName(fieldName);
	var dailyRate = parseFloatValue(rateObj[0].value);
	
	
	// Insure Rental Rate is legit
	if(dailyRate == "" || dailyRate == undefined || isNaN(dailyRate)) {
		rateObj[0].value = 0.00;
	}
	

	// Post Data
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'eqid',eqid);
	addPostToForm(myForm,'addEdit',addEdit);
	addPostToForm(myForm,'visible',visible);
	
	
	
	// Go to the Code to Update the Database
	if(visible == 'Yes') {
		myForm.target = 'hiddenFrame';
	} else {
		myForm.target = '_top';
	}
	myForm.action = '/site/projects/dryingArea/updateEquipmentUsage.php';
	myForm.method = 'POST';
	myForm.submit();
	
}


//=================================================
//
// Add Equipment to Drying Area
//
function dryingAreaEquipmentAdd(projectID, roomid, addEdit) {
	
	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaEquipmentForm')[0];
	
	// Get the checklist
	var checkboxList = window.document.getElementsByName('addEquipSelect');
	var checkList = new Array();
	var checkCount = 0;
	for(var i=0;i<checkboxList.length;i++) {
		if(checkboxList[i].checked) {
			checkList[checkCount] = checkboxList[i].value;
			
			var obj = window.document.createElement('input');
			obj.type = 'hidden';
			obj.id = 'check_' + checkCount;
			obj.name = 'check_' + checkCount;
			obj.value = checkList[checkCount];
			myForm.appendChild(obj);
			
			checkCount++;
		}
	}
	
	// Post the number of check points
	addPostToForm(myForm,'checkCount',checkCount);
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'addEdit',addEdit);
	
	
	// Go to the Code to Update the Database
	myForm.target = '_top';
	myForm.action = '/site/projects/dryingArea/updateEquipmentUsageAdd.php';
	myForm.method = 'POST';
	myForm.submit();
}


//============================================================
//
// Drying Area Equipment Autoflip
//
function dryingAreaEquipmentAutoflip(projectID,roomid,dateNumber,eqid,addEdit) {


	// Yes Image
	var yesImage = new Image();
	yesImage.src = '/site/images/yes.gif';
	var noImage = new Image();
	noImage.src = '/site/images/close_info.gif';

	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaEquipmentForm')[0];
	createFrame(window,'hiddenFrame');
	
	// Get the current setting of the clicked day/equipment
	var todayLabel = "used_" + eqid + "_" + dateNumber;
	var todayObj = window.document.getElementsByName(todayLabel);
	if(todayObj[0].value == "Yes") {
		var yesNo = "No";	
	} else {
		var yesNo = "Yes";
	}

	// Number of days
	var numDaysObj = window.document.getElementsByName('numDays');
	var numDays = parseInt(numDaysObj[0].value);
	


	// Loop over all days from current day to end
	for(var i=dateNumber;i<numDays;i++) {
		
		var useLabel = "used_" + eqid + "_" + i;
		var useObj = window.document.getElementsByName(useLabel);
		var useImageObj = window.document.getElementsByName(useLabel + "_image");
		if(useImageObj.length > 0 && useObj.length > 0) {
			
			// Switch to new value
			useObj[0].value = yesNo;
			
			// Change to appropriate image
			if(yesNo == "Yes") {
				useImageObj[0].src = yesImage.src;
			} else {
				useImageObj[0].src = noImage.src;	
			}
		} else {
			i = numDays + 1;	
		}
		
	}
	
	
	// Post Data
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'eqid',eqid);
	addPostToForm(myForm,'addEdit',addEdit);
	addPostToForm(myForm,'visible','Yes');
	
	
	var uid = window.document.getElementsByName('uid')[0].value;
	
	// Go to the Code to Update the Database
	myForm.target = 'hiddenFrame';
	myForm.action = '/site/projects/dryingArea/updateEquipmentUsage.php';
	myForm.method = 'POST';
	myForm.submit();
	

}

//=================================================
//
// dryingAreaEquipmentCheckBox
//
function dryingAreaEquipmentCheckBox(eqid) {

	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaEquipmentForm')[0];
	
	// Get the checklist
	var checkboxList = window.document.getElementsByName('addEquipSelect');
	var checkCount = 0;
	for(var i=0;i<checkboxList.length;i++) {
		
		if(checkboxList[i].value == eqid) {
			if(checkboxList[i].checked == true) {
				checkboxList[i].checked = false;	
			} else {
				checkboxList[i].checked = true;
			}
		}
	}

}



//=================================================
//
// dryingAreaEquipmentCheckBox
//
function dryingAreaEquipmentCheckBoxOn(eqid) {

	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaEquipmentForm')[0];
	
	// Get the checklist
	var checkboxList = window.document.getElementsByName('addEquipSelect');
	var checkCount = 0;
	for(var i=0;i<checkboxList.length;i++) {
		
		if(checkboxList[i].value == eqid) {
			checkboxList[i].checked = true;
		}
	}

}



//=======================================================================================
//=======================================================================================
//=======================================================================================
//=======================================================================================
//                                      Pro Version
//=======================================================================================
//=======================================================================================
//=======================================================================================
//=======================================================================================



//=================================================
//
// Add Equipment to Drying Area (Pro)
//
function dryingAreaEquipmentProAdd(projectID, roomid, addEdit) {
	
	
	// Get the form
	var myForm = window.document.getElementsByName('dryingAreaEquipmentForm')[0];
	
	// Get the checklist
	var checkboxList = window.document.getElementsByName('addEquipSelect');
	var checkList = new Array();
	var checkCount = 0;
	for(var i=0;i<checkboxList.length;i++) {
		if(checkboxList[i].checked) {
			checkList[checkCount] = checkboxList[i].value;
			
			var obj = window.document.getElementsByName('qty_' + checkList[checkCount]);
			var qty = obj[0].value;
			
			var source = window.document.getElementsByName('source_' + checkList[checkCount])[0].value;
			
			addPostToForm(myForm,'check_' + checkCount,checkList[checkCount]);
			addPostToForm(myForm,'qty_' + checkCount,qty);
			
			addPostToForm(myForm,'source_' + checkCount,source);
			
			
			var costObj = window.document.getElementsByName('cost_' + checkList[checkCount]);
			var cost = new Number(0.00);
			if(costObj.length > 0) {
				cost = parseFloat(costObj[0].value);
				if(isNaN(cost)) {
					cost = 0.00;
				} else {
					cost = parseFloat(cost.toFixed(2));
				}
				costObj[0].value = cost;
			}
			addPostToForm(myForm,'cost_' + checkCount,cost);
			
			checkCount++;
		}
	}
	
	
	
	
	// Post the number of check points
	addPostToForm(myForm,'checkCount',checkCount);
	addPostToForm(myForm,'pid',projectID);
	addPostToForm(myForm,'roomid',roomid);
	addPostToForm(myForm,'addEdit',addEdit);
	
	// Go to the Code to Update the Database
	myForm.target = '_top';
	myForm.action = '/site/projects/dryingArea/updateEquipmentProUsageAdd.php';
	myForm.method = 'POST';
	myForm.submit();
}




//=======================================================================================
//=======================================================================================
//=======================================================================================
//=======================================================================================
//                                      Scout Version
//=======================================================================================
//=======================================================================================
//=======================================================================================
//=======================================================================================


//===============================================
//
// Print Moisture Scout Report
//
function printMoistureScoutReport() {
	
	
	// Get the form
	var myForms = window.document.getElementsByName("dryingAreaDetailsForm");
	var myForm = myForms[0];
	
	// Get the number of generic equipment
	var genericObj = window.document.getElementsByName("numGenerics");
	var numGenerics = genericObj[0].value;
	
	// Used CFM (Desiccant)
	var usedCFM_DD = 0;
	
	// Used AHAM (Conventional/LGR)
	var usedAHAM_ConvLGR = 0;
	
	// Used CFM (AS)
	var usedCFM_AS = 0;
	
	// Air Mover
	var numAM = 0;
	
	
	// Number of Equipment Pieces
	var numEquipment = 0;
		
	// Get the quantities
	for(var i=0;i<numGenerics;i++) {
		
	
		// Get the equipment ID
		var eqidObj = window.document.getElementsByName("equipment_" + i);
		var equipmentID = eqidObj[0].value;
		
	
		// Get the qty
		var qtyObj = window.document.getElementsByName("qty_" + equipmentID);
		var qty = qtyObj[0].value;
		if(qty == "" || isNaN(qty)) {
			qtyObj[0].value = 0;
			qty = 0;
		} else {
			qty = parseInt(qty);	
		}
		
		
		// Don't bother if there is no quantity
		if(qty > 0) {
			
			// Check the equipment type
			var eqTypeObj = window.document.getElementsByName("eqType_" + equipmentID);
			var eqType = eqTypeObj[0].value;
			
			// Check the equipment type
			var eqTypeIDObj = window.document.getElementsByName("eqTypeID_" + equipmentID);
			var eqTypeID = eqTypeIDObj[0].value;
			
			// Check the model name eqModelName
			var modelNameObj = window.document.getElementsByName("eqModelName_" + equipmentID);
			var modelName = modelNameObj[0].value;
			
			
			// Check the equipment power
			var eqPower = window.document.getElementsByName("eqType_Power_" + equipmentID)[0].value;
			
			// Air Mover Calculator
			if(eqType == "Air Mover") {
				numAM += qty;
			}
			
			if(eqType == "Air Scrubber") {
				var CFM_AS_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_AS = parseFloat(CFM_AS_Obj[0].value);
				usedCFM_AS = usedCFM_AS + (qty * CFM_AS);
			} 
			
			if(eqType == "Desiccant Dehumidifier") {
				var CFM_DD_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_DD = parseFloat(CFM_DD_Obj[0].value);
				usedCFM_DD = usedCFM_DD + (qty * CFM_DD);
			}
			
			if(eqType == "Desiccant Dehumidifier" || 
			   eqType == "Refrigerant Dehumidifier") {
			
				var AHAM_Obj = window.document.getElementsByName("eqPerf_GOMRPD_" + equipmentID);
				var AHAM = parseFloat(AHAM_Obj[0].value);
				usedAHAM_ConvLGR = usedAHAM_ConvLGR + (qty * AHAM);
			}
			
			//
			// Store the equipment information in POST
			//
			
			// qty
			addPostToForm(myForm,'qty_' + numEquipment,qty);
			
			// equipment ID
			addPostToForm(myForm,'equipmentID_' + numEquipment,equipmentID);
			
			// equipment type
			addPostToForm(myForm,'eqType_' + numEquipment,eqType);
			
			// equipment type id
			addPostToForm(myForm,'eqTypeID_' + numEquipment,eqTypeID);
			
			// model name
			addPostToForm(myForm,'modelName_' + numEquipment, modelName);
			
			// Power
			addPostToForm(myForm,'eqPower_' + numEquipment, eqPower);
			
			
			// Up-tick number of equipment
			numEquipment++;
			
			
		}
	
	}

	// number of equipment
	addPostToForm(myForm,'numEquipment',numEquipment);
	
	// usedAHAM_ConvLGR 
	addPostToForm(myForm,'usedCFM_DD',usedCFM_DD);

	// usedAHAM_ConvLGR 
	addPostToForm(myForm,'usedAHAM_ConvLGR',usedAHAM_ConvLGR);
	
	// number of air scrubbers CFM
	addPostToForm(myForm,'usedCFM_AS',usedCFM_AS);
	
	// number of air movers
	addPostToForm(myForm,'used_AM',numAM);
	
	
	//======================================================================
	//
	// Submit
	//
	myForm.target = 'hiddenFrame';
	myForm.method = 'POST';
	myForm.action = '/site/utilities/genMoistureScoutReport.php';
	myForm.submit();
	
	
}




//===============================================
//
// Print Moisture Scout Report
//
function printMoistureScoutReportPage() {
	
	
	// Get the form
	var myForms = window.document.getElementsByName("dryingAreaDetailsForm");
	var myForm = myForms[0];
	
	// Get the number of generic equipment
	var genericObj = window.document.getElementsByName("numGenerics");
	var numGenerics = genericObj[0].value;
	
	// Used CFM (Desiccant)
	var usedCFM_DD = 0;
	
	// Used AHAM (Conventional/LGR)
	var usedAHAM_ConvLGR = 0;
	
	// Used CFM (AS)
	var usedCFM_AS = 0;
	
	// Air Mover
	var numAM = 0;
	
	
	// Number of Equipment Pieces
	var numEquipment = 0;
		
	// Get the quantities
	for(var i=0;i<numGenerics;i++) {
		
	
		// Get the equipment ID
		var eqidObj = window.document.getElementsByName("equipment_" + i);
		var equipmentID = eqidObj[0].value;
		
	
		// Get the qty
		var qtyObj = window.document.getElementsByName("qty_" + equipmentID);
		var qty = qtyObj[0].value;
		if(qty == "" || isNaN(qty)) {
			qtyObj[0].value = 0;
			qty = 0;
		} else {
			qty = parseInt(qty);	
		}
		
		
		// Don't bother if there is no quantity
		if(qty > 0) {
			
			// Check the equipment type
			var eqTypeObj = window.document.getElementsByName("eqType_" + equipmentID);
			var eqType = eqTypeObj[0].value;
			
			// Check the equipment type
			var eqTypeIDObj = window.document.getElementsByName("eqTypeID_" + equipmentID);
			var eqTypeID = eqTypeIDObj[0].value;
			
			// Check the model name eqModelName
			var modelNameObj = window.document.getElementsByName("eqModelName_" + equipmentID);
			var modelName = modelNameObj[0].value;
			
			
			// Check the equipment power
			var eqPower = window.document.getElementsByName("eqType_Power_" + equipmentID)[0].value;
			
			// Air Mover Calculator
			if(eqType == "Air Mover") {
				numAM += qty;
			}
			
			if(eqType == "Air Scrubber") {
				var CFM_AS_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_AS = parseFloat(CFM_AS_Obj[0].value);
				usedCFM_AS = usedCFM_AS + (qty * CFM_AS);
			} 
			
			if(eqType == "Desiccant Dehumidifier") {
				var CFM_DD_Obj = window.document.getElementsByName("eqPerf_CFM_" + equipmentID);
				var CFM_DD = parseFloat(CFM_DD_Obj[0].value);
				usedCFM_DD = usedCFM_DD + (qty * CFM_DD);
			}
			
			if(eqType == "Desiccant Dehumidifier" || 
			   eqType == "Refrigerant Dehumidifier") {
			
				var AHAM_Obj = window.document.getElementsByName("eqPerf_GOMRPD_" + equipmentID);
				var AHAM = parseFloat(AHAM_Obj[0].value);
				usedAHAM_ConvLGR = usedAHAM_ConvLGR + (qty * AHAM);
			}
			
			//
			// Store the equipment information in POST
			//
			
			// qty
			addPostToForm(myForm,'qty_' + numEquipment,qty);
			
			// equipment ID
			addPostToForm(myForm,'equipmentID_' + numEquipment,equipmentID);
			
			// equipment type
			addPostToForm(myForm,'eqType_' + numEquipment,eqType);
			
			// equipment type id
			addPostToForm(myForm,'eqTypeID_' + numEquipment,eqTypeID);
			
			// model name
			addPostToForm(myForm,'modelName_' + numEquipment, modelName);
			
			// Power
			addPostToForm(myForm,'eqPower_' + numEquipment, eqPower);
			
			
			// Up-tick number of equipment
			numEquipment++;
			
			
		}
	
	}

	// number of equipment
	addPostToForm(myForm,'numEquipment',numEquipment);
	
	// usedAHAM_ConvLGR 
	addPostToForm(myForm,'usedCFM_DD',usedCFM_DD);

	// usedAHAM_ConvLGR 
	addPostToForm(myForm,'usedAHAM_ConvLGR',usedAHAM_ConvLGR);
	
	// number of air scrubbers CFM
	addPostToForm(myForm,'usedCFM_AS',usedCFM_AS);
	
	// number of air movers
	addPostToForm(myForm,'used_AM',numAM);
	
	
	//======================================================================
	//
	// Submit
	//
	myForm.target = '_blank';
	myForm.method = 'POST';
	myForm.action = '/site/utilities/genMoistureScoutReport.php?var=print';
	myForm.submit();
	
	
}



//==============================================
//
// Update Drying Area GPP (Scout)
//
function updateDryingAreaGPPScout() {
	
	// Get temperature
	var obj = window.document.getElementsByName("area_temperature");
	var area_temperature = obj[0].value;
	if(isNaN(area_temperature) || area_temperature == "") {
		if(area_temperature != "") {
			area_temperature = 0;
			obj[0].value = area_temperature;
		} 
	}
	area_temperature = parseFloat(area_temperature);
	
	
	
	// Get rh
	var obj = window.document.getElementsByName("area_rh");
	var area_rh = obj[0].value;
	if(isNaN(area_rh) || area_rh == "") {
		if(area_rh != "") {
			area_rh = 0;
			obj[0].value = area_rh;
		}
	}
	area_rh = parseFloat(area_rh);
	
	
	// Calculate GPP
	var gpp = parseFloat(calcGPP_withTempCheck(area_temperature,area_rh));
	
	// Display GPP
	var gppObj = window.document.getElementsByName("area_gpp");
	if(area_temperature == "" || area_rh == "" || isNaN(area_rh) || isNaN(area_temperature)) {
		var gppFormat = "N/A";
		gppObj[0].style.color = "#FF0000";
	} else {
		var gppFormat = gpp.toFixed(2);
		gppObj[0].style.color = "#000000";
	}
	gppObj[0].value = gppFormat;

}


//=============================================
//
// Update GPP Calculations (Scout)
//
function updateGPPScout() {


	// Update the drying area values
	updateDryingAreaGPPScout();
	
	
	
	
	// Get temperature
	var obj = window.document.getElementsByName("area_temperature");
	var area_temperature = obj[0].value;
	if(isNaN(area_temperature) || area_temperature == "") {
		if(area_temperature != "") {
			area_temperature = 0;
			obj[0].value = area_temperature;
		}
	}
	area_temperature = parseFloat(area_temperature);
	
	
	
	// Get rh
	var obj = window.document.getElementsByName("area_rh");
	var area_rh = obj[0].value;
	if(isNaN(area_rh) || area_rh == "") {
		if(area_rh != "") {
			area_rh = 0;
			obj[0].value = area_rh;
		}
	}
	area_rh = parseFloat(area_rh);
	
	
	// Calculate GPP
	var gpp = parseFloat(calcGPP_withTempCheck(area_temperature,area_rh));
	if(area_temperature == "" || area_rh == "" || isNaN(area_temperature) || isNaN(area_rh)) {
		gpp = "N/A";	
	}
	
	
	// Get the number of dehumidifiers
	var obj = window.document.getElementsByName("numDehumidifiers");
	var numDehumidifiers = obj[0].value;
	if(numDehumidifiers == "" || isNaN(numDehumidifiers)) {
		numDehumidifiers = 0;
		obj[0].value = numDehumidifiers;
	}
	numDehumidifiers = parseInt(numDehumidifiers);
	
	
	// Loop over DHs
	for(var i=0;i<numDehumidifiers;i++) {
	
	
	
		// Get the track ID
		var obj = window.document.getElementsByName("dehumidifier_trackID_" + i);
		var trackID = obj[0].value;
		
		
		// Get the temperature
		//atLeastZero("dehumidifier_temperature_" + trackID);
		var obj = window.document.getElementsByName("dehumidifier_temperature_" + trackID);
		if(isNaN(obj[0].value)) {
			obj[0].value = 0;
		}
		var dehumidifier_temperature = obj[0].value;
		
		
		// Get the rh
		//atLeastZero("dehumidifier_rh_" + trackID);
		var obj = window.document.getElementsByName("dehumidifier_rh_" + trackID);
		if(isNaN(obj[0].value)) {
			obj[0].value = 0;
		}
		var dehumidifier_rh = obj[0].value;
		
		
		// Calculate the dh gpp
		var dh_gpp = parseFloat(calcGPP_withTempCheck(dehumidifier_temperature,dehumidifier_rh));
		var dh_gpp_color;
		if(dehumidifier_temperature == "" || dehumidifier_rh == "" || isNaN(dehumidifier_temperature) || isNaN(dehumidifier_rh)) {
			dh_gpp = "N/A";
			dh_gpp_color = "red";
		} else {
			dh_gpp = dh_gpp.toFixed(2);	
			dh_gpp_color = "black";
		}
		
		
		
		
		// Calculate the dh gd
		if(area_temperature == "" || area_rh == "" || dehumidifier_temperature == "" || dehumidifier_rh == "" ||
		   isNaN(area_temperature) || isNaN(area_rh) || isNaN(dehumidifier_temperature) || isNaN(dehumidifier_rh)) {
			var dh_gd = "N/A";
			var dh_gd_color = "red";
		} else {
			var dh_gd = parseFloat(gpp - dh_gpp);
			if(dh_gd < 0) {
				var dh_gd_color = "red";	
			} else {
				var dh_gd_color = "black";
			}
			var dh_gd = dh_gd.toFixed(2);
		}
		
		
		
		// Update the dh gpp
		var obj = window.document.getElementsByName("dehumidifier_gpp_" + trackID);
		obj[0].value = dh_gpp;
		obj[0].style.color = dh_gpp_color;
		
		// Update the dh gd
		var obj = window.document.getElementsByName("dehumidifier_gd_" + trackID);
		obj[0].value = dh_gd;
		obj[0].style.color = dh_gd_color;
	
	}
	

}


//================================
//
// Calculate Power Usage
//
function updateKWScout() {

	// If there is no spot to put the power usage, don't bother calculating
	var totalPowerUsageObjs = window.document.getElementsByName('totalPowerUsage');
	if(totalPowerUsageObjs.length == 1) {
		
		// Loop over the generic equipment list
		// and sum the product of qty and power
		var numGenerics = window.document.getElementsByName('numGenerics')[0].value;
		var totalPowerUsage = 0;
		for(var i=0;i<numGenerics;i++) {
			
			var eqid = window.document.getElementsByName('equipment_' + i)[0].value;
			var power = window.document.getElementsByName('eqType_Power_' + eqid)[0].value;
			var qty = window.document.getElementsByName('qty_' + eqid)[0].value;
			totalPowerUsage += (parseFloat(power) * parseFloat(qty));
		}
		totalPowerUsage = totalPowerUsage / 1000;
		totalPowerUsageObjs[0].value = totalPowerUsage.toFixed(2);
	}
}


//================================
//
// Refresh Scout Page
//
function refreshScoutPage() {
	
	// Get the form
	var myForms = window.document.getElementsByName("dryingAreaDetailsForm");
	var myForm = myForms[0];
	
	myForm.method = 'POST';
	myForm.action = '/site/utilities/utilities.php#dh';
	myForm.target = '_top';
	myForm.submit();
	
}


//===============================
//
// Clear Scout Page
//
function clearScoutPage() {

	
	// Are you sure?
	var answer = confirm('Are you sure you wish to clear this form?');
	if(answer == false) {
		return;	
	}
	
	var randomNumber = Math.floor(Math.random()*100000000);
	
	window.location = '/site/utilities/utilities.php?rand='+randomNumber;

}



//=========================================
//
// Flush TinyMCE for the Moisture Map Page
//
function flushTinyMCE(elementID) {
	
	// Flush TinyMCE to value
	try {
	  if(tinyMCE) {
		  tinyMCE.triggerSave();
		  var notesObj = $("#" + elementID);
		  var notesText = tinyMCE.get(elementID).getContent();
		  notesObj.value = tinyMCE.get(elementID).getContent();
		  
	  }
	} catch(err) {}
	
}


//=========================================
//
// Flush TinyMCE for the Moisture Map Page
//
function flushDryingAreaMoistureMapTinyMCE() {
	
	// Flush TinyMCE to value
	if(tinyMCE) {
		tinyMCE.triggerSave();
		var notesObj = window.document.getElementsByName('notes')[0];
		
		var notesText = tinyMCE.get('notes').getContent();
		
		notesObj.value = tinyMCE.get('notes').getContent();
		
	}
}


//===========================================
//
// Delete Selected Equipment
//
function deleteSelectedEquipment(projectID, roomid) {

	var myForm = createForm(window,'myForm');
	
	var selectboxes = window.document.getElementsByName('equipmentSelectBox');
	
	var confirmationAlert = "Are you absolutely certain you wish to delete the following equipment: \n";
	
	var numEquipment = 0;
	var equipmentID = new Array();
	for(var ieq = 0; ieq < selectboxes.length ; ieq++) {
		if(selectboxes[ieq].checked == true) {
			
			
			equipmentID[numEquipment] = selectboxes[ieq].value;
			
			
			// Get equipment name
			if(numEquipment < 15) {
				var equipmentName = window.document.getElementsByName("equipment_" + selectboxes[ieq].value)[0].value;
				confirmationAlert = confirmationAlert + equipmentName + '\n';
			}
			
			numEquipment++;
		}
	}
	addPostToForm(myForm,"equipmentID",equipmentID);
	addPostToForm(myForm,'numEquipment',numEquipment);
	if(numEquipment >= 14) {
		confirmationAlert = confirmationAlert + "etc...\n";	
	}
	
	confirmationAlert = confirmationAlert + '\n\nThis operation cannot be undone.\n';
	
	if(numEquipment == 0) {
		alert('Select equipment in use you wish to delete.');
		return false;
	} else {
		var answer = confirm(confirmationAlert);
		if(answer == false) {
			window.document.removeChild(myForm);
			return false;	
		}
	}
	
	
	addPostToForm(myForm,'projectID',projectID);
	addPostToForm(myForm,'roomid',roomid);

	myForm.method = 'post';
	myForm.target = '_top';
	myForm.action = '/site/projects/dryingArea/deleteSelectedEquipment.php';
	myForm.submit();
}
