// 
// Global Variables
//

var formchange = 0;
var inf = null;
var gReqItems;
var gReqLabels;
var quickStartMode = '';
var cursor = {x:0, y:0};
var altbldg = 0;
var activeprimaryuse = -1

if(navigator.appVersion.indexOf('MSIE') < 0) {
	window.document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorPosition;


/////////////////////////////////////////////////////////////////////////
function resetTabs(tabid) {
	resetTab('tab_YourAccount');

	resetTab('tab_Custodial');
	resetTab('tab_Demographics');
	resetTab('tab_Maintenance');
	resetTab('tab_Security');
	resetTab('tab_Utilities');
	resetTab('tab_Analyze');

	resetTab('tab_YourCompany');
	resetTab('tab_BuildingSurveys');
	resetTab('tab_Analysis');
	resetTab('tab_Purchase');

	resetTab('tab_Sustainability');
	resetTab('tab_LEED-EBWorksheet');

	if($(tabid) != undefined) {
		document.getElementById(tabid).className = 'tabheader on';
		document.getElementById(tabid).blur();
	}
}


/////////////////////////////////////////////////////////////////////////
function resetTab(tabid) {
	if(document.getElementById(tabid)) {
		document.getElementById(tabid).className = 'tabheader off';
	}
}


/////////////////////////////////////////////////////////////////////////
function pageInitialize() {
	if($('footer')) {
		$('footer').style.width = '700px';
	}

	if($('graphpanel')) {
		$('graphpanel').style.display = 'none';
	}

	if($('surveypanel')) {
		$('surveypanel').style.display = '';
	}
	window.onscroll = '';
}


/////////////////////////////////////////////////////////////////////////
function inputChange(thisinput, options) {
	formchange = 1;

	if($(thisinput).style != undefined) {
		thisinput.style.background = '#FFFFFF';
	}

	if(options.indexOf('sum') >= 0) {
		sumPageValues(thisinput);
	}
}


/////////////////////////////////////////////////////////////////////////
function inputUtilityWaterSewerCombined(curelement) {
	var f, i, sum1 = 0, sumfield1;

	document.getElementById('utility_strint_water_annual_cost_add2_sum1').value = '';
	document.getElementById('utility_strint_sewer_annual_cost_add2').value = '';

	f = document.forms[0]
	for(i = 0; i < f.elements.length; i++) {
		if(f[i].id.indexOf('_add1') > 0) {
			sum1 += currencyToFloat(f[i].value);
		}

		if(f[i].id.indexOf('_sum1') > 0) {
			sumfield1 = f[i];
		} 
	}
	if(sumfield1) { sumfield1.value = Math.round(sum1 * 100)/100; }
}


/////////////////////////////////////////////////////////////////////////
function UtilitiesSetCO2Default() {
	$('utility_strint_co2_conversion').value = $('co2convdefault').innerHTML;
}


/////////////////////////////////////////////////////////////////////////
function sumMaintenanceChart(colname, curelement) {
	var f, i;
	var totalval = 0;
	var totalhvac = 0;
	var totaltrades = 0;
	var totaltech = 0;
	var totalalt = 0;
	var subtotalhvac = 0;
	var subtotaltrades = 0;
	var subtotaltech = 0;
	var subtotalalt = 0;
	var totalfield, hvacfield, tradesfield, techfield;
	var section = '';
	var pos1, pos2;

	// Format strictly numeric field
	curelement.value = curelement.value.replace(',', '');
	curelement.style.background = '#FFFFFF';

	if(curelement.id.indexOf('_') >= 0) {
		var pos1 = curelement.id.indexOf('_strint_') + 8;
		var pos2 = curelement.id.indexOf('_', pos1 + 1);
		section = curelement.id.substring(pos1, pos2);
	}

	if(curelement.id.indexOf('_total_') >= 0) {
		if(confirm('You have modified a auto-computed total field.  If you click OK, the fields above that were summed to compute this field will be cleared.') == true) {
			if(curelement.id == 'maintenance_strint_pppm_total_cost') {
				maintFieldsClearColumns('ex_int', 'total');
				maintFieldsClearColumns('ex_cont', 'total');
				maintFieldsClearColumns('ex', 'combined');

			} else if(curelement.id == 'maintenance_strint_total_building_maint_cost') {
				maintFieldsClearColumns('std_int', 'total');
				maintFieldsClearColumns('std_cont', 'total');
				maintFieldsClearColumns('std', 'combined');
				maintFieldsClearColumns('ex_int', 'total');
				maintFieldsClearColumns('ex_cont', 'total');
				maintFieldsClearColumns('ex', 'combined');

			} else if(curelement.id == 'maintenance_strint_total_std_int') {
				maintFieldsClearColumns('std_int', 'total');
			} else if(curelement.id == 'maintenance_strint_total_std_cont') {
				maintFieldsClearColumns('std_cont', 'total');
			} else if(curelement.id == 'maintenance_strint_total_std') {
				maintFieldsClearColumns('std', 'combined');
			} else if(curelement.id == 'maintenance_strint_total_ex_int') {
				maintFieldsClearColumns('ex_int', 'total');
			} else if(curelement.id == 'maintenance_strint_total_ex_cont') {
				maintFieldsClearColumns('ex_cont', 'total');
			} else if(curelement.id == 'maintenance_strint_total_ex') {
				maintFieldsClearColumns('ex', 'combined');
			} else if(curelement.id == 'maintenance_strint_total_excp_int') {
				maintFieldsClearColumns('excp_int', 'total');
			} else if(curelement.id == 'maintenance_strint_total_excp_cont') {
				maintFieldsClearColumns('excp_cont', 'total');
			} else if(curelement.id == 'maintenance_strint_total_excp') {
				maintFieldsClearColumns('excp', 'combined');
			}
		} else {
			curelement.value = '';
			if(curelement.id == 'maintenance_strint_total_std' ||
			 curelement.id == 'maintenance_strint_total_ex' ||
			 curelement.id == 'maintenance_strint_total_excp') {
				maintSumCombinedTotals();
			}
		}
	}

	// alert('cur element id is ' + curelement.id + ', section is ' + section + ' colname is ' + colname);

	// Pre-Process SubTotal Field
	if(curelement.id.indexOf('_subtotal_') >= 0) {
		// the next function returns the number of section summed fields 
		if(preCheckMaintChartSections(curelement, colname, section) > 0) {
			if(confirm('You have modified a auto-computed sub-total field.  If you click OK, the fields that were summed to compute this field will be cleared.') == true) {
				maintFieldsClearSummed(colname, section);
			} else {
				curelement.value = '';
			}
		}
	}

	// Scan and Identify All Fields within Column
	f = document.forms[0]
	for(i = 0; i < f.elements.length; i++) {
		if(f[i].id.indexOf(colname) > 0) {

			// Standard (non-total) Field
			if(f[i].id.indexOf('total') < 0) {
				if(IsNumeric(f[i].value)) {
					if(f[i].id.indexOf('maintenance_strint_hvac_') == 0) { 
						subtotalhvac += parseFloat(f[i].value); 
						totalhvac += parseFloat(f[i].value); 
					} else if(f[i].id.indexOf('maintenance_strint_trades') == 0) { 
						subtotaltrades += parseFloat(f[i].value); 
						totaltrades += parseFloat(f[i].value); 
					} else if(f[i].id.indexOf('maintenance_strint_tech') == 0) { 
						subtotaltech += parseFloat(f[i].value); 
						totaltech += parseFloat(f[i].value); 
					} else {
						totalalt += parseFloat(f[i].value);
						subtotalalt += parseFloat(f[i].value);
					}
				}
			} else {
				if(f[i].id.indexOf('_total_') >= 0) {
					totalfield = f[i];
				}
			}

			// Identify SubTotal Fields
			if(f[i].id.indexOf('maintenance_strint_hvac_subtotal_' + colname) == 0) {
					hvacfield = f[i];
			} else if(f[i].id.indexOf('maintenance_strint_trades_subtotal_' + colname) == 0) {
					tradesfield = f[i];
			} else if(f[i].id.indexOf('maintenance_strint_tech_subtotal_' + colname) == 0) {
					techfield = f[i];
			}
		}
	}


	// Sum current SubTotal Field
	if(curelement.id.indexOf(section + '_subtotal_' + colname) >= 0) {
		// alert('subtotal field ' + section);
		totalhvac = hvacfield.value; 
		totaltech = techfield.value;
		totaltrades = tradesfield.value;

	// Sum current Standard Field
	} else {
		// alert('not a subtotal field, cur element id is ' + curelement.id + ', section is ' + section + ' colname is ' + colname);
		if(section == 'hvac') {
 			hvacfield.value = Math.round(subtotalhvac * 100)/100;
			totalhvac = hvacfield.value
		} else if(section == 'tech') {
 			techfield.value = Math.round(subtotaltech * 100)/100;
			totaltech = techfield.value
		} else if(section == 'trades') {
 			tradesfield.value = Math.round(subtotaltrades * 100)/100;
			totaltrades = tradesfield.value
		}
		if(hvacfield) { totalhvac = hvacfield.value; }
		if(totaltech) { totaltech = techfield.value; }
		if(totaltrades) { totaltrades = tradesfield.value; }
	}
	totalval = Math.round(100 * (Number(totalhvac) + Number(totaltrades) + Number(totaltech) + Number(subtotalalt))/100);

	// alert('total [0] hvac/tech/trades is ' + totalhvac + '/' + totaltech + '/' + totaltrades);

	if(totalfield) {
		if(totalval > 0) {
			totalfield.value = totalval;
		}
	}

	if(curelement.id != 'maintenance_strint_total_std' &&
	 curelement.id != 'maintenance_strint_total_ex' &&
	 curelement.id != 'maintenance_strint_total_excp') {
		maintSumCombinedTotals();
	}

	// TOTAL COLS 1 and 2
	var tbmc = 0;
	var pppmtotal = 0;

	var buftot = 0;
	var bufval = document.getElementById('maintenance_strint_total_std').value;
	if(parseInt(bufval)) { buftot += parseInt(bufval); }
	tbmc += buftot;


	if(curelement.id != 'maintenance_strint_pppm_total_cost' && curelement.id != 'maintenance_strint_total_building_maint_cost') {
		// TOTAL COLS 3 and 4
		var buftot = 0;
		var bufval = $('maintenance_strint_total_ex').value;
		if(parseInt(bufval)) { buftot += parseInt(bufval); }
		tbmc += buftot;
		pppmtotal += buftot;
		$('maintenance_strint_pppm_total_cost').value = buftot;
	} else {
		pppmtotal = $('maintenance_strint_pppm_total_cost').value;
	}
	
	// TOTAL COLS 4 and 5
	if(curelement.id != 'maintenance_strint_pppm_total_cost' && curelement.id != 'maintenance_strint_total_building_maint_cost') {
		var buftot = 0;
		var bufval = $('maintenance_strint_total_excp').value;
		if(parseInt(bufval)) { buftot += parseInt(bufval); }
		$('maintenance_strint_total_building_maint_cost').value = tbmc;
	}

	// PPP
	$('maintenance_strint_pct_tbm_ppp').value = Math.round(100 * (100 * ($('maintenance_strint_pppm_total_cost').value/($('maintenance_strint_total_building_maint_cost').value))))/100;

	if(isNaN($('maintenance_strint_pct_tbm_ppp').value)) {
		$('maintenance_strint_pct_tbm_ppp').value = '';
	}

	// FCI
	if($('maintenance_strint_deferred_maintenance').value != '' && $('maintenance_strint_current_replacement_value').value != '') {
		$('maintenance_strint_facility_condition_index').value = Math.round(100 * ($('maintenance_strint_deferred_maintenance').value / $('maintenance_strint_current_replacement_value').value))/100;
	}
	
	// Update Contractual Arrangement fields
	if($('maintenance_strint_total_std_int').value == 0 &&
	 $('maintenance_strint_total_ex_int').value == 0 &&
	 $('maintenance_strint_total_excp_int').value == 0) {
		$('maintenance_contractual_emp_union').selectedIndex = 3;
	}

	if($('maintenance_strint_total_std_cont').value == 0 &&
	 $('maintenance_strint_total_ex_cont').value == 0 &&
	 $('maintenance_strint_total_excp_cont').value == 0) {
		$('maintenance_contractual_cont_union').selectedIndex = 3;
	}

	if($('maintenance_strint_pct_tbm_ppp').value == '' ||
	 isNaN($('maintenance_strint_pct_tbm_ppp').value)) {
		$('maintenance_bestpr_pm_65_85_no').checked = true;
		$('maintenance_bestpr_pm_40_64_no').checked = true;
		$('maintenance_bestpr_pm_lessthan_40_no').checked = true;
	} else if($('maintenance_strint_pct_tbm_ppp').value >= 65 &&
	 $('maintenance_strint_pct_tbm_ppp').value < 85) {
		$('maintenance_bestpr_pm_65_85_yes').checked = true;
		$('maintenance_bestpr_pm_40_64_yes').checked = true;
		$('maintenance_bestpr_pm_lessthan_40_yes').checked = true;
	} else if($('maintenance_strint_pct_tbm_ppp').value >= 40 &&
	 $('maintenance_strint_pct_tbm_ppp').value < 65) {
		$('maintenance_bestpr_pm_65_85_no').checked = true;
		$('maintenance_bestpr_pm_40_64_yes').checked = true;
		$('maintenance_bestpr_pm_lessthan_40_yes').checked = true;
	} else if($('maintenance_strint_pct_tbm_ppp').value < 40) {
		$('maintenance_bestpr_pm_65_85_no').checked = true;
		$('maintenance_bestpr_pm_40_64_no').checked = true;
		$('maintenance_bestpr_pm_lessthan_40_yes').checked = true;
	}
}


/////////////////////////////////////////////////////////////////////////
function maintenanceFieldChange(qno) {

	if(qno == 'BPM6') {
		if($('maintenance_bestpr_mms_all_yes').checked == true) {
			$('maintenance_bestpr_mms_most_yes').checked = true;
			$('maintenance_bestpr_mms_most_no').checked = false;
		}

	} else if(qno == 'BPM7') {
		if($('maintenance_bestpr_mms_most_yes').checked == true) {
			$('maintenance_bestpr_mms_all_yes').checked = false;
			$('maintenance_bestpr_mms_all_no').checked = true;
		} else if($('maintenance_bestpr_mms_most_no').checked == true) {
			$('maintenance_bestpr_mms_all_yes').checked = false;
			$('maintenance_bestpr_mms_all_no').checked = true;
		}

	} else if(qno == 'BPM14') {
		if($('maintenance_bestpr_ppm_most_major_equip_yes').checked == false) {
			$('maintenance_bestpr_ppm_all_major_equip_yes').checked = false;
			$('maintenance_bestpr_ppm_all_major_equip_no').checked = true;
		}
	} else if(qno == 'BPM15') {
		if($('maintenance_bestpr_ppm_all_major_equip_yes').checked == true) {
			$('maintenance_bestpr_ppm_most_major_equip_yes').checked = true;
		}
	} else if(qno == 'BPM10') {
		if($('maintenance_bestpr_pm_65_85_yes').checked == true) {
			$('maintenance_bestpr_pm_40_64_yes').checked = true;
			$('maintenance_bestpr_pm_lessthan_40_yes').checked = true;
		} 

	} else if(qno == 'BPM11') {
		if($('maintenance_bestpr_pm_40_64_yes').checked == true) {
			$('maintenance_bestpr_pm_65_85_no').checked = true;
			$('maintenance_bestpr_pm_lessthan_40_yes').checked = true;

		} else if($('maintenance_bestpr_pm_40_64_no').checked == true) {
			$('maintenance_bestpr_pm_65_85_no').checked = true;
		}

	} else if(qno == 'BPM12') {
		if($('maintenance_bestpr_pm_lessthan_40_yes').checked == true) {
			$('maintenance_bestpr_pm_65_85_no').checked = true;
			$('maintenance_bestpr_pm_40_64_no').checked = true;

		} else if($('maintenance_bestpr_pm_lessthan_40_no').checked == true) {
			$('maintenance_bestpr_pm_65_85_no').checked = true;
			$('maintenance_bestpr_pm_40_64_no').checked = true;
		}
	}

	if(qno == 'BPM10' || qno == 'BPM11' || qno == 'BPM12') {
		// Check settings against M27 for validity
		if($('maintenance_strint_pct_tbm_ppp').value >= 65 &&
		 $('maintenance_strint_pct_tbm_ppp').value < 85) {
			if($('maintenance_bestpr_pm_65_85_yes').checked != true ||
			$('maintenance_bestpr_pm_40_64_yes').checked != true ||
			$('maintenance_bestpr_pm_lessthan_40_yes').checked != true) {
				alert("This value is in-conflict with the value computed on line M27.");
			}
		}

		if($('maintenance_strint_pct_tbm_ppp').value >= 40 &&
		 $('maintenance_strint_pct_tbm_ppp').value < 65) {
			if($('maintenance_bestpr_pm_65_85_yes').checked != false ||
			$('maintenance_bestpr_pm_40_64_yes').checked != true ||
			$('maintenance_bestpr_pm_lessthan_40_yes').checked != true) {
				alert("This value is in-conflict with the value computed on line M27.");
			}
		}

		if($('maintenance_strint_pct_tbm_ppp').value < 40) {
			if($('maintenance_bestpr_pm_65_85_yes').checked != false ||
			$('maintenance_bestpr_pm_40_64_yes').checked != false ||
			$('maintenance_bestpr_pm_lessthan_40_yes').checked != true) {
				alert("This value is in-conflict with the value computed on line M27.");
			}
		}
	}

}


/////////////////////////////////////////////////////////////////////////
function demographicsFieldChange(qno, priuse) {
	var f, i;

	if(qno == 'D11') {

		// Clear old tier-two selections
		if(activeprimaryuse > 0) {
			f = $('specificuse_block_' + activeprimaryuse).getElementsByTagName('*');
			for(i = 0; i < f.length; i++) {
				f[i].checked = false;
			}
		}

		f = $('primary_use_block').getElementsByTagName('*');
		for(i = 0; i < f.length; i++) {
			if(f[i].value != '' && f[i].value != null && f[i].value > -1) {
				if($('building_primary_use').options[$('building_primary_use').selectedIndex].value == f[i].value) {
					$('specificuse_block_' + f[i].value).style.display = 'block';
					activeprimaryuse = f[i].value;

				} else {
					$('specificuse_block_' + f[i].value).style.display = 'none';
				}
			}
		}

		var d11val = $('building_primary_use').options[$('building_primary_use').selectedIndex].value;

		if(priuse == -1 || d11val == -1) {
			$('building_primary_use').selectedIndex = $('building_primary_use').options.length - 1;
			$('primary_use_other_panel').style.display = '';
		} else {
			$('primary_use_other_panel').style.display = 'none';
		} 

	} else if(qno == 'D22') {
		f = $('association_block').getElementsByTagName('*');
		for(i = 0; i < f.length; i++) {
			if(f[i].id != undefined) {
				if(f[i].id.indexOf('building_assoc_') >= 0) {
					var buf = f[i].id.replace('building_assoc_', '');
					if($('assocdesignation_' + buf) != undefined) { 
  						if(f[i].checked == true) {
							$('assocdesignation_' + buf).style.display = 'block';
						} else {
							$('assocdesignation_' + buf).style.display = 'none';
	
							c = $('assocdesignation_' + buf).getElementsByTagName('input');
							for(j = 0; j < c.length; j++) {
								if(c[j].id != undefined) {
									if(c[j].id.indexOf('building_associationdesignation_') >= 0) {
										c[j].checked = false;
									}
								}
							}
						}
					}
				}
			}
		}

	} else if(qno == 'D22a') {
	    cb = priuse.split('|');
        if($(cb[0]).checked == true) {
			$('building_assoc_' + cb[1]).checked = true;
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function custodialFieldChange(qno) {

	if(qno == 'BPC18') {
		if($('custodial_bestpr_requests_tracked_completely_yes').checked == true) {
			$('custodial_bestpr_requests_tracked_sometimes_yes').checked = false;
			$('custodial_bestpr_requests_tracked_sometimes_no').checked = true;
			$('custodial_bestpr_requests_not_tracked_yes').checked = false;
			$('custodial_bestpr_requests_not_tracked_no').checked = true;
		}
	} else if(qno == 'BPC19') {
		if($('custodial_bestpr_requests_tracked_sometimes_yes').checked == true) {
			$('custodial_bestpr_requests_tracked_completely_yes').checked = false;
			$('custodial_bestpr_requests_tracked_completely_no').checked = true;
			$('custodial_bestpr_requests_not_tracked_yes').checked = false;
			$('custodial_bestpr_requests_not_tracked_no').checked = true;
		}

	} else if(qno == 'BPC20') {
		if($('custodial_bestpr_requests_not_tracked_yes').checked == true) {
			$('custodial_bestpr_requests_tracked_completely_yes').checked = false;
			$('custodial_bestpr_requests_tracked_completely_no').checked = true;
			$('custodial_bestpr_requests_tracked_sometimes_yes').checked = false;
			$('custodial_bestpr_requests_tracked_sometimes_no').checked = true;
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function securityFieldChange(qno) {

	if(qno == 'BPS2') {
		if($('security_bestpr_guardforce_cert_greater_than_80_yes').checked == true) {
			$('security_bestpr_guardforce_cert_bet_40_80_yes').checked = false;
			$('security_bestpr_guardforce_cert_bet_40_80_no').checked = true;
			$('security_bestpr_guardforce_cert_less_than_40_yes').checked = false;
			$('security_bestpr_guardforce_cert_less_than_40_no').checked = true;
		}
	} else if(qno == 'BPS3') {
		if($('security_bestpr_guardforce_cert_bet_40_80_yes').checked == true) {
			$('security_bestpr_guardforce_cert_greater_than_80_yes').checked = false;
			$('security_bestpr_guardforce_cert_greater_than_80_no').checked = true;
			$('security_bestpr_guardforce_cert_less_than_40_yes').checked = false;
			$('security_bestpr_guardforce_cert_less_than_40_no').checked = true;
		}
	} else if(qno == 'BPS4') {
		if($('security_bestpr_guardforce_cert_less_than_40_yes').checked == true) {
			$('security_bestpr_guardforce_cert_bet_40_80_yes').checked = false;
			$('security_bestpr_guardforce_cert_bet_40_80_no').checked = true;
			$('security_bestpr_guardforce_cert_greater_than_80_yes').checked = false;
			$('security_bestpr_guardforce_cert_greater_than_80_no').checked = true;
		}
	} else if(qno == 'BPS13') {
		if($('security_bestpr_personnel_training_greater_than_80_yes').checked == true) {
			$('security_bestpr_personnel_training_bet_40_80_yes').checked = false;
			$('security_bestpr_personnel_training_bet_40_80_no').checked = true;
			$('security_bestpr_personnel_training_less_than_40_yes').checked = false;
			$('security_bestpr_personnel_training_less_than_40_no').checked = true;
		}
	} else if(qno == 'BPS14') {
		if($('security_bestpr_personnel_training_bet_40_80_yes').checked == true) {
			$('security_bestpr_personnel_training_less_than_40_yes').checked = false;
			$('security_bestpr_personnel_training_less_than_40_no').checked = true;
			$('security_bestpr_personnel_training_greater_than_80_yes').checked = false;
			$('security_bestpr_personnel_training_greater_than_80_no').checked = true;
		}
	} else if(qno == 'BPS15') {
		if($('security_bestpr_personnel_training_less_than_40_yes').checked == true) {
			$('security_bestpr_personnel_training_bet_40_80_yes').checked = false;
			$('security_bestpr_personnel_training_bet_40_80_no').checked = true;
			$('security_bestpr_personnel_training_greater_than_80_yes').checked = false;
			$('security_bestpr_personnel_training_greater_than_80_no').checked = true;
		}
	}

}


/////////////////////////////////////////////////////////////////////////
function currencyToFloat(value) {

// alert('converting ' + value);
	value = value.replace(',', '');
	if(IsNumeric(value)) {
// alert('returning ' + parseFloat(value));
		return parseFloat(value);
	} else {
		return 0;
	}

}


/////////////////////////////////////////////////////////////////////////
function sumPageValues(curelement) {
	var f, i;
	var sumfield = null, sumbuf = 0;

	f = document.forms[0]

	for(j = 1; j <= 4; j++) {
		sumbuf = 0;
		for(i = 0; i < f.elements.length; i++) {
			if(f[i].id.indexOf('_add' + j) > 0) {
				sumbuf += currencyToFloat(f[i].value);
			}

			if(f[i].id.indexOf('_sum' + j) > 0) {
				sumfield = f[i].id;
			}
		}

		if(sumfield != null && sumbuf != 0) { 
			$(sumfield).value = Math.round(sumbuf * 100)/100; 
		}
	}

	// for Securities page only
	if(document.getElementById('security_strint_pct_costs_perimeter_total_sum2')) {
		var buftot = 100 * (parseInt(document.getElementById('security_strint_security_costs_perimeter_total_sum3').value)/parseInt(document.getElementById('security_strint_security_costs_total_sum1').value));

		document.getElementById('security_strint_pct_costs_perimeter_internal_add2').value = Math.round(((10000 * document.getElementById('security_strint_security_costs_perimeter_internal_add3').value) / document.getElementById('security_strint_security_costs_internal_add1').value)) / 100;

		document.getElementById('security_strint_pct_costs_perimeter_contractual_add2').value = Math.round(((10000 * document.getElementById('security_strint_security_costs_perimeter_contractual_add3').value) / document.getElementById('security_strint_security_costs_contractual_add1').value)) / 100;

		document.getElementById('security_strint_pct_costs_perimeter_total_sum2').value = Math.round(buftot * 100 )/100;
	}

	// Update Custodial Contractual Arrangement fields
	if($('custodial_strint_total_cost_internal_sum1')) {
		if($('custodial_strint_total_cost_internal_sum1').value == 0) {
			$('custodial_contractual_emp_union').selectedIndex = 3;
		}
		if($('custodial_strint_total_cost_contractual_sum2').value == 0) {
			$('custodial_contractual_cont_union').selectedIndex = 3;
		}
	}

	// Update Security Contractual Arrangement fields
	if($('security_strint_security_costs_internal_add1')) {
		if($('security_strint_security_costs_internal_add1').value == 0) {
			$('security_union_or_non_employees').selectedIndex = 3;
		}
		if($('security_strint_security_costs_contractual_add1').value == 0) {
			$('security_union_or_non_contractors').selectedIndex = 3;
		}
	}

	// For Utilities Page
	if($('utility_strint_power_usage_effectiveness')) {
		document.getElementById('utility_strint_power_usage_effectiveness').value = Math.round(document.getElementById('utility_strint_data_center_energy_annual_cons').value / document.getElementById('utility_strint_it_energy_annual_cons').value);
		computeCarbonFootprint();

	}

}


/////////////////////////////////////////////////////////////////////////
function computeCarbonFootprint() {
	var cfnatgas = 1000 * $('utility_strint_natural_gas_annual_cons').value * ConvertGasToCubicFeet(1) * ConvertCFGasToCO2Pounds(1) * ConvertPoundsToWeight(1);

	var cfoil = 1000 * $('utility_strint_fuel_oil_annual_cons').value * ConvertLiquidToUSGallons(1) * ConvertOilUSGallonsToCO2Pounds(1) * ConvertPoundsToWeight(1);

	var cfgasoline = 1000 * $('utility_strint_gasoline_onsite_annual_cons').value * ConvertLiquidToUSGallons(1) * ConvertGasolineUSGallonsToCO2Pounds(1) * ConvertPoundsToWeight(1);

	var cfdiesel = 1000 * $('utility_strint_diesel_onsite_annual_cons').value * ConvertLiquidToUSGallons(1) * ConvertDieselUSGallonsToCO2Pounds(1) * ConvertPoundsToWeight(1);

	// var cfelec = 1000 * $('utility_strint_electricity_annual_cons').value * ConvertElectricToKWH(1) * $('utility_strint_co2_conversion').value;
	var cfelec = 1000 * $('utility_strint_electricity_annual_cons').value * $('utility_strint_co2_conversion').value;

	var cfwaterchilled = 1000 * $('utility_strint_water_chilled_annual_cons').value * ConvertElectricToBTU(1) * ConvertWaterChilledBTUToCO2Pounds(1) * ConvertPoundsToWeight(1);

	var cfwaterhot = 1000 * $('utility_strint_water_hot_annual_cons').value * ConvertElectricToBTU(1) * ConvertWaterHotBTUToCO2Pounds(1) * ConvertPoundsToWeight(1);

	var cfsteam = 1000 * $('utility_strint_steam_annual_cons').value * ConvertElectricToBTU(1) * ConvertWaterHotBTUToCO2Pounds(1) * ConvertPoundsToWeight(1);

	// var tot = cfnatgas + '<br>' + cfoil + '<br>' + cfgasoline + '<br>' + cfdiesel + '<br>---<br>' + cfelec + '<br>' + cfwaterchilled + '<br>' + cfwaterhot + '<br>' + cfsteam + '<br> TOTAL: ' + (cfnatgas + cfoil + cfgasoline + cfdiesel + cfelec + cfwaterchilled + cfwaterhot + cfsteam);

	var tot = cfnatgas + cfoil + cfgasoline + cfdiesel + cfelec + cfwaterchilled + cfwaterhot + cfsteam;

	tot = FormatNumber(Math.round(tot));

	$('co2_footprint_calc_ro').innerHTML = tot;
	$('utility_strint_co2_footprint').value = tot;
}


/////////////////////////////////////////////////////////////////////////
function preCheckMaintChartSections(curelement, colname, mode) {
	var f;
	var i;
	var hvacsubtotal;
	var tradessubtotal;
	var techsubtotal;
	var hvacsumfields = 0;
	var tradessumfields = 0;
	var techsumfields = 0;

// alert('colname is ' + colname);

	f = document.forms[0]
	for(i = 0; i < f.elements.length; i++) {
		if(f[i].id.indexOf(colname) > 0) {

			if(f[i].id.indexOf('maintenance_strint_hvac_') == 0) { 
// alert('adding hvac');
				if(f[i].id.indexOf('subtotal') < 0) {
					if(f[i].value != '') { hvacsumfields++; }
				} else {
					hvacsubtotal = f[i].value;
				}
// alert('hvactotal is ' + hvacsubtotal);

			} else if(f[i].id.indexOf('maintenance_strint_trades_') == 0) {
				if(f[i].id.indexOf('subtotal') < 0) {
					if(f[i].value != '') { tradessumfields++; }
				} else {
					tradessubtotal = f[i].value;
				}

			} else if(f[i].id.indexOf('maintenance_strint_tech') == 0) {
				if(f[i].id.indexOf('subtotal') < 0) {
					if(f[i].value != '') { techsumfields++; }
				} else {
					techsubtotal = f[i].value;
				}
			}
		}
	}

	if(mode == 'hvac') {
		return hvacsumfields;
	} else if(mode == 'trades') {
		return tradessumfields;
	} else if(mode == 'tech') {
		return techsumfields;
	}
}


/////////////////////////////////////////////////////////////////////////
function maintFieldsClearSummed(colname, section) {
	var f, i;

	f = document.forms[0]
	for(i = 0; i < f.elements.length; i++) {
		if(f[i].id.indexOf(colname) > 0 && f[i].id.indexOf(section) > 0) {
			if(f[i].id.indexOf('subtotal') < 0) {
				// alert('clearing field ' + f[i].id);
				f[i].value = '';
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////
function maintFieldsClearColumns(colname, mode) {
	var f, i;

	f = document.forms[0]
	for(i = 0; i < f.elements.length; i++) {
		if(f[i].id.indexOf(colname) > 0 && f[i].id.indexOf('_total_') < 0) {
			// alert('clearing field ' + f[i].id);
			f[i].value = '';
		}
	}

	if(mode == 'combined') {
		if(colname == 'std') {
			$('maintenance_strint_total_std_int').value = 0;
			$('maintenance_strint_total_std_cont').value = 0;
		} else if(colname == 'ex') {
			$('maintenance_strint_total_ex_int').value = 0;
			$('maintenance_strint_total_ex_cont').value = 0;
		} else if(colname == 'excp') {
			$('maintenance_strint_total_excp_int').value = 0;
			$('maintenance_strint_total_excp_cont').value = 0;
		}
	} else {
		maintSumCombinedTotals();
	}
}


/////////////////////////////////////////////////////////////////////////
function maintSumCombinedTotals() {

	if($('maintenance_strint_total_std_int').value == '') {
		$('maintenance_strint_total_std_int').value = 0;
	}
	if($('maintenance_strint_total_std_cont').value == '') {
		$('maintenance_strint_total_std_cont').value = 0;
	}
	$('maintenance_strint_total_std').value = 
	 parseInt($('maintenance_strint_total_std_int').value) + 
	 parseInt($('maintenance_strint_total_std_cont').value);


	if($('maintenance_strint_total_ex_int').value == '') {
		$('maintenance_strint_total_ex_int').value = 0;
	}
	if($('maintenance_strint_total_ex_cont').value == '') {
		$('maintenance_strint_total_ex_cont').value = 0;
	}
	$('maintenance_strint_total_ex').value = 
	 parseInt($('maintenance_strint_total_ex_int').value) + 
	 parseInt($('maintenance_strint_total_ex_cont').value);


	if($('maintenance_strint_total_excp_int').value == '') {
		$('maintenance_strint_total_excp_int').value = 0;
	}
	if($('maintenance_strint_total_excp_cont').value == '') {
		$('maintenance_strint_total_excp_cont').value = 0;
	}
	$('maintenance_strint_total_excp').value = 
	 parseInt($('maintenance_strint_total_excp_int').value) + 
	 parseInt($('maintenance_strint_total_excp_cont').value);
}


/////////////////////////////////////////////////////////////////////////
function saveClearWait(menuid) {
	saveCurrentPage();
	document.body.style.cursor = 'wait';

	// below, causes menu to permanently disappear
	// $(menuid).style.display = 'none';
}


/////////////////////////////////////////////////////////////////////////
function saveCurrentPage() {

	if(formchange == 1) {
		if(confirm('Save current page (Cancel to continue without saving)?')) {
			if(document.forms[0]) {
				// alert('found form ' + document.forms[0].id);
				document.forms[0].onsubmit();
				// alert('Page saved.');
			}
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function saveCurrentPageAndForward(url) {

	if(formchange == 1) {
		if(confirm('Save current page (Cancel to continue without saving)?')) {
			if(document.forms[0]) {
				// alert('found form ' + document.forms[0].id);
				document.forms[0].onsubmit();
				// alert('Page saved.');
			}
		}
	}
	// alert('forwarding to ' + url);
	document.location = url;
}


/////////////////////////////////////////////////////////////////////////
function IsNumeric(strString) {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;
   var i;

   if (strString.length == 0) return false;

   for (i = 0; i < strString.length && blnResult == true; i++) {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1) {
         blnResult = false;
      }
   }
   return blnResult;
}


/////////////////////////////////////////////////////////////////////////
function ProcessErrors(model, jsonerrors) {
	var buf, i;
	var errstr = "";
	var newdiv;

	ClearErrorMessages();
	ClearErrorMessages();

	buf = jsonerrors.evalJSON();
	for(i = 0; i < buf.length; i++) {
		// alert(model + '_' + buf[i][0] + ' -- ' + buf[i][1]);
		$(model + '_' + buf[i][0]).style.background = '#FF7777';

		newdiv = document.createElement('div');
		newdiv.className = 'errormsgfield';
		newdiv.id = 'errmsg00' + i;

		var errval = String(buf[i][1])
		if(errval.indexOf("*", 0) == "0") {
			newdiv.innerHTML = errval.substring(1);
		} else {
			newdiv.innerHTML = errval;
		}
		Element.insert($(model + '_' + buf[i][0]), {before: newdiv});

		if(String(buf[i][1]).indexOf("*", 0) == "0") {
			errstr += "<li>" + errval.substring(1) + "</li>";

		} else {

			var errfield = String(buf[i][0]);
			errfield = errfield.replace(/_/g, ' ');
			errfield = errfield.replace(/ add\d/g, ' ');
			errfield = errfield.replace(/strint /g, ' ');
			errfield = errfield.replace(/tag fiscal year end 1i/g, 'fiscal year end');

			var errval = String(buf[i][1]);
			errval = errval.replace(/required field/g, 'is a required field');
			errstr += "<li>" + errfield + ": " + errval + "</li>";
		}
	}

	var diverr = document.getElementById('errors_for_' + model);
    diverr.style.border = "none";
	diverr.innerHTML = "<table style=\"width:99%;border:2px solid #FF0000;background:#FFFF00;color:#FF0000\"<tr><td><b>There was a problem with your entry.  Please correct the following:</b><ul>" + errstr + "</ul></td></tr></table><br />";
	diverr.style.display = "";

	if(model == 'purchase') {
		UnlockPurchaseButton();
	}

	document.body.style.cursor = 'default';
	window.scroll(0, 0);

	document.getElementById('errormsgbottom').style.display = 'none';
	formchange = 0;
	return;
}


/////////////////////////////////////////////////////////////////////////
function ClearErrorMessages() {
	var errs = document.getElementsByClassName('errormsgfield');
	for(i = 0; i < errs.length; i++) {
		$(errs[i]).remove();
	}

	// clear red background from input fields
	var errs = document.forms[0].getElements();
	for(i = 0; i < errs.length; i++) {
		if($(errs[i]).type != "submit" && $(errs[i]).type != "button") {
			$(errs[i]).style.background = "#FFFFFF";
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function ProcessTextError(model, errmsg) {

	ClearErrorMessages();

	var diverr = document.getElementById('errors_for_' + model);
    diverr.style.border = "none";
	diverr.innerHTML = "<table style=\"width:99%;border:2px solid #FF0000;background:#FFFF00;color:#FF0000\"<tr><td><b>" + errmsg + "</b></td></tr></table><br />";
	diverr.style.display = "";

	if($('errormsgbottom')) {
		$('errormsgbottom').style.display = 'none';
	}
	document.body.style.cursor = 'default';
	window.scroll(0, 0);
}


/////////////////////////////////////////////////////////////////////////
function ProcessUpdateSuccess(model) {
	var buf, i;
	var newdiv

	// clear localized error messages
	var errs = document.getElementsByClassName('errormsgfield');
	for(i = 0; i < errs.length; i++) {
		$(errs[i]).remove();
	}

	// clear red background from input fields
	var errs = document.forms[0].getElements();
	for(i = 0; i < errs.length; i++) {
		if($(errs[i]).type != "submit" && $(errs[i]).type != "button") {
			$(errs[i]).style.background = "#FFFFFF";
		}
	}

	var diverr = document.getElementById('errors_for_' + model);

    diverr.style.border = "none";
	diverr.innerHTML = "<table style=\"width:99%;border:2px solid #00AACC;background:#99FFFF;color:#000000\"<tr><td><b>Update complete.</b></td></tr></table><br />";

	// diverr.style.width = "99%";
	// diverr.style.border = "2px solid #00AACC";
	// diverr.style.color = "#00AACC";
	// diverr.style.background = "#FFFFFF";
	// diverr.innerHTML = "Update complete";
	diverr.style.display = "";

	document.body.style.cursor = 'default';
	window.scroll(0, 0);

	document.getElementById('errormsgbottom').style.display = 'none';
	formchange = 0;
}

 
/////////////////////////////////////////////////////////////////////////
function UpdateFieldIndicators(mode) {

	if(mode == 'superquickstart') {
		if(quickStartMode == 'superquickstart') {
			mode = '';
			quickStartMode = '';
		} else {
			quickStartMode = 'superquickstart';
		}
	} else if(mode == 'quickstart') {
		if(quickStartMode == 'quickstart') {
			mode = '';
			quickStartMode = '';
		} else {
			quickStartMode = 'quickstart';
		}
	}

	SetFieldIndicators(mode);

	new Ajax.Updater('', '/fieldindicator/update/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'mode=' + encodeURIComponent(mode)});
}


/////////////////////////////////////////////////////////////////////////
function SetFieldIndicators(mode) {

	// DEMOGRAPHICS
	SetFieldIndicator('strint_gross_square_area', mode);
	SetFieldIndicator('fiscal_year_end', mode);
	SetFieldIndicator('gross_area_measurement_type', mode);
	SetFieldIndicator('rentable_square_area', mode);
	SetFieldIndicator('rentable_area_measurement_type', mode);
	SetFieldIndicator('age', mode);
	SetFieldIndicator('geographic_region', mode);
	SetFieldIndicator('setting', mode);
	SetFieldIndicator('hours_per_day', mode);
	SetFieldIndicator('days_per_week', mode);
	SetFieldIndicator('site_type', mode);
	SetFieldIndicator('ownership', mode);
	SetFieldIndicator('primary_use', mode);
	SetFieldIndicator('background_check', mode);
	SetFieldIndicator('floors_above_grade', mode);
	SetFieldIndicator('ftes', mode);

	// UTILITIES
	SetFieldIndicator('electric_annual_cost_add4', mode);
	SetFieldIndicator('water_sewer_combined_cost_add4_sum2', mode);
	SetFieldIndicator('natural_gas_annual_cost_add4', mode);
	SetFieldIndicator('total_annual_cost_sum4', mode);
	SetFieldIndicator('electricity_annual_cons', mode);
	SetFieldIndicator('utility_motion_sensors_conference', mode);

	SetFieldIndicator('motion_sensors_conference', mode);
	SetFieldIndicator('motion_sensors_office', mode);
	SetFieldIndicator('motion_sensors_restrooms', mode);
	SetFieldIndicator('recommissioning_ongoing', mode);
	SetFieldIndicator('recommissioning_recommendations', mode);
	SetFieldIndicator('plate_frame_heat_exch', mode);
	SetFieldIndicator('tinted_filmed_windows', mode);
	SetFieldIndicator('addl_insulation_vertical', mode);
	SetFieldIndicator('energy_recovery_exhaust', mode);
	SetFieldIndicator('daylight_sensing_lighting', mode);
	SetFieldIndicator('mechanical_window_coverings', mode);

	SetFieldIndicator('bms_ems_hvac', mode);
	SetFieldIndicator('sub_metering', mode);
	SetFieldIndicator('solar_wind', mode);
	SetFieldIndicator('chiller_replacements', mode);
	SetFieldIndicator('initial_commissioning', mode);
	SetFieldIndicator('minor_repairs', mode);
	SetFieldIndicator('off_hour_controls', mode);
	SetFieldIndicator('high_efficiency_filters', mode);
	SetFieldIndicator('energy_efficient_lighting', mode);

	SetFieldIndicator('motor_vfds', mode);
	SetFieldIndicator('cycle_hvac', mode);
	SetFieldIndicator('economizer_cycle', mode);
	SetFieldIndicator('occupant_training', mode);
	SetFieldIndicator('glazing_glass', mode);
	SetFieldIndicator('energy_reduction_targets', mode);
	SetFieldIndicator('chiller_replacements_non_cfc', mode);
	SetFieldIndicator('co2_monitoring', mode);
	SetFieldIndicator('light_colored_roofing', mode);
	SetFieldIndicator('green_roofing', mode);
	SetFieldIndicator('addl_insulation', mode);

	SetFieldIndicator('bestpr_combined_heat_and_power', mode);
	SetFieldIndicator('bestpr_demand_side_management', mode);
	SetFieldIndicator('bestpr_gas_thermal_ac', mode);
	SetFieldIndicator('bestpr_ground_source', mode);
	SetFieldIndicator('bestpr_hybrid_cooling', mode);
	SetFieldIndicator('bestpr_individual_ventilation', mode);
	SetFieldIndicator('bestpr_on_site_generators', mode);
	SetFieldIndicator('bestpr_thermal_storage', mode);

	// CUSTODIALS
	SetFieldIndicator('total_cost_internal', mode);
	SetFieldIndicator('area_cleaned', mode);
	SetFieldIndicator('cust_employees', mode);
	SetFieldIndicator('cust_contractors', mode);
	SetFieldIndicator('cust_ftes', mode);

	SetFieldIndicator('freq_offices_low_dusting', mode);
	SetFieldIndicator('freq_offices_high_dusting', mode);
	SetFieldIndicator('freq_offices_trash_removal', mode);
	SetFieldIndicator('freq_offices_recycling_removal', mode);
	SetFieldIndicator('freq_offices_vacuuming', mode);
	SetFieldIndicator('freq_hallway_floor_care', mode);
	SetFieldIndicator('freq_hallway_trash_removal', mode);
	SetFieldIndicator('freq_reception_floor_care', mode);
	SetFieldIndicator('freq_reception_trash_removal', mode);
	SetFieldIndicator('freq_production_cleaning', mode);
	SetFieldIndicator('freq_lab_cleaning', mode);
	SetFieldIndicator('freq_restrooms_cleaning', mode);
	SetFieldIndicator('freq_cafeteria_cleaning', mode);
	SetFieldIndicator('freq_sweep_mop_comp_flooring', mode);
	SetFieldIndicator('freq_buf_tile_comp_flooring', mode);
	SetFieldIndicator('freq_wax_polish_comp_flooring', mode);
	SetFieldIndicator('freq_spot_clean_glass_entrance_doors', mode);
	SetFieldIndicator('freq_interior_window_blind_cleaning', mode);
	SetFieldIndicator('freq_upholstery', mode);
	SetFieldIndicator('freq_spot_carpet', mode);
	SetFieldIndicator('freq_light_ventilation', mode);
	SetFieldIndicator('freq_walls_switch_plates', mode);

	SetFieldIndicator('leed_green_supplies', mode);
	SetFieldIndicator('leed_recycling_compliance', mode);
	SetFieldIndicator('bestpr_requests_24_hours', mode);
	SetFieldIndicator('bestpr_areas_defined', mode);
	SetFieldIndicator('bestpr_freq_established', mode);
	SetFieldIndicator('bestpr_freq_reviewed', mode);
	SetFieldIndicator('bestpr_contract_rebid', mode);
	SetFieldIndicator('bestpr_cust_satisf_scored', mode);
	SetFieldIndicator('bestpr_cust_satisf_surveys', mode);
	SetFieldIndicator('bestpr_silent_vacuums', mode);
	SetFieldIndicator('bestpr_equip_ready', mode);
	SetFieldIndicator('bestpr_iso_9001', mode);
	SetFieldIndicator('bestpr_qa_plan', mode);

	SetFieldIndicator('bestpr_inspections_key', mode);
	SetFieldIndicator('bestpr_internal_mgt', mode);
	SetFieldIndicator('bestpr_natl_procurement', mode);
	SetFieldIndicator('bestpr_oos_separate', mode);
	SetFieldIndicator('bestpr_recycling_benefit', mode);
	SetFieldIndicator('bestpr_recycling_not_well_sorted', mode);
	SetFieldIndicator('bestpr_requests_tracked_completely', mode);
	SetFieldIndicator('bestpr_requests_tracked_sometimes', mode);
	SetFieldIndicator('bestpr_requests_not_tracked', mode);
	SetFieldIndicator('bestpr_day_30_minute_response', mode);
	SetFieldIndicator('bestpr_skip_cleaning', mode);

	SetFieldIndicator('bestpr_specialized_contracts', mode);
	SetFieldIndicator('bestpr_performance_incentives', mode);
	SetFieldIndicator('bestpr_turnover_monitored', mode);

	// MAINTENANCE
	SetFieldIndicator('maint_combined_totals', mode);
	SetFieldIndicator('maint_tbmc', mode);
	SetFieldIndicator('maint_employees', mode);
	SetFieldIndicator('maint_contractors', mode);
	SetFieldIndicator('maint_ftes', mode);

	SetFieldIndicator('bestpr_fci_completed', mode);
	SetFieldIndicator('bestpr_contractor_standards', mode);
	SetFieldIndicator('bestpr_handheld_devices', mode);
	SetFieldIndicator('bestpr_equipment_standards', mode);
	SetFieldIndicator('bestpr_jit', mode);
	SetFieldIndicator('bestpr_mms_all', mode);
	SetFieldIndicator('bestpr_mms_most', mode);
	SetFieldIndicator('bestpr_maintenance_as_needed', mode);

	SetFieldIndicator('bestpr_multiskilled_workforce', mode);
	SetFieldIndicator('bestpr_pm_65_85', mode);
	SetFieldIndicator('bestpr_pm_40_64', mode);
	SetFieldIndicator('bestpr_pm_lessthan_40', mode);
	SetFieldIndicator('bestpr_ppm_fully', mode);
	SetFieldIndicator('bestpr_ppm_most_major_equip', mode);
	SetFieldIndicator('bestpr_ppm_all_major_equip', mode);
	SetFieldIndicator('bestpr_staff_training', mode);
	SetFieldIndicator('bestpr_training_upgrade', mode);
	SetFieldIndicator('bestpr_ultrasound_thermal', mode);

	// SECURITY
	SetFieldIndicator('sust_total', mode);
	SetFieldIndicator('sust_ftes', mode);
	SetFieldIndicator('sust_employees', mode);
	SetFieldIndicator('sust_contractors', mode);

	SetFieldIndicator('bestpr_id_badges', mode);
	SetFieldIndicator('bestpr_guardforce_cert_greater_than_80', mode);
	SetFieldIndicator('bestpr_guardforce_cert_bet_40_80', mode);
	SetFieldIndicator('bestpr_guardforce_cert_less_than_40', mode);
	SetFieldIndicator('bestpr_internal_audit_reviews', mode);
	SetFieldIndicator('bestpr_lesson_plans_reviewed', mode);
	SetFieldIndicator('bestpr_access_cctv', mode);
	SetFieldIndicator('bestpr_security_reception_visitor_combined', mode);

	SetFieldIndicator('bestpr_security_reception_visitor_not_combined', mode);
	SetFieldIndicator('bestpr_turnover_monitored', mode);
	SetFieldIndicator('bestpr_specialized_functions_contracted', mode);
	SetFieldIndicator('bestpr_tailgating_prohibited', mode);
	SetFieldIndicator('bestpr_personnel_training_greater_than_80', mode);
	SetFieldIndicator('bestpr_personnel_training_bet_40_80', mode);
	SetFieldIndicator('bestpr_personnel_training_less_than_40', mode);
	SetFieldIndicator('bestpr_unmanned_revolving_doors', mode);

	if(mode == '') {
		$('legend-required').style.background = "#FFFFAA";
		$('legend-quickstart').style.background = "#FFFFFF";
		$('legend-superquickstart').style.background = "#FFFFFF";

	} else if(mode == 'quickstart') {
		$('legend-required').style.background = "#FFFFFF";
		$('legend-quickstart').style.background = "#FFFFAA";
		$('legend-superquickstart').style.background = "#FFFFFF";

	} else {
		$('legend-required').style.background = "#FFFFFF";
		$('legend-quickstart').style.background = "#FFFFFF";
		$('legend-superquickstart').style.background = "#FFFFAA";
	}
}


/////////////////////////////////////////////////////////////////////////
function SetFieldIndicator(fieldid, mode) {

	if(mode == '') {
		if($(fieldid + '_indicator_qs')) {
			$(fieldid + '_indicator_qs').style.display = 'none';
		}
		if($(fieldid + '_indicator_sqs')) {
			$(fieldid + '_indicator_sqs').style.display = 'none';
		}
		if($(fieldid + '_indicator_req')) {
			$(fieldid + '_indicator_req').style.display = '';
		}

	} else if(mode == 'quickstart') {
		if($(fieldid + '_indicator_sqs')) {
			$(fieldid + '_indicator_sqs').style.display = '';
		} else if($(fieldid + '_indicator_qs') != null) {
			$(fieldid + '_indicator_qs').style.display = '';
		} 

	} else if(mode == 'superquickstart') {
		if($(fieldid + '_indicator_qs')) {
			$(fieldid + '_indicator_qs').style.display = 'none';
		}
		if($(fieldid + '_indicator_sqs')) {
			$(fieldid + '_indicator_sqs').style.display = '';
		}
	}
}

/////////////////////////////////////////////////////////////////////////
function ProcessCreditCardResult(result, resultmessage, coid, authid, newsub) {

	// alert('cc res: ' + result + ', msg: ' + resultmessage + ', coid: ' + coid + ', authid: ' + authid + ', newsub: ' + newsub);

	var diverr = document.getElementById('errors_for_purchase');
    diverr.style.border = "none";
	diverr.style.display = "";

	ClearEntryErrors();
	$('instructions').style.display = 'none';

    if(result == "0") {
		diverr.innerHTML = "<table style=\"width:750px;border:2px solid #00AACC;background:#99FFFF;color:#000000\"<tr><td class=\"instructions\"><b>Purchase Complete.  New credit(s) have been added to your account, which will expire one year from today.</b><br><br><b>Next Steps:</b><ul><li>Print this page for your records (An e-mail receipt will also be sent to the card-holder e-mail address.)</li><li><a href=\"javascript:SwitchToBuildings('" + authid + "');\"><b>Click here</b></a> to input your buildings, or <a href=\"javascript:SwitchToSurveys('" + coid + "', '" + authid + "');\"><b>click here</b></a> to initiate surveys of buildings you have already input.</li></ul>" + $('aftersale').innerHTML + "</td></tr></table><br />";

		// Clear the credit card number and CVV
		document.getElementById('purchase_card_number').value = document.getElementById('purchase_card_number').value.substring(0, 4) + "************";
		document.getElementById('purchase_card_cvv').value = "***";

		// Show the new purchases
		$('costsurveycredits').innerHTML = parseInt($('costsurveycredits').innerHTML) + parseInt($('purchase_benchmarking_qty').value);
		$('costsurveycredits').style.background = "#FFFF00";
		$('sustainabilitysurveycredits').innerHTML = parseInt($('sustainabilitysurveycredits').innerHTML) + parseInt($('purchase_sustainability_qty').value);
		$('sustainabilitysurveycredits').style.background = "#FFFF00";

		// Update past purchases
		var newpastcost = parseInt($('pastcostcredits').value) + parseInt($('purchase_benchmarking_qty').value);
		$('pastcostcredits').value = newpastcost;
		$('pastcostcreditsdiv').innerHTML = newpastcost;

		var newpastsust = parseInt($('pastsustcredits').value) + parseInt($('purchase_sustainability_qty').value);
		$('pastsustcredits').value = newpastsust;
		$('pastsustcreditsdiv').innerHTML = newpastsust;

		$('pastcoan').innerHTML = parseInt($('pastcoan').innerHTML) + parseInt($('purchase_company_analysis_qty').value);

		// Display after-purchase message
		// $('aftersale').style.display = 'block';

		// Remove purchase button
		$('button_purchase').style.display = 'none';
		$('repurchase_message').style.display = '';

	} else {
		diverr.innerHTML = "<table style=\"width:99%;border:2px solid #FF0000;background:#FFFF00;color:#FF0000\"<tr><td><b>There was a problem charging your credit card.<br>The clearing company responded with this message: " + resultmessage + ".<br>Please review your card information and re-submit.</td></tr></table><br />";
	}

	document.body.style.cursor = 'default';
	window.scroll(0, 0);

	document.getElementById('errormsgbottom').style.display = 'none';
	UnlockPurchaseButton();
}


/////////////////////////////////////////////////////////////////////////
function ProcessCreditRenewalResult(nocost, nosust, coid, authid) {
//	alert('PCCR with ' + nocost + ' - ' + nosust + ' - ' + coid + ' - ' + authid);

	var diverr = document.getElementById('errors_for_purchase');
    diverr.style.border = "none";
	diverr.style.display = "";

	ClearEntryErrors();
	$('instructions').style.display = 'none';

	diverr.innerHTML = "<table style=\"width:750px;border:2px solid #00AACC;background:#99FFFF;color:#000000\"<tr><td class=\"instructions\"><b>Application of Credits Complete.  The surveys credited will expire one year from their former expiration date, or from today (depending upon when in your subscription cycle you renewed).  These new expiration dates can be seen by clicking the link in the second line below.</b><br><br><b>Next Steps:</b><ul><li>Print this page for your records.</li><li><a href=\"javascript:SwitchToSurveys('" + coid + "', '" + authid + "');\"><b>Click here</b></a> to access your surveys.</li></ul></td></tr></table><br />";

	// Show the reduced number of available credits
	$('costsurveycredits').innerHTML = 
     parseInt($('costsurveycredits').innerHTML) - parseInt(nocost);
	$('costsurveycredits').style.background = "#FFFF00";
	$('sustainabilitysurveycredits').innerHTML = 
     parseInt($('sustainabilitysurveycredits').innerHTML) - parseInt(nosust);
	$('sustainabilitysurveycredits').style.background = "#FFFF00";

	// Remove purchase button
	$('button_purchase').style.display = 'none';
	$('repurchase_message').style.display = '';

	document.body.style.cursor = 'default';
	window.scroll(0, 0);

	document.getElementById('errormsgbottom').style.display = 'none';
	UnlockPurchaseButton();
}


/////////////////////////////////////////////////////////////////////////
function ProcessCreditCardResultNFMT(result, resultmessage, coid, authid, newsub) {
	var diverr = document.getElementById('errors_for_purchase');
    diverr.style.border = "none";
	diverr.style.display = "";

	ClearEntryErrors();
	$('instructions').style.display = 'none';

	var msg = '<div style="margin:8px;margin-top:12px;margin-bottom:12px;border:3px double #AAAAAA;background:#EEEEEE;padding:16px;">';
	msg += '<span style="font-weight:bold;color:#666666;">';
	msg += '<a name="nfmtaddl">Special Offers:</a><br/><br/>'; 
    msg += '1. If your company had multiple NFMT attendees and you therefore ';
    msg += 'received more than one free subscription, you will have until ';
    msg += 'May 31 to activate it. <a href="#nfmtaddl" onClick="$(&quot;nfmtaddlins&quot;).style.display = &quot;block&quot;">Click here</a> for instructions.';

    msg += '<div id="nfmtaddlins" style="display:none;margin-left:20px;margin-right:20px;margin-top:10px;border:1px solid #666666;padding:10px;">';
    msg += '1. In the box near the bottom of the page, click on ';
    msg += '"Add a New User".<br/>';
    msg += '2. Fill in the boxes for each additional user needing ';
    msg += 'access to FM BENCHMARKING. <br/>';
    msg += '3. Each of those users should then log-in, and click "Purchase Credits" from the Main Menu.  On the Purchase Building Survey Credits screen, each should enter their unique e-mail address in the Coupon Code box.<br/>';
    msg += '</div>';

    msg += '<br/><br/>';
    msg += '2. If you would like to purchase additional credits to apply to ';
    msg += 'other buildings, you will receive a discount on them if ';
    msg += 'you complete the purchase within 60 days.  <br/><br/>';

    msg += '<u>Cost Surveys:</u><br/>';
    msg += 'Additional Cost Surveys, 1-7: $225/ea.<br/>';
    msg += 'Additional Cost Surveys, 7 or more: $210/ea.<br/><br/>';

    msg += '<u>Sustainability Surveys:</u><br/>';
    msg += 'Additional Sustainability Surveys, 1-7: $150/ea.<br/>';
    msg += 'Additional Sustainability Surveys, 7 or more: $135/ea.<br/><br/>';

    msg += '<u>Cost + Sustainability Surveys Combined (Ordered Together):</u><br/>';
    msg += 'Additional Combined Surveys, 1-7: $325/ea.<br/>';
    msg += 'Additional Combined Surveys, 7 or more: $285/ea.<br/><br/>';

    if(result == "0") {
		diverr.innerHTML = "<table style=\"width:750px;border:2px solid #00AACC;background:#99FFFF;color:#000000\"<tr><td class=\"instructions\"><b>Purchase Complete.  &nbsp;&nbsp; New credit(s) have been added to your account, which will expire one year from today.</b><br><br><b>Next Steps:</b><ul><li>Print this page for your records (An e-mail receipt will also be sent to the card-holder e-mail address.)</li><li><a href=\"javascript:SwitchToBuildings('" + authid + "');\"><b>Click here</b></a> to input your buildings, or <a href=\"javascript:SwitchToSurveys('" + coid + "', '" + authid + "');\"><b>click here</b></a> to initiate surveys of buildings you have already input.</li></ul>" + msg + "</td></tr></table><br />";

		// Clear the credit card number and CVV
		document.getElementById('purchase_card_number').value = document.getElementById('purchase_card_number').value.substring(0, 4) + "************";
		document.getElementById('purchase_card_cvv').value = "***";

		// Show the new purchases
		$('costsurveycredits').innerHTML = parseInt($('costsurveycredits').innerHTML) + parseInt($('purchase_benchmarking_qty').value);
		$('costsurveycredits').style.background = "#FFFF00";
		$('sustainabilitysurveycredits').innerHTML = parseInt($('sustainabilitysurveycredits').innerHTML) + parseInt($('purchase_sustainability_qty').value);
		$('sustainabilitysurveycredits').style.background = "#FFFF00";

		// Update past purchases
		var newpastcost = parseInt($('pastcostcredits').value) + parseInt($('purchase_benchmarking_qty').value);
		$('pastcostcredits').value = newpastcost;
		$('pastcostcreditsdiv').innerHTML = newpastcost;

		var newpastsust = parseInt($('pastsustcredits').value) + parseInt($('purchase_sustainability_qty').value);
		$('pastsustcredits').value = newpastsust;
		$('pastsustcreditsdiv').innerHTML = newpastsust;

		$('pastcoan').innerHTML = parseInt($('pastcoan').innerHTML) + parseInt($('purchase_company_analysis_qty').value);

		// Display after-purchase message
		// $('aftersale').style.display = 'block';

		// Remove purchase button
		$('button_purchase').style.display = 'none';
		$('repurchase_message').style.display = '';

	} else {
		diverr.innerHTML = "<table style=\"width:99%;border:2px solid #FF0000;background:#FFFF00;color:#FF0000\"<tr><td><b>There was a problem charging your credit card.<br>The clearing company responded with this message: " + resultmessage + ".<br>Please review your card information and re-submit.</td></tr></table><br />";
	}

	document.body.style.cursor = 'default';
	window.scroll(0, 0);

	document.getElementById('errormsgbottom').style.display = 'none';
	UnlockPurchaseButton();
}


/////////////////////////////////////////////////////////////////////////
function ResetPurchaseScreen() {

	$('purchase_benchmarking_qty').value = 0;
	$('purchase_sustainability_qty').value = 0;
	$('purchase_company_analysis_qty').value = 0;

	$('subtotalcostsurvey').innerHTML = "$0.00";
	$('subtotalsustsurvey').innerHTML = "$0.00";
	$('subtotalcompanyanalysis').innerHTML = "$0.00";
	$('combineddiscount').innerHTML = "$0.00";

	$('subtotal').innerHTML = "$0.00";
	$('prevdisc').innerHTML = "$0.00";
	$('refundprior').innerHTML = "$0.00";
	// $('totalpurchase').innerHTML = "$0.00";
	$('purchase_amount').innerHTML = "$0.00";
	$('ssl_amount').value = "$0.00";
	// $('alternativetotal').innerHTML = "$0.00";

	$('couponcodeerror').style.display = '';
	$('couponcodeerror').innerHTML = '';
	$('coupon_code').style.display = '';
	$('couponcodediscount').innerHTML = '';
	$('couponcodediscount').style.display = 'none';
	$('couponcodelabel2').style.display = 'none';
	$('couponcodelabel').style.display = '';

    $('coupon_code').value = '';

	ClearCouponCode();
	ShowHidePurchaseFieldsRequired('hide');
}


/////////////////////////////////////////////////////////////////////////
function ClearEntryErrors() {

	// clear localized error messages
	var errs = document.getElementsByClassName('errormsgfield');
	for(i = 0; i < errs.length; i++) {
		$(errs[i]).remove();
	}

	// clear red background from input fields
	var errs = document.forms[0].getElements();
	for(i = 0; i < errs.length; i++) {
		if($(errs[i]).type != "submit" && $(errs[i]).type != "button") {
			$(errs[i]).style.background = "#FFFFFF";
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function ProcessPreRegSuccess(model) {

	var divitem = document.getElementById('pagecontent');
	divitem.innerHTML = "<div class='heading'>Pre-Registration for FM BENCHMARKING</div><br /><br /><b>Thank you for your interest in FM BENCHMARKING.  We will be contacting you soon!</b>";
	divitem.style.display = "";

}

/////////////////////////////////////////////////////////////////////////
function BeforeFormSubmit(model) {
	document.body.style.cursor = 'wait';

	var diverr = document.getElementById('errormsgbottom');
	if(model == "purchase") {
		diverr.innerHTML = "<b>Please wait &#151; credit card processing could take up to 90 seconds.</b>";
	} else {
		diverr.innerHTML = "<b>Please Wait...</b>";
	}
	diverr.style.display = "";
}


/////////////////////////////////////////////////////////////////////////
function AfterFormSubmit() {
	// document.body.style.cursor = 'default';
	// window.scroll(0, 0);
}



/////////////////////////////////////////////////////////////////////////
function LockPurchaseButton() {
	document.getElementById("button_purchase").disabled = true;
}


/////////////////////////////////////////////////////////////////////////
function UnlockPurchaseButton() {
	document.getElementById("button_purchase").disabled = false;
}


/////////////////////////////////////////////////////////////////////////
function isNull(val) {
	return(val == null);
}


/////////////////////////////////////////////////////////////////////////
function PositionInformArea() {
// alert('PIA, inf top is ' + inf.style.top);
	if(inf) {
		inf.style.top = document.documentElement.scrollTop + 'px';
	}
}


/////////////////////////////////////////////////////////////////////////
function ShowPopup(name) {
	ClosePopup();
	document.getElementById(name).style.display = 'block';
}


/////////////////////////////////////////////////////////////////////////
function ClosePopup() {
	if($('definitionspopup')) {
		$('definitionspopup').style.display = 'none';
	}
	if($('instructionspopup')) {
		$('instructionspopup').style.display = 'none';
	}
	if($('helpmenupopup')) {
		$('helpmenupopup').style.display = 'none';
	}
}


/////////////////////////////////////////////////////////////////////////
function DisplayMedian(median) {
	document.getElementById('medianval').innerHTML = "<span style='color:#FF0000;font-weight:bold'>Median Value:<br />" + median + "</span><div style='height:4px;width:3px'></div>";

    if(document.getElementById('createanothergraph') != null) {
		document.getElementById('createanothergraph').disabled = '';
	}
    if(document.getElementById('returntorecentsurvey') != null) {
		document.getElementById('returntorecentsurvey').disabled = '';
	}
}


/////////////////////////////////////////////////////////////////////////
function DisplayYourValue(yourval) {
	document.getElementById('yourval').innerHTML = "<span style='color:#FF0000;font-weight:bold'>Your Building:<br />" + yourval + "</span>";
}


/////////////////////////////////////////////////////////////////////////
function DisplayNumberBuildings(nobldgs) {
	if(document.getElementById('numberbuildings')) {
		document.getElementById('numberbuildings').innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;<b>Number of Buildings:</b> " + nobldgs;
	}
}


/////////////////////////////////////////////////////////////////////////
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';

	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	if(x2 != 0) {
		return x1 + x2;
	} else {
		return x1;
	}
}


/////////////////////////////////////////////////////////////////////////
function FlashInformBox(err) {

		if(err != '') {
        	$('informbox').style.background = "#FF0000";
			$('informbox').morph('background:#FFCCCC;', { duration: 1.0 });

		} else {
        	$('informbox').style.background = "#FFFF00";
			$('informbox').morph('background:#FFFFFF;', { duration: 1.0 });
		}
}


/////////////////////////////////////////////////////////////////////////
function ValidatePurchaseFields() {

	if(isNaN($('purchase_benchmarking_qty').value) ||
	 parseInt($('purchase_benchmarking_qty').value) < 0 ||
	 $('purchase_benchmarking_qty').value == '') {
		alert('Please enter a number between 0 and 20 for the Cost Survey quantity.');
		$('purchase_benchmarking_qty').value = '0';
	} else if(parseInt($('purchase_benchmarking_qty').value) > 20) {
		$('purchase_benchmarking_qty').value = '20';
		qtycost = 20;
		alert('High-Quantity Pricing:  FM BENCHMARKING offers special pricing for purchases over 20 survey credits (per survey type).  Please e-mail us at info@fmbenchmarking.com to initiate this purchase.');
	}

	if(isNaN($('purchase_sustainability_qty').value) ||
	 parseInt($('purchase_sustainability_qty').value) < 0 ||
	 $('purchase_sustainability_qty').value == '') {
		alert('Please enter a number between 0 and 20 for the Sustainability Survey quantity.');
		$('purchase_sustainability_qty').value = '0';
	} else if(parseInt($('purchase_sustainability_qty').value) > 20) {
		$('purchase_sustainability_qty').value = '20';
		qtysust = 20;
		alert('High-Quantity Pricing:  FM BENCHMARKING offers special pricing for purchases over 20 survey credits (per survey type).  Please e-mail us at info@fmbenchmarking.com to initiate this purchase.');
	}

	if($('purchase_company_analysis_qty').value != '0' && 
	 $('purchase_company_analysis_qty').value != '1') {
		alert('Special Comparison Report quantity must be 0 or 1.');
		$('purchase_company_analysis_qty').value = '0';
		qtycoan = 0; 
	}
}


/////////////////////////////////////////////////////////////////////////
function SetAllRenewalExpiring(mode, thirtydays) {
	var costchg = 0;
	var sustchg = 0;
	var surveyid;

	for(var i = 0;  i < document.new_purchase.elements.length; i++) {
		if(document.new_purchase.elements[i].id.indexOf('renew_used_expiring_check') >= 0) {

			surveyid = document.new_purchase.elements[i].id.substring(26, 27);
			// alert('surveyid is ' + surveyid);

			if(mode == 'check') {
				if(document.new_purchase.elements[i].checked == false) {
					if(surveyid == 1) {
						costchg++;
					} else {
						sustchg++;
					}
					document.new_purchase.elements[i].checked = true;
					// alert('checked ' + document.new_purchase.elements[i].id);
					buf = document.new_purchase.elements[i].id.replace('used_expiring_check', 'used_expiring_from_unused_check');
					buf = buf.replace('used_expired_check', 'used_expired_from_unused_check');
					if($(buf) != 'undefined') {
						// alert('unchecking ' + buf);
						$(buf).checked = false;
					}


				}
			} else {
				if(document.new_purchase.elements[i].checked == true) {
					if(surveyid == 1) {
						costchg--
					} else {
						sustchg--
					}
					document.new_purchase.elements[i].checked = false;
				}
			}
		}
	}

	UpdatePurchaseQuantities(costchg, sustchg, thirtydays);
}


/////////////////////////////////////////////////////////////////////////
function SetAllRenewalExpired(mode, thirtydays) {
	var costchg = 0;
	var sustchg = 0;
	var surveyid;

	for(var i = 0;  i < document.new_purchase.elements.length; i++) {
		if(document.new_purchase.elements[i].id.indexOf('renew_used_expired_check') >= 0) {
			surveyid = document.new_purchase.elements[i].id.substring(25, 26);
			// alert('surveyid is ' + surveyid);

			if(mode == 'check') {
				if(document.new_purchase.elements[i].checked == false) {
					if(surveyid == 1) {
						costchg++;
					} else {
						sustchg++;
					}
					document.new_purchase.elements[i].checked = true;

					// alert('checked ' + document.new_purchase.elements[i].id);
                    buf = document.new_purchase.elements[i].id.replace('used_expiring_check', 'used_expiring_from_unused_check');
                    buf = buf.replace('used_expired_check', 'used_expired_from_unused_check');
                    if($(buf) != 'undefined') {
                        // alert('unchecking ' + buf);
                        $(buf).checked = false;
                    }
				}
			} else {
				if(document.new_purchase.elements[i].checked == true) {
					if(surveyid == 1) {
						costchg--
					} else {
						sustchg--
					}
					document.new_purchase.elements[i].checked = false;
				}
			}

//			if(mode == 'check') {
//				document.new_purchase.elements[i].checked = true;
//			} else {
//				document.new_purchase.elements[i].checked = false;
//			}
		}
	}

	UpdatePurchaseQuantities(costchg, sustchg, thirtydays);
}


/////////////////////////////////////////////////////////////////////////
function UpdateRenewalPurchaseTotal(mode, cb, thirtydays) {
	var costchg = 0;
	var sustchg = 0;
	var ibuf;

	if(mode == 'firsttime') {
		// alert('counting all');
		// count all
		for(var i = 0;  i < document.new_purchase.elements.length; i++) {
			ibuf = document.new_purchase.elements[i];
			if(ibuf.id.indexOf('renew_used_expiring_check') >= 0 || ibuf.id.indexOf('renew_used_expired_check') >= 0) {
				if(ibuf.checked == true) {
					if(ibuf.id.indexOf('renew_used_expired_check_1') >= 0 ||
					 ibuf.id.indexOf('renew_used_expiring_check_1') >= 0) {
						costchg++;
					} else {
						sustchg++;
					}
				}
			}
		}

	} else {
		// count change of this field only
		if(cb.checked == true) {
			if(cb.id.indexOf('renew_used_expired_check_1') >= 0 ||
			 cb.id.indexOf('renew_used_expiring_check_1') >= 0) {
				costchg++;
			}

			if(cb.id.indexOf('renew_used_expired_check_2') >= 0 ||
			 cb.id.indexOf('renew_used_expiring_check_2') >= 0) {
				sustchg++;
			}

			if(cb.id.indexOf('renew_used_expiring_from_unused_check_1') >= 0 ||
			 cb.id.indexOf('renew_used_expired_from_unused_check_1') >= 0) {
				costchg--;
			}

			if(cb.id.indexOf('renew_used_expiring_from_unused_check_2') >= 0 ||
			 cb.id.indexOf('renew_used_expired_from_unused_check_2') >= 0) {
				sustchg--;
			}

		} else {
			if(cb.id.indexOf('renew_used_expired_check_1') >= 0 ||
			 cb.id.indexOf('renew_used_expiring_check_1') >= 0) {
				costchg--;
			}

			if(cb.id.indexOf('renew_used_expired_check_2') >= 0 ||
			 cb.id.indexOf('renew_used_expiring_check_2') >= 0) {
				sustchg--;
			}
		}
	}

	// alert('updating fields');
	UpdatePurchaseQuantities(costchg, sustchg, thirtydays);
	UpdateRenewalSelections(cb);
}


/////////////////////////////////////////////////////////////////////////
function UpdatePurchaseQuantities(costchg, sustchg, thirtydays) {

	var qtycost = parseInt($('purchase_benchmarking_qty').value);
	var qtysust = parseInt($('purchase_sustainability_qty').value);
	qtycost += costchg;
	qtysust += sustchg;
	if(qtycost < 0) { qtycost = 0; }
	if(qtysust < 0) { qtysust = 0; }
	$('purchase_benchmarking_qty').value = qtycost;
	$('purchase_sustainability_qty').value = qtysust;

	UpdatePurchaseTotal(thirtydays);
}


/////////////////////////////////////////////////////////////////////////
function UpdateRenewalSelections(cb) {

    if(cb.id != undefined) {
		// clear conflicting checkboxes as needed
		buf = '';
		if(cb.id.indexOf('renew_used_expiring_from_unused') >= 0) {
			buf = cb.id.replace('from_unused_', '')
		} else if(cb.id.indexOf('renew_used_expiring_check') >= 0) {
			buf = cb.id.replace('expiring_check', 'expiring_from_unused_check')
		} else if(cb.id.indexOf('renew_used_expired_from_unused') >= 0) {
			buf = cb.id.replace('from_unused_', '')
		} else if(cb.id.indexOf('renew_used_expired_check') >= 0) {
			buf = cb.id.replace('expired_check', 'expired_from_unused_check')
		}
		$(buf).checked = false;
	}

	var unused = parseInt($('costsurveycredits').innerHTML) + parseInt($('sustainabilitysurveycredits').innerHTML);

	if(unused == 0) {
		for(var i = 0; i < document.new_purchase.elements.length; i++) {
			ibuf = document.new_purchase.elements[i];
			if(ibuf.id.indexOf('renew_used_expiring_from_unused_check') >= 0 || ibuf.id.indexOf('renew_used_expired_from_unused_check') >= 0) {
				ibuf.disabled = true;
			}
		}
		if($('purchase_unused_expiring_credits')) {
			$('purchase_unused_expiring_credits').style.color = '#999999';
		}
		if($('purchase_unused_expired_credits')) {
			$('purchase_unused_expired_credits').style.color = '#999999';
		}
	} else {
		if($('instructionsrenewalunusedcredits') && ($('sectionListUsedExpiring') != undefined || $('sectionListUsedExpired') != undefined)) {
			$('instructionsrenewalunusedcredits').style.display = 'inline';
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function UpdatePurchaseTotal(thirtydays) {

	ValidatePurchaseFields();
    PreProcessCouponCode();

	var pastcost = document.getElementById('pastcostcredits').value;
	var pastsust = document.getElementById('pastsustcredits').value;
	if(pastcost == '') { pastcost = 0; }
	if(pastsust == '') { pastsust = 0; }

	var qtycost = parseInt($('purchase_benchmarking_qty').value) + parseInt(pastcost);
	var qtysust = parseInt($('purchase_sustainability_qty').value) + parseInt(pastsust);
	var qtycoan = $('purchase_company_analysis_qty').value;

	ComputePurchaseTotal(false, thirtydays, pastcost, pastsust, qtycost, qtysust, qtycoan);

	DisplayUpSell(parseInt($('purchase_benchmarking_qty').value) + parseInt($('pastcostcreditsdiv').innerHTML), parseInt($('purchase_sustainability_qty').value) + parseInt($('pastsustcreditsdiv').innerHTML), thirtydays);

	document.body.style.cursor = 'wait';
	new Ajax.Updater('', '/purchases/update/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'qtycost=' + encodeURIComponent($('purchase_benchmarking_qty').value) + '&qtysust=' + encodeURIComponent($('purchase_sustainability_qty').value) + '&qtycoan=' + encodeURIComponent($('purchase_company_analysis_qty').value) + '&couponcode=' + encodeURIComponent($('coupon_code').value) });

}


/////////////////////////////////////////////////////////////////////////
function PreProcessCouponCode() {
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

	coupon = $('coupon_code').value;

	if(coupon.search(emailRegEx) >= 0) {
		coupon = "email:" + coupon;
	}

    if(coupon != '') {
		new Ajax.Updater('', '/couponimpressions/new', {asynchronous:false, evalScripts:true, method:'get', parameters:'qtycost=' + encodeURIComponent($('purchase_benchmarking_qty').value) + '&qtysust=' + encodeURIComponent($('purchase_sustainability_qty').value) + '&qtycoan=' + encodeURIComponent($('purchase_company_analysis_qty').value) + '&couponcode=' + encodeURIComponent(coupon) });
	} else {
		$('couponcodeerror').innerHTML = '';
		$('couponcodeerror').style.display = 'none';
	}
}


/////////////////////////////////////////////////////////////////////////
function ClearCouponCode() {

	new Ajax.Updater('', '/couponimpressions/new', {asynchronous:false, evalScripts:true, method:'get', parameters:'mode=clear'});
}


/////////////////////////////////////////////////////////////////////////
function TestPurchaseTotals(thirtydays) {
	var buf = '';

	buf += '<table border=1 cellspacing=0 cellpadding=4>';
	buf += '<tr><td>prev qty cost</td><td>prev qty sust</td><td>qty cost</td><td>qty sust</td><td>total cost</td><td>total sust</td><td>total qty coan</td><td>total discount</td><td>subtotal cost</td><td>prev disc</td><td>refund prior</td><td>total cost</td><td>creditcard cost</td><td>alternative total</td></tr>';

	var setpastcost = 1;
	var setpastsust = 1;
	var setqtycost = 1;
	var setqtysust = 0;
	var setqtycoan = 0;
	var ctr = 0;

	for(setpastcost = 0; setpastcost <= 20; setpastcost++) {
		for(setpastsust = 0; setpastsust <= 20; setpastsust++) {
			for(setqtycost = 0; setqtycost <= 20; setqtycost++) {
				for(setqtysust = 0; setqtysust <= 20; setqtysust++) {
					qtycost = setpastcost + setqtycost;
					qtysust = setpastsust + setqtysust;
					if(ctr % 5 == 0) {
						buf += '<tr><td>' + setpastcost + '</td><td>' + setpastsust + '</td><td>' + setqtycost + '</td><td>' + setqtysust + '</td>' + ComputePurchaseTotal(true, thirtydays, setpastcost, setpastsust, qtycost, qtysust, setqtycoan);
					}
					ctr++;
				}
			}
		}
	}

	buf += '</table>';

	top.consoleRef=window.open('', 'myconsole', 'width=900,height=450,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1')
	top.consoleRef.document.writeln(buf);

}


/////////////////////////////////////////////////////////////////////////
function ComputePurchaseTotal(testmode, thirtydays, pastcost, pastsust, qtycost, qtysust, qtycoan) {

	var costrangelow = parseInt(pastcost);
	var costrangehigh = parseInt(pastcost) + parseInt(qtycost);
	var totalcost = ComputeCostSurveyPurchasePrice(parseInt(costrangelow) - parseInt(pastcost) + 1, parseInt(costrangehigh) - parseInt(pastcost) + 1, parseInt(pastsust));
    var costrefund = ComputeCostSurveyPurchasePrice(1, parseInt(pastcost) + 1, parseInt(pastsust));

	var sustrangelow = parseInt(pastsust);
	var sustrangehigh = parseInt(pastsust) + parseInt(qtysust);
	var totalsust = ComputeSustainSurveyPurchasePrice(parseInt(sustrangelow) - parseInt(pastsust) + 1, parseInt(sustrangehigh) - parseInt(pastsust) + 1, pastcost);
    var sustrefund = ComputeSustainSurveyPurchasePrice(1, parseInt(pastsust) + 1, pastcost);

	// set special comparison report
	var totalqtycoan = 0;
	if(parseInt(qtycost) >= 20 || parseInt(qtysust) >= 20) {
		if($('pastcoan').value != '1') {
			$('purchase_company_analysis_qty').value = '1';
		}
		totalqtycoan = 0;
	} else if(qtycoan == '1') { 
		totalqtycoan = 500;
		alert('Ordering twenty Cost or Sustainability survey credits within a thirty-day period entitles you to the Special Comparison Report for free.  If ordering fewer surveys, the cost is 500 USD.  Please update your Special Comparison Report quantity as needed.');
	} else if(qtycoan == '0') { 
		totalqtycoan = 0;
	}

    // compute previons combined purchase discount
	var prevdisc = 0
	var pastcomblow = 0;
	var pastcombhigh = parseInt(pastcost);
	if(parseInt(pastsust) < parseInt(pastcost)) {
		pastcombhigh = parseInt(pastsust);
	}
// alert('[prev] lo is ' + pastcomblow + ', hi is ' + pastcombhigh);
	prevdisc = ComputeSurveyDiscount(parseInt(pastcomblow), parseInt(pastcombhigh));

	// compute current combined purchase discount
	var totaldisc = 0;
    var comblow = costrangelow
	if(parseInt(sustrangelow) < parseInt(costrangelow)) { 
		comblow = sustrangelow; 
	}
	comblow = parseInt(comblow) + parseInt(pastcomblow);

    var combhigh = parseInt(qtycost);
	if(parseInt(qtysust) < parseInt(qtycost)) {
		combhigh = parseInt(qtysust);
	}
	combhigh = parseInt(combhigh) + parseInt(pastcomblow);

// alert('[cur] lo is ' + comblow + ', hi is ' + combhigh);
	if(combhigh > 0) {
		totaldisc = ComputeSurveyDiscount(parseInt(comblow), parseInt(combhigh));
	}

	totaldisc += parseInt(prevdisc);

	var subtcost = parseInt(totalcost) + parseInt(totalsust) + parseInt(totalqtycoan) - parseInt(totaldisc);

	var refundprior = parseInt(costrefund) + parseInt(sustrefund);

	var tcost = parseInt(subtcost) - parseInt(refundprior) + parseInt(prevdisc);

	var alternativetotal = ComputeCostWithoutHistory(qtycost - pastcost, qtysust - pastsust);

	// Correct negative amounts
	if(parseInt(tcost) < 0) {
		tcost = 0;
	}

	if(testmode == false) {
		DisplayPurchaseTotals(totalcost, totalsust, totalqtycoan, totaldisc, subtcost, prevdisc, refundprior, tcost, alternativetotal);
		DisplayUpSell(qtycost, qtysust, thirtydays);
	} else {
		return PrintPurchaseTotals(totalcost, totalsust, totalqtycoan, totaldisc, subtcost, prevdisc, refundprior, tcost, alternativetotal);
	}

}


/////////////////////////////////////////////////////////////////////////
function DisplayPurchaseTotals(totalcost, totalsust, totalqtycoan, totaldisc, subtcost, prevdisc, refundprior, tcost, alternativetotal) {

	$('subtotalcostsurvey').innerHTML = "$" + totalcost;
	$('subtotalsustsurvey').innerHTML = "$" + FormatDollarCost(totalsust);
	$('subtotalcompanyanalysis').innerHTML = "$" + FormatDollarCost(totalqtycoan);

	$('combineddiscount').innerHTML = "($" + FormatDollarCost(totaldisc) + ")";

	// $('subtotal').innerHTML = "$" + FormatDollarCost(subtcost);
	$('subtotal').innerHTML = "$" + FormatDollarCost(subtcost + totaldisc);

	$('prevdisc').innerHTML = "($" + FormatDollarCost(prevdisc) + ')';
	$('refundprior').innerHTML = "($" + FormatDollarCost(refundprior - prevdisc) + ')';
	// $('totalpurchase').innerHTML = "$" + FormatDollarCost(tcost);
	$('purchase_amount').innerHTML = "$" + FormatDollarCost(tcost);
	$('ssl_amount').value = tcost;
	// $('alternativetotal').innerHTML = "$" + FormatDollarCost(alternativetotal);
	if(tcost > 0) {
		ShowHidePurchaseFieldsRequired('show');
	} else {
		ShowHidePurchaseFieldsRequired('hide');
	}
}


/////////////////////////////////////////////////////////////////////////
function ShowHidePurchaseFieldsRequired(mode) {

	if(mode == "hide") {
		$('req_card_type').style.display = 'none';
		$('req_card_number').style.display = 'none';
		$('req_card_cvv').style.display = 'none';
		$('req_card_name').style.display = 'none';
		$('req_card_exp_date').style.display = 'none';
		$('req_card_address').style.display = 'none';
		$('req_card_email').style.display = 'none';

		if($('purchase_amount').innerHTML.indexOf('credit card') < 0) {
			$('purchase_amount').innerHTML = $('purchase_amount').innerHTML + ' <span style=color:red;>(your credit card info is not needed if amount is zero)</span>'
		}
	} else {
		$('req_card_type').style.display = '';
		$('req_card_number').style.display = '';
		$('req_card_cvv').style.display = '';
		$('req_card_name').style.display = '';
		$('req_card_exp_date').style.display = '';
		$('req_card_address').style.display = '';
		$('req_card_email').style.display = '';
	}
}


/////////////////////////////////////////////////////////////////////////
function PrintPurchaseTotals(totalcost, totalsust, totalqtycoan, totaldisc, subtcost, prevdisc, refundprior, tcost, alternativetotal) {
	var buf = '';

	buf += '<td>$' + totalcost + '</td>';
	buf += '<td>$' + FormatDollarCost(totalsust) + '</td>';
	buf += '<td>$' + FormatDollarCost(totalqtycoan) + '</td>';
	buf += '<td>($' + FormatDollarCost(totaldisc) + ')</td>';
	buf += '<td>$' + FormatDollarCost(subtcost) + '</td>';
	buf += '<td>($' + FormatDollarCost(prevdisc) + ')</td>';
	buf += '<td>$' + FormatDollarCost(refundprior) + '</td>';
	buf += '<td>$' + FormatDollarCost(tcost) + '</td>';
	if(parseInt(tcost) == 0) {
		buf += '<td style="background:#FFFF00">' + tcost + '</td>';

	} else if(parseInt(tcost) < 0) {
		buf += '<td style="background:#FF0000">' + tcost + '</td>';

	} else if(parseInt(alternativetotal) < parseInt(tcost)) {
		buf += '<td style="background:#FF0000">' + tcost + '</td>';

	} else if(parseInt(alternativetotal) == parseInt(tcost)) {
		buf += '<td style="background:#00FF00">' + tcost + '</td>';

	} else {
		buf += '<td>' + tcost + '</td>';
	}
	buf += '<td>$' + FormatDollarCost(alternativetotal) + '</td></tr>';

	return buf;
}


/////////////////////////////////////////////////////////////////////////
function ComputeCostWithoutHistory(qtycost, qtysust) {

	qtycost = parseInt(qtycost)
	qtysust = parseInt(qtysust)

	var totalcost = ComputeCostSurveyPurchasePrice(1, qtycost + 1, 0);
	var totalsust = ComputeSustainSurveyPurchasePrice(1, qtysust + 1, 0);

	var totaldisc = 0;

    var combhigh = parseInt(qtycost);
	if(qtysust < qtycost) {
		combhigh = parseInt(qtysust);
	}

	if(combhigh > 0) {
		totaldisc = ComputeSurveyDiscount(0, combhigh);
	}

	subtcost = parseInt(totalcost) + parseInt(totalsust) - parseInt(totaldisc);

	return subtcost;
}


/////////////////////////////////////////////////////////////////////////
function FormatDollarCost(amount) {

	var buf = new String(amount);
	if(buf.indexOf(".") > 0) {
		// alert('. is at ' + buf.indexOf(".") + ', len is ' + buf.length);
		if( buf.indexOf(".") + 3 > buf.length ) {
			// alert('adding 0 to ' + buf);
			buf += '0';
		}
	} else {
		buf += '.00';
	}
	return buf;
}


/////////////////////////////////////////////////////////////////////////
function FormatNumber(val) {
	val += '';
	x = val.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/////////////////////////////////////////////////////////////////////////
function ComputeCostSurveyPurchasePrice(lo, hi, prevsust) {
	var baseprice = 275;
	var total = 0;
	var i = 0;

// alert('lo is ' + lo + ', hi is ' + hi);
	if(hi > 10) {
		total = (hi - lo) * 210;

	} else {
		for(i = lo; i < hi; i++) {
			if (i == 1) {
				baseprice = 275;
			} else if(i == 2) {
				baseprice = 250;
			} else if(i >= 3 && i <= 10) {
				baseprice = 225;
			} else {
				baseprice = 210;
			}
			total += baseprice
		}
	}

	return total + '.00';
}


/////////////////////////////////////////////////////////////////////////
function ComputeSustainSurveyPurchasePrice(lo, hi, prevcost) {
	var baseprice = 175;
	var total = 0;
	var i = 0;

	if(hi > 10) {
		total = (hi - lo) * 135;
    // } else if (hi == 10) {
	//	total = (hi - lo) * 138.5;
	} else {
		for(i = lo; i < hi; i++) {
			if (i == 1) {
				baseprice = 175;
			} else if(i == 2) {
				baseprice = 160;
			} else if(i >= 3 && i <= 10) {
				baseprice = 150;
			} else {
				// baseprice = 138.5;
				baseprice = 135;
			}
			total += baseprice
		}
	}

  	return total;
}


/////////////////////////////////////////////////////////////////////////
function ComputeSurveyDiscount(lo, hi) {
	var baseprice = 75;
	var total = 0;
	var i = 0;

	if(hi > 10) {
		total = (hi - lo) * 60;

	} else if((hi - lo) == 10) {
		total = (hi - lo) * 45;

	} else {
		for(i = lo; i < hi; i++) {
			if (i == 0) {
				baseprice = 75;
			} else if(i == 1) {
				baseprice = 60;
			} else if(i > 1 && i < 10) {
				baseprice = 50;
			} else {
				baseprice = 48.5;
			}
			total += baseprice
		}
	}

	return total;
}


/////////////////////////////////////////////////////////////////////////
function DisplayUpSell(nocost, nosust, thirtydays) {
	var msg;

	if(parseInt(nocost) + parseInt(nosust) == 0) {
		return;
	}

	msg = '<div style="margin:8px;margin-top:12px;margin-bottom:12px;border:3px double #AAAAAA;background:#EEEEEE;padding:16px;">';
	msg += '<span style="font-weight:bold;color:#666666;">';
	msg += 'Special Offer: Add to your purchase by ' + FormatDate(thirtydays) + ' and receive bulk pricing discounts:</span><br/><br/>'
    msg += '<span style="color:#666666;">';
	msg += DisplayCostUpSell(nocost);
	msg += DisplaySustUpSell(nosust);
	msg += DisplayCombinedUpSell(nocost, nosust);
	msg += '</span></div>';
		
	$('aftersale').innerHTML = msg;
}


/////////////////////////////////////////////////////////////////////////
function DisplayCostUpSell(nocost) {
	var msg = '';

	if(nocost >= 9) {
		msg += 'Additional Cost Surveys: $210/ea.<br>'

	} else if(nocost == 8) {
		msg += 'One additional Cost Survey: $225<br>'
		msg += 'Additional Cost Surveys: $215/ea.<br>'

	} else if(nocost >= 2) {
		msg += 'Additional Cost Surveys, 1-';
		msg += 9 - parseInt(nocost);
		msg += ': $225/ea.<br>'

		msg += 'Additional Cost Surveys, ';
		msg +=  9 - parseInt(nocost);
		msg += ' or more: $210/ea.<br>'

	} else if(nocost == 1) {
		msg += 'One additional Cost Survey: $250<br>'
		msg += 'Additional Cost Surveys, 2-8: $225/ea.<br>'
		msg += 'Additional Cost Surveys, 9 or more: $210/ea.<br>'
	}

	if(msg != '') {
		msg = '<u>Cost Surveys:</u><br/>' + msg + '<br/>';
	}
	return msg;
}


/////////////////////////////////////////////////////////////////////////
function DisplaySustUpSell(nosust) {
	var msg = '';

	if(nosust >= 9) {
		msg += 'Additional Sustainability Surveys: $135/ea.<br>'

	} else if(nosust == 8) {
		msg += 'One additional Sustainability Survey: $150<br>'
		msg += 'Additional Sustainability Surveys: $135/ea.<br>'

	} else if(nosust >= 2) {
		msg += 'Additional Sustainability Surveys, 1-';
		msg += 9 - parseInt(nosust);
		msg += ': $150/ea.<br>'

		msg += 'Additional Sustainability Surveys, ';
		msg +=  9 - parseInt(nosust);
		msg += ' or more: $135/ea.<br>'

	} else if(nosust == 1) {
		msg += 'One additional Sustainability Survey: $160<br>'
		msg += 'Additional Sustainability Surveys, 2-8: $150/ea.<br>'
		msg += 'Additional Sustainability Surveys, 9 or more: $135/ea.<br>'
	}

	if(msg != '') {
		msg = '<u>Sustainability Surveys:</u><br/>' + msg + '<br/>';
	}
	return msg;
}


/////////////////////////////////////////////////////////////////////////
function DisplayCombinedUpSell(nocost, nosust) {
	var msg = '';

	var comb = nocost;
	if(parseInt(nosust) < parseInt(nocost)) {
		comb = nosust;
	}

	if(comb >= 9) {
		msg += 'Additional Combined Surveys: $285/ea.<br>'

	} else if(comb == 8) {
		msg += 'One additional Combined Survey: $325<br>'
		msg += 'Additional Combined Surveys: $285/ea.<br>'

	} else if(comb >= 2) {
		msg += 'Additional Combined Surveys, 1-';
		msg += 9 - parseInt(comb);
		msg += ': $325/ea.<br>'

		msg += 'Additional Combined Surveys, ';
		msg +=  9 - parseInt(comb);
		msg += ' or more: $285/ea.<br>'

	} else if(comb == 1) {
		msg += 'One additional Combined Survey: $350<br>'
		msg += 'Additional Combined Surveys, 2-8: $325/ea.<br>'
		msg += 'Additional Combined Surveys, 9 or more: $285/ea.<br>'
	}

	if(msg != '') {
		msg = '<u>Cost + Sustainability Surveys Combined (Ordered Together):</u><br/>' + msg + '<br/>';
	}
	return msg;
}

/////////////////////////////////////////////////////////////////////////
function FormatDate(indate) {

	return indate.substring(5, 7) + '/' + indate.substring(8, 10) + '/' + indate.substring(0, 4);

}


/////////////////////////////////////////////////////////////////////////
function BeginBuildingSurvey() {

    document.getElementById('errors_for_buildingsurvey').style.display = 'none';
    document.getElementById('errors_for_buildingsurvey').innerHTML = '';

	if(document.getElementById('buildingsurvey_survey_id').selectedIndex > 0 && document.getElementById('buildingsurvey_building_id').selectedIndex > 0) {
		document.getElementById('buildingsurvey_submit').disabled = false;
	} else {
		document.getElementById('buildingsurvey_submit').disabled = true;
	}
}


/////////////////////////////////////////////////////////////////////////
function ShowCVVHelp() {
	var helpwin = window.open('/images/cv_card.jpg', 'CVV_Help', 'width=569,height=223,resizable=no,scrollbars=no,toolbar=no,directories=no,menubar=no,copyhistory=no,location=no,status=no');

}


/////////////////////////////////////////////////////////////////////////
function SwitchToPurchasing(coid, auth) {

	new Ajax.Updater('surveypanel', '/purchases/new/' + coid, {asynchronous:true, evalScripts:true, method:'get', onComplete:function(request){resetTabs('tab_Purchase')}, parameters:'authenticity_token=' + encodeURIComponent(auth)});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToBuildings(auth) {

	new Ajax.Updater('surveypanel', '/companybuildings', {asynchronous:true, evalScripts:true, method:'get', onComplete:function(request){resetTabs('tab_YourCompany')}, parameters:'authenticity_token=' + encodeURIComponent(auth)});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToSurveys(coid, auth) {

	new Ajax.Updater('surveypanel', '/buildingsurveys/index/' + coid, {asynchronous:true, evalScripts:true, method:'get', onComplete:function(request){resetTabs('tab_BuildingSurveys')}, parameters:'authenticity_token=' + encodeURIComponent(auth)});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToNewUserForm(auth) {

	new Ajax.Updater('surveypanel', '/companies/newuser/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth)});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToNewUserRegistrationForm(auth) {

	new Ajax.Updater('surveypanel', '/companies/newregistrationuser/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth)});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToCompanyIndex(auth) {

	new Ajax.Updater('surveypanel', '/companies/index/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth)});

}


/////////////////////////////////////////////////////////////////////////
function SwitchToCompany(auth, params) {
	var id = '0';
	var pos = 0;
	if(params.indexOf('&id=') > 0) { 
		pos = params.indexOf('&id=') + 4;
	} else if(params.indexOf('id=') == 0) {
		pos = 3;
	}

	if(pos > 0) {
		id = '';
		while(pos <= params.length && (!isNaN(params.charAt(pos))) && params.charAt(pos) != '') {
			id += params.charAt(pos);
			pos += 1;
		}
	}

	new Ajax.Updater('surveypanel', '/companies/edit/' + id, {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&' + params});
}


/////////////////////////////////////////////////////////////////////////
function SwitchToTerms(auth, params) {

	new Ajax.Updater('surveypanel', '/accounts/terms/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&' + params});
}


/////////////////////////////////////////////////////////////////////////
function TransferCreditsToClient(auth) {
	var params = 'cost=' + $('transfercost').value;
	params += '&sustainability=' + $('transfersust').value;
    params += '&client=' + $('selectedtransferclientid').innerHTML;
	params += '&direction=toclient';

	new Ajax.Updater('', '/credit_transfers/create/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&' + params});

}


/////////////////////////////////////////////////////////////////////////
function TransferCreditsFromClient(auth) {
	var params = 'cost=' + $('transfercost').value;
	params += '&sustainability=' + $('transfersust').value;
    params += '&client=' + $('selectedtransferclientid').innerHTML;
	params += '&direction=fromclient';

	new Ajax.Updater('', '/credit_transfers/create/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&' + params});

}


/////////////////////////////////////////////////////////////////////////
function ClearUserFields() {
	$('user_first_name').value = '';
	$('user_last_name').value = '';
	$('user_title').value = '';
	$('user_email').value = '';
	$('user_password').value = '';
	$('user_password_confirmation').value = '';

	if($('user_privilege_sa_admin')) {
		$('user_privilege_sa_admin').checked = false;
	}

	if($('user_privilege_co_admin')) {
		$('user_privilege_co_admin').checked = false;
	}

	if($('user_privilege_co_survey')) {
		$('user_privilege_co_survey').checked = false;
	}

	if($('user_privilege_co_report')) {
		$('user_privilege_co_report').checked = false;
	}

	if($('user_privilege_subsidiaries_ro')) {
		$('user_privilege_subsidiaries_ro').checked = false;
	}

	if($('user_privilege_subsidiaries_edit')) {
		$('user_privilege_subsidiaries_edit').checked = false;
	}
}


/////////////////////////////////////////////////////////////////////////
function UserAdminChecked(cb) {

	if(cb.checked == true) {
		$('user_privilege_co_survey').checked = true;
		$('user_privilege_co_report').checked = true;
		$('user_privilege_subsidiaries_ro').checked = true;
		$('user_privilege_subsidiaries_edit').checked = true;
	}
}


/////////////////////////////////////////////////////////////////////////
function SustainabilityNewCertPlan(cb) {
	if(cb.checked == true) {
		document.getElementById('newcertifications').style.display = 'none';
	} else {
		document.getElementById('newcertifications').style.display = 'inline';
	}
}


/////////////////////////////////////////////////////////////////////////
function SustainabilityNoCertPlan(cb) {
	if(cb.checked == true) {
		document.getElementById('newcerttimeframe').style.display = 'none';
	} else {
		document.getElementById('newcerttimeframe').style.display = 'inline';
	}
}


/////////////////////////////////////////////////////////////////////////
function SustainabilitySumESPFields() {

	var tot = 0;

	var bufval = parseInt(document.getElementById('sustainability_Target_operational_changes_through_users').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Target_operational_changes_new_devices').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Target_minor_repairs').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Target_major_capital_retrofits').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Target_other').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	document.getElementById('ESPTotal').value = tot;
}


/////////////////////////////////////////////////////////////////////////
function SustainabilitySumRecyclingFields() {

	var tot = 0;

	var bufval = parseInt(document.getElementById('sustainability_Recycling_target_recycling_containers').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Recycling_target_behavior_changes').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Recycling_target_incoming_waste').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Recycling_target_incoming_materials').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Recycling_target_recycle_electronic_components').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	document.getElementById('RecyclingTotal').value = tot;
}


/////////////////////////////////////////////////////////////////////////
function SustainabilitySumWaterFields() {

	var tot = 0;

	var bufval = parseInt(document.getElementById('sustainability_Water_target_fixture').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Water_target_plant').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Water_target_landscaping').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Water_target_behavior_changes').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	bufval = parseInt(document.getElementById('sustainability_Water_target_other').value);
	if(parseInt(bufval)) { tot += parseInt(bufval); }

	document.getElementById('WaterTotal').value = tot;
}


/////////////////////////////////////////////////////////////////////////
function SustainabilityInitiativeChange(cb) {
	var buf;

	if(cb.id.indexOf('_to_implement') > 0) {
		buf = cb.id
		buf = buf.replace(/_to_implement/, '_implemented');
		$(buf).checked = false;

	} else {
		buf = cb.id
		buf = buf.replace(/_implemented/, '_to_implement');
		$(buf).checked = false;
	}

}


/////////////////////////////////////////////////////////////////////////
function SustainabilityCountTopFour(cb) {

	var tot = 0;
	tot += $('sustainability_Top_item_user_occupant_behavior_changes').checked;
	tot += $('sustainability_Top_item_building_commissioning').checked;
	tot += $('sustainability_Top_item_energy_efficient_lighting').checked;
	tot += $('sustainability_Top_item_reduce_lighting_levels').checked;
	tot += $('sustainability_Top_item_lighting_motion_sensors').checked;
	tot += $('sustainability_Top_item_lighting_timing_management_systems').checked;
	tot += $('sustainability_Top_item_energy_efficient_equipment_upgrades').checked;
	tot += $('sustainability_Top_item_CO2_monitoring_for_outside_air_makeup_controls').checked;
	tot += $('sustainability_Top_item_install_VFDs_on_motors').checked;
	tot += $('sustainability_Top_item_reflective_white_roofing').checked;
	tot += $('sustainability_Top_item_additional_insulation').checked;
	tot += $('sustainability_Top_item_upgrade_to_high_performance_glazing').checked;
	tot += $('sustainability_Top_item_adjust_temperatures').checked;
	tot += $('sustainability_Top_item_install_flat_screen_monitors').checked;
	tot += $('sustainability_Top_item_PCs_in_sleep_mode_when_not_used').checked;
	tot += $('sustainability_Top_item_custodians_clean_during_working_hours').checked;
	tot += $('sustainability_Top_item_other_planned_initiative').checked;

	if(tot > 4) {
		alert("Please select no more than four items.");
		cb.checked = false;
	}

	// check checkbox to left if needed
	buf = cb.id + '_to_implement';
	buf = buf.substring(0, 78);
	if(cb.checked && $(buf)) {
		$(buf).checked = true;
	}

}


/////////////////////////////////////////////////////////////////////////
function ShowDetailedHelpPopup(file) {

	helpwin = window.open('/help/' + file, 'Help', 'width=525,height=450,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1')
	helpwin.focus();

}


/////////////////////////////////////////////////////////////////////////
function AnalysisSelectReportType() {
	if($('analyze_id').options[$('analyze_id').selectedIndex].value == 2) {
		$('select_buildings_benchmarking').style.display = 'none';
		$('select_reports_benchmarking').style.display = 'none';
		$('select_buildings_sustainability').style.display = 'inline';
		$('select_reports_sustainability').style.display = 'inline';

		AlterCostFilters('none');
		AlterSustainabilityFilters('collapse');

	} else {
		$('select_buildings_benchmarking').style.display = 'inline';
		$('select_reports_benchmarking').style.display = 'inline';
		$('select_buildings_sustainability').style.display = 'none';
		$('select_reports_sustainability').style.display = 'none';

		AlterSustainabilityFilters('none');
		AlterCostFilters('collapse');
		// AlterAnalyzeSection('demographics_basic', 'expand');
	}
	$('filtertoggle').innerHTML = '(expand all)';
}


/////////////////////////////////////////////////////////////////////////
function AnalysisShowHideReportFormat() {
	var name = $('analyze[benchmarking_survey_name]').options[$('analyze[benchmarking_survey_name]').selectedIndex].value;

	if(name.indexOf('Tabular') >= 0) {
		$('ReportFormatRow').style.display = '';
	} else {
		$('ReportFormatRow').style.display = 'none';
	}

}


/////////////////////////////////////////////////////////////////////////
function AnalysisSetAreaSelect(units) {
    if(units == 'Square Feet') {
        document.getElementById('unitsareasquarefeet').style.display = '';
        document.getElementById('unitsareasquaremeters').style.display = 'none';
//        document.getElementById('units_units_area').selectedIndex = 0;
    } else {
        document.getElementById('unitsareasquarefeet').style.display = 'none';
        document.getElementById('unitsareasquaremeters').style.display = '';
//        document.getElementById('units_units_area').selectedIndex = 1;
    }
}


/////////////////////////////////////////////////////////////////////////
function AnalysisSetFiscalEndYear(source) {

    var analidx = $('analyze_id').selectedIndex;
    var analsel = $('analyze_id').options[analidx].text;
	var bldgidx;
	var bldgsel;

	// var altyear = $('analyze[alt_fiscal_year]').checked;

	if(analsel == 'Cost') {
    	bldgidx = $('analyze_benchmarking_buildingsurvey_id').selectedIndex;
	    bldgsel = $('analyze_benchmarking_buildingsurvey_id').options[bldgidx].text;
	} else {
    	bldgidx = $('analyze_sustainability_buildingsurvey_id').selectedIndex;
	    bldgsel = $('analyze_sustainability_buildingsurvey_id').options[bldgidx].text;
	}

	var len = bldgsel.length
	var yrshort = bldgsel.substring(len - 3, len - 1);
	var newyear = parseInt('20' + yrshort);

	var selidx = $('analyze_fiscal_year_1i').selectedIndex;
	var selyear = $('analyze_fiscal_year_1i').options[selidx].value;
	var newselidx = selidx + parseInt(newyear) - parseInt(selyear);

	if(selyear == newyear && source == 'year') {
		$('alt_fiscal_year_message').style.display = 'none';
	} else {
		$('alt_fiscal_year_message').style.display = '';
	}
}


/////////////////////////////////////////////////////////////////////////
function AnalysisSetPrimaryUse(name, val) {
	if(val == '-1') {
		$('yourprimaryuse').innerHTML = "All Others";
	} else {
		$('yourprimaryuse').innerHTML = name;
	}
}


/////////////////////////////////////////////////////////////////////////
function AnalysisSetPreventativeMaintenance(lessthan40, bet40and64, bet64and85) {
	if(bet64and85 == 'yes') {
		$('yourmaintenancepmwork').innerHTML = '65 - 85%';
	} else if(bet40and64 == 'yes') {
		$('yourmaintenancepmwork').innerHTML = '40 - 64%';
	} else if(lessthan40 == 'yes') {
		$('yourmaintenancepmwork').innerHTML = 'Less than 40%';
	}
}


/////////////////////////////////////////////////////////////////////////
function AnalysisSetYourBuilding(divname, value) {
    if($(divname) != undefined) {
		$(divname).innerHTML = value;
	}
}


/////////////////////////////////////////////////////////////////////////
function AnalysisSubmit(auth) {

	analyzeWait();
	AnalysisSetFiscalEndYear();

	var format = $('analyze[output_type]').value;
	// alert("format requested: " + format);

	if(format == "Microsoft Excel") {
		document.location = '/analyze/show/0?' + $('analyzeform').serialize() + '&format=xls&authenticity_token=' + encodeURIComponent(auth);

	} else {
		new Ajax.Updater('graphpanel', '/analyze/show/0', {asynchronous:true, evalScripts:true, method:'post', parameters:Form.serialize($('analyzeform')) + '&authenticity_token=' + encodeURIComponent(auth)});
	}
}


/////////////////////////////////////////////////////////////////////////
function DataSubmitExportRequest(auth, bsidcost, bsidsust) {

    saveCurrentPage();
	document.location = '/buildingsurveys/show/0?bsidcost=' + bsidcost + '&bsidsust=' + bsidsust + '&format=csv&authenticity_token=' + encodeURIComponent(auth);
}


/////////////////////////////////////////////////////////////////////////
function BooleanToYesNo(bool) {
	if(bool == 'true') {
		return 'yes';
	} else {
		return 'no';
	}
}


/////////////////////////////////////////////////////////////////////////
function FormatAssociationList(alist) {
	alist = alist.replace(/^\|/g, '');
	alist = alist.replace(/\|$/g, '');
	alist = alist.replace(/\|/g, ', ');
	alist = alist.replace(/_/g, ' ');
	return alist;
}


/////////////////////////////////////////////////////////////////////////
function SustainabilityHelp(fieldname) {
	// $(fieldname).style.display = 'block';
	$(fieldname + '_helpopen').style.display = 'none';
	$(fieldname + '_helpclose').style.display = '';

	$(fieldname).setStyle({opacity:'0.0'});
	$(fieldname).setStyle({display:'block'});
	new Effect.Opacity(fieldname, { duration: 0.75, delay: 0, from:0.0, to :1.0 });
}


/////////////////////////////////////////////////////////////////////////
function SustainabilityHelpClose(fieldname) {
	$(fieldname).style.display = 'none';
	$(fieldname + '_helpopen').style.display = '';
	$(fieldname + '_helpclose').style.display = 'none';
}


/////////////////////////////////////////////////////////////////////////
function LEEDTotal() {
	var tot = 0;
	var field = '';

	for(var i = 0;  i < document.leedform.elements.length; i++) {
		if(document.leedform.elements[i].value == 'yes') {
			if(document.leedform.elements[i].checked == true) {
				field = document.leedform.elements[i].name;
				field = field.replace('leedworksheet[', '');
				field = field.replace(']', '') + '_points';
				if($(field) != null) {
					if(parseInt($(field).value)) {
						tot += parseInt($(field).value);
					}
				}
			}
		} else if(document.leedform.elements[i].value.indexOf('|') >= 0) {
			if(document.leedform.elements[i].name.indexOf('_UC') < 0) {
				tot += parseInt(document.leedform.elements[i].value.split(/\|/)[1]);
			}
		}
	}
	$('leedtotalshow').innerHTML = tot;
	$('leedtotal').value = tot;
}


/////////////////////////////////////////////////////////////////////////
function LEEDTotalUC() {
	var tot = 0;
	var field = '';

	for(var i = 0;  i < document.leedform.elements.length; i++) {
		if(document.leedform.elements[i].value == 'uc' || 
		 document.leedform.elements[i].value == 'yes') {
			if(document.leedform.elements[i].checked == true) {
				field = document.leedform.elements[i].name;
				field = field.replace('leedworksheet[', '');
				field = field.replace(']', '') + '_points';
				if($(field) != null) {
					if(parseInt($(field).value)) {
						tot += parseInt($(field).value);
					}
				}
			}
		} else if(document.leedform.elements[i].value.indexOf('|') >= 0) {
			if(document.leedform.elements[i].name.indexOf('_UC') >= 0) {
				tot += parseInt(document.leedform.elements[i].value.split(/\|/)[1]);
			}
		}
	}
	$('leedtotalshowuc').innerHTML = tot;
	$('leedtotaluc').value = tot;

}


/////////////////////////////////////////////////////////////////////////
function LEEDRequired() {
	var buf = '';

	for (var i = 0; i < gReqItems.length; i++) {
	    var obj = $('leedworksheet_' + gReqItems[i] + '_yes');
		if(obj.checked == false) {
			buf += '&nbsp;-&nbsp;' + gReqLabels[i] + "<br>";
		}
	}

	if(buf != '') {
		buf = buf.replace('<b>', '');
		buf = buf.replace('</b>', '');

		$('leedtotalshow').innerHTML += '<div style=\'color:#FF0000;font-size:11px;line-height:12px;margin-top:4px;\'>To be eligible for certification, you will need to:<br>&nbsp;&nbsp;-&nbsp;Bring your current score up to 40.<br>&nbsp;&nbsp;-&nbsp;Implement the Required items.</div><div style=\'margin-left:10px;margin-top:2px;color:#770000;font-size:11px;line-height:11px;\'>' + buf + '</div>';
	}
}


/////////////////////////////////////////////////////////////////////////
function LEEDDependencies(rb, list) {
	var alist, i;

	if(rb.value == 'yes') {
		alist = list.split(',');
		for(i = 0; i < alist.length; i++) {
			if($('leedworksheet_' + alist[i] + '_yes')) {
				$('leedworksheet_' + alist[i] + '_yes').checked = true;
			}
		}	
	}
}


/////////////////////////////////////////////////////////////////////////
function analyzeWait() {

	ShowWaitPanel();
	$('button_analyze_inform').disabled = 'disabled';
	$('button_analyze_bottom').disabled = 'disabled';
	$('errormsgbottom').innerHTML = 'Processing... Please wait.';
	$('errormsgbottom').style.display = '';
	$('informready').innerHTML = $('informready').innerHTML + '<br><font color=red><b>Processing...<br>Please wait.</b></font>';

}


/////////////////////////////////////////////////////////////////////////
function analyzeReset() {

	$('button_analyze_inform').disabled = '';
	$('button_analyze_bottom').disabled = '';
	$('errormsgbottom').innerHTML = '';
	$('errormsgbottom').style.display = 'none';
	$('informready').innerHTML = '';
}


/////////////////////////////////////////////////////////////////////////
function getSWFImage() {

	var browser = navigator.appName;
	var b_version = navigator.appVersion;
	var version = parseFloat(b_version);

	if(browser.indexOf('Internet Explorer') > 0) {
		$('printcontent').style.display = 'none';
		$('flashcontent').className = 'xxx';
		$('flashcontent').id = 'xxx';

	} else {
		img = "<img src='data:image/png;base64," + document.getElementById('graph').get_img_binary() + "' />";
		$('printcontent').innerHTML = img;
	}

}

/////////////////////////////////////////////////////////////////////////
function UpdateAnalyzeSection(section) {
	
	if($(section + '_symbol').innerHTML.indexOf('down') > 0) {
		// $('analysis_section_' + section).style.display = 'none';
		Effect.Fade('analysis_section_' + section);

		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';

	} else {
		// $('analysis_section_' + section).style.display = '';
		Effect.Appear('analysis_section_' + section);
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.down.12.png" border=0 height=12 width=12>';

		// Change notes on all column headings
		$('demographics_basic_notes').innerHTML = 'hold down the control key to select multiple values';
		$('demographics_specific_notes').innerHTML = 'hold down the control key to select multiple values';
		$('utilities_notes').innerHTML = 'hold down the control key to select multiple values';
		$('maintenance_notes').innerHTML = 'hold down the control key to select multiple values';
		$('custodial_notes').innerHTML = 'hold down the control key to select multiple values';
		$('security_notes').innerHTML = 'hold down the control key to select multiple values';
		$('sustainability_notes').innerHTML = 'hold down the control key to select multiple values';

	}
}

/////////////////////////////////////////////////////////////////////////
function AnalysisClearFilters() {

	var elements = $('analyzeform').elements;
	for(var i = 0; i < elements.length; i++) {
		if(elements[i].name.substring(0, 8) == "analyze[") {
			if(elements[i].name == "analyze[id]" ||
			 elements[i].name == "analyze[benchmarking_buldingsurvey_id]" ||
			 elements[i].name == "analyze[benchmarking_survey_name]" ||
			 elements[i].name == "analyze[sustainability_buildingsurvey_id]" ||
			 elements[i].name == "analyze[sustainability_survey_name]" ||
			 elements[i].name == "analyze[fiscal_year(1i)]") {
				// do nothing
			} else {

				// alert('name: ' + elements[i].name + ', type: ' + elements[i].type + ', val: ' + elements[i].value);
				if(elements[i].type == "select-one") {
					elements[i].selectedIndex = 0;
	
				} else if(elements[i].type == "select-multiple") {
					// alert('multiple length is ' + elements[i].options.length);
					for(var j = 0; j < elements[i].options.length; j++) {
						elements[i].options[j].selected = false;
					}
	
				} else if(elements[i].type == "checkbox") {
					elements[i].checked = false;
				}
			}
		}
	}

}


/////////////////////////////////////////////////////////////////////////
function FilterToggle() {
	if($('filtertoggle').innerHTML == '(expand all)') {
		if($('analyze_id').options[$('analyze_id').selectedIndex].value == '1') {
			AlterCostFilters('expand');
		} else if($('analyze_id').options[$('analyze_id').selectedIndex].value == '2') {
			AlterSustainabilityFilters('expand');
		} else {
			AlterCostFilters('expand');
			AlterSustainabilityFilters('expand');
		}
		$('filtertoggle').innerHTML = '(collapse all)';

	} else {
		if($('analyze_id').options[$('analyze_id').selectedIndex].value == '1') {
			AlterCostFilters('collapse');
		} else if($('analyze_id').options[$('analyze_id').selectedIndex].value == '2') {
			AlterSustainabilityFilters('collapse');
		} else {
			AlterCostFilters('collapse');
			AlterSustainabilityFilters('collapse');
		}
		$('filtertoggle').innerHTML = '(expand all)';
	}
}


/////////////////////////////////////////////////////////////////////////
function AlterCostFilters(display) {
	AlterAnalyzeSection('demographics_basic', display);
	AlterAnalyzeSection('demographics_specific', display);
	AlterAnalyzeSection('utilities', display);
	AlterAnalyzeSection('maintenance', display);
	AlterAnalyzeSection('custodial', display);
	AlterAnalyzeSection('security', display);
}


/////////////////////////////////////////////////////////////////////////
function AlterSustainabilityFilters(display) {
	AlterAnalyzeSection('demographics_basic', display);
	AlterAnalyzeSection('demographics_specific', display);
	AlterAnalyzeSection('sustainability', display);
}


/////////////////////////////////////////////////////////////////////////
function HideSustainabilityFilters() {
	// HideAnalyzeSection('sustainability');
}


/////////////////////////////////////////////////////////////////////////
function ShowAnalyzeSection(section) {
	AlterAnalyzeSection(section, '');
}


/////////////////////////////////////////////////////////////////////////
function HideAnalyzeSection(section) {
	AlterAnalyzeSection(section, 'none');
}


/////////////////////////////////////////////////////////////////////////
function ExpandAnalyzeSection(section) {
	AlterAnalyzeSection(section, 'expand');
}


/////////////////////////////////////////////////////////////////////////
function CloseAnalyzeSection(section) {
	AlterAnalyzeSection(section, 'collapse');
}


/////////////////////////////////////////////////////////////////////////
function AlterAnalyzeSection(section, display) {

	if(display == 'none') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = 'none';
		$('analysis_heading_' + section).style.display = 'none';

	} else if(display == 'collapse') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_heading_' + section).style.display = '';
		$('analysis_section_' + section).style.display = 'none';

	} else if(display == 'expand') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.down.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = '';
		$('analysis_heading_' + section).style.display = '';

	} else {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = 'none';
		$('analysis_heading_' + section).style.display = '';
	}
}

/////////////////////////////////////////////////////////////////////////
function AlterSurveySection(section, display) {

	if(display == 'none') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = 'none';
		$('analysis_heading_' + section).style.display = 'none';

	} else if(display == 'collapse') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_heading_' + section).style.display = '';
		$('analysis_section_' + section).style.display = 'none';

	} else if(display == 'expand') {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.down.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = '';
		$('analysis_heading_' + section).style.display = '';

	} else {
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';
		$('analysis_section_' + section).style.display = 'none';
		$('analysis_heading_' + section).style.display = '';
	}
}

/////////////////////////////////////////////////////////////////////////
function UpdateSurveySection(section) {
	
	if($(section + '_symbol').innerHTML.indexOf('down') > 0) {
		Effect.Fade('survey_section_' + section);
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.right.12.png" border=0 height=12 width=12>';

	} else {
		Effect.Appear('survey_section_' + section);
		$(section + '_symbol').innerHTML = '<img src="/images/pointer.down.12.png" border=0 height=12 width=12>';

	}
}


/////////////////////////////////////////////////////////////////////////
function OpenAllSurveySections() {
	
	document.body.style.cursor = 'wait';
	secs = document.getElementsByTagName("*");

	for (var i = 0; i < secs.length; i++) {
		var element = secs[i];
		if($(element).id.indexOf('survey_section_') >= 0) {
			$(element).style.display = 'inline';
		}
	}

	$('sectioncontrol').innerHTML = '<a  class="surveycolumnheading" style="color:#777777;text-decoration:none;" href="javascript:CloseAllSurveySections();">Close all Sections</a>';
	document.body.style.cursor = 'default';

}


/////////////////////////////////////////////////////////////////////////
function CloseAllSurveySections() {
	
	document.body.style.cursor = 'wait';
	secs = document.getElementsByTagName("*");

	for (var i = 0; i < secs.length; i++) {
		var element = secs[i];
		if($(element).id.indexOf('survey_section_') >= 0) {
			$(element).style.display = 'none';
		}
	}

	$('sectioncontrol').innerHTML = '<a class="surveycolumnheading" style="color:#777777;text-decoration:none;" href="javascript:OpenAllSurveySections();">Expand all Sections</a>';
	document.body.style.cursor = 'default';
}


/////////////////////////////////////////////////////////////////////////
function ie6DataEntryMenu(name, mode) {

	var browser = navigator.appName;
	var b_version = navigator.appVersion;
	var version = parseFloat(b_version);
	// alert('browser is ' + browser + ' version is ' + b_version);

	if(b_version.indexOf('MSIE 6') < 0) {
		return;
	}

	if(mode == 'show') {
		$('menu_' + name).style.display = 'block';
	} else if(mode == 'sustain') {
		clearTimeout(timerPullDown)
	} else {
		timerPullDown = setTimeout("$('menu_" + name + "').style.display = 'none';", 500);
	}

}


/////////////////////////////////////////////////////////////////////////
function ShowAllCompanies(filter, order) {
	var filter = $('selectfilter').options[$('selectfilter').selectedIndex].value;
	document.body.style.cursor = 'wait';
	new Ajax.Updater('surveypanel', '/companies/index/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'selectfilter=' + filter + '&order=' + order});

}


/////////////////////////////////////////////////////////////////////////
function ShowAdminColumns(tbl, colid, colnomin, colnomax) {
	ShowHideTableColumns(tbl, 2, colnomin, colnomax, '');
	$(colid + '_heading').style.display = '';
	$(colid + '_underscore').style.display = '';
	$(colid + '_show').style.display = 'none';
}


/////////////////////////////////////////////////////////////////////////
function HideAdminColumns(tbl, colid, colnomin, colnomax) {
	ShowHideTableColumns(tbl, 2, colnomin, colnomax, 'none');
	$(colid + '_heading').style.display = 'none';
	$(colid + '_underscore').style.display = 'none';
	$(colid + '_show').style.display = '';
}


/////////////////////////////////////////////////////////////////////////
function ShowHideTableColumns(tbl, startrow, colnomin, colnomax, display) {

	for(var i=startrow, limit=tbl.rows.length; i < limit; ++i) {
		for(var j=colnomin, stop=colnomax; j <= stop; ++j) {
			if(typeof(tbl.rows[i].cells[j]) != "undefined") {
				tbl.rows[i].cells[j].style.display = display;
			}
		}
	} 
}


/////////////////////////////////////////////////////////////////////////
function ShowWaitPanel(panelid) {

	if(navigator.appVersion.indexOf('MSIE 6') < 0) {
	    if($(panelid) != undefined) {
			new Effect.Appear($(panelid), { duration: 0.5, delay: 0, from:0.0, to :0.3 });
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function HideWaitPanel(panelid) {

	if(navigator.appVersion.indexOf('MSIE 6') < 0) {
	    if($(panelid) != undefined) {
			new Effect.Fade($(panelid), { duration: 0.5, delay: 0, from:0.3, to :0.0 });
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function SwitchAltBuilding(checkbox, controller, bsid) {

	if(checkbox.checked) {
		LoadAltBuilding(controller, bsid, 'hover');
	} else {
		altbldg = 0;
	}
}


/////////////////////////////////////////////////////////////////////////
function LoadAltBuilding(controller, bsid, mode) {

	new Ajax.Updater('', '/' + controller + '/compare/' + bsid, {asynchronous:false, evalScripts:true, method:'get', parameters:'mode=' + encodeURIComponent(mode)});

}


/////////////////////////////////////////////////////////////////////////
function LoadCouponIndex(auth) {

//	new Ajax.Updater('', '/accounts/redraw/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&redrawtargetcontroller=couponimpressions&redrawtargetaction=index&redrawtargetid=0'});

}


/////////////////////////////////////////////////////////////////////////
function DisplayAltBuilding(jsonalt) {
	altbldg = jsonalt.evalJSON();
	// alert(jsonalt);
}


/////////////////////////////////////////////////////////////////////////
function showAltValue(model, field) {
	var altval = undefined;

	fieldid = field.id.replace(model + '_', '')

	if(fieldid.substring(fieldid.length - 4, fieldid.length) == '_yes') {
		fieldidbase = fieldid.substring(0, fieldid.length - 4)
		altval = eval('altbldg.' + fieldidbase);

	} else if(fieldid.substring(fieldid.length - 3, fieldid.length) == '_no') {
		fieldidbase = fieldid.substring(0, fieldid.length - 3)
		altval = eval('altbldg.' + fieldidbase);

	} else if(fieldid.substring(0, 5) == 'freq_') {
		altval = eval('altbldg.' + fieldid);
		altval = UnconvertFrequency(altval);

	} else if(fieldid.substring(fieldid.length - 1, fieldid.length) == '_') {
		fieldidbase = fieldid.substring(0, fieldid.length - 1)
		altval = eval('altbldg.' + fieldidbase);

	} else {
		altval = eval('altbldg.' + fieldid);
	}

	if(altval != undefined) {
		if(altval == '' || altval == null || altval.length == 0) {
			altval = '(no value)';
		} else if(altval == true) {
			altval = 'yes';
		} else if(altval == false) {
			altval = 'no';
		}
		$('altvalue').style.top = (cursor.y - 50) + 'px';
		$('altvalue').style.left = (cursor.x - 60) + 'px';
		$('altvalue').innerHTML = "last year:<br/>" + altval + "<br/>";
		$('altvalue').style.display = 'block';
		$(field).style.background = '#FFFFDD';
	}
}


/////////////////////////////////////////////////////////////////////////
function showAltAssociationValue(field) {
	var associd = field.id.replace("building_assoc_", "");
	var altval = eval('altbldg.associations');
	var display = 'no';

	if(altval != undefined) {
		if(altval.indexOf('|' + associd + '|') >= 0) {
			display = 'yes';
		}

		$('altvalue').style.top = (cursor.y - 50) + 'px';
		$('altvalue').style.left = (cursor.x - 60) + 'px';
		$('altvalue').innerHTML = "last year:<br/>" + display + "<br/>";
		$('altvalue').style.display = 'block';
		$(field).style.background = '#FFFFDD';
	}
}


/////////////////////////////////////////////////////////////////////////
function showAltSpecifiedValue(model, name, field) {
	var altval = undefined;

	altval = eval('altbldg.' + name);

	if(altval != undefined) {
		if(altval == '' || altval == null || altval.length == 0) {
			altval = '(no value)';
		}
		$('altvalue').style.top = (cursor.y - 50) + 'px';
		$('altvalue').style.left = (cursor.x - 60) + 'px';
		$('altvalue').innerHTML = "last year:<br/>" + altval + "<br/>";
		$('altvalue').style.display = 'block';
		$(field).style.background = '#FFFFDD';
	}
}


/////////////////////////////////////////////////////////////////////////
function hideAltValue(field) {
	if($('altvalue')) {
		$('altvalue').style.display = 'none';
	}
	if($(field)) {
		$(field).style.background = '#FFFFFF';
	}
}


/////////////////////////////////////////////////////////////////////////
function getCursorPosition(e) {
	e = e || window.event;

	if (e.pageX || e.pageY) {
		cursor.x = e.pageX;
		cursor.y = e.pageY;
	} else {
		cursor.x = e.clientX +
		(document.documentElement.scrollLeft ||
		document.body.scrollLeft) -
		document.documentElement.clientLeft;

		cursor.y = e.clientY +
		(document.documentElement.scrollTop ||
		document.body.scrollTop) -
		document.documentElement.clientTop;
	}

}


/////////////////////////////////////////////////////////////////////////
function populateFieldsWithAlt(jsonalt, model) {
	var theform = document.forms[0];
	var i;
	altbldg = jsonalt.evalJSON();

	for(i = 0; i < theform.elements.length; i++) {
		if(theform.elements[i] != undefined) {

			fieldid = theform.elements[i].id.replace(model + '_', '');

			if(fieldid != undefined && fieldid != '') {

				if(fieldid.substring(fieldid.length - 3, fieldid.length) == '_no' || fieldid.substring(fieldid.length - 4, fieldid.length) == '_yes') {
					populateYesNoFieldWithAlt(model, fieldid);

				} else if(fieldid.substring(0, 6) == 'assoc_') {
					populateAssociationFieldWithAlt(fieldid);

				} else {
					altval = eval('altbldg.' + fieldid);

					if(altval != undefined) {
						if(theform.elements[i].value != undefined) {
							theform.elements[i].value = altval;
						}
					}
				}
			}
		}
	}

	if(model == 'building') {
		demographicsFieldChange('D11', '');
		demographicsFieldChange('D22', '');
	}
	altbldg = 0
}


/////////////////////////////////////////////////////////////////////////
function populateYesNoFieldWithAlt(model, fieldid) {
	var fieldidbase

	if (fieldid.substring(fieldid.length - 4, fieldid.length) == '_yes') {
		fieldidbase = fieldid.substring(0, fieldid.length - 4)
		// alert('fieldidbase is ' + fieldidbase);

		altval = eval('altbldg.' + fieldidbase);

		if(altval != undefined) {
			if(altval == 'yes') {
				$(model + '_' + fieldidbase + '_yes').checked = true;
			} else if(altval == 'no') {
				$(model + '_' + fieldidbase + '_no').checked = true;
			}
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function populateAssociationFieldWithAlt(fieldid) {

	var fieldidbase = fieldid.replace('assoc_', '');
	altval = eval('altbldg.associations');

	if(altval.indexOf('|' + fieldidbase + '|') >= 0) {
		$('building_assoc_' + fieldidbase).checked = true;
	} else {
		$('building_assoc_' + fieldidbase).checked = false;
	}
}


/////////////////////////////////////////////////////////////////////////
function showQuickStart() {
	$('quickstartlegend').style.display = 'block';
	$('comparisonmenu').style.display = 'none';
}


/////////////////////////////////////////////////////////////////////////
function showComparisonMenu() {
	$('quickstartlegend').style.display = 'none';
	$('comparisonmenu').style.display = 'block';
}


/////////////////////////////////////////////////////////////////////////
function LoadHoverOverRenewalContent(companyid, timeframe, used, expiring) {
	new Ajax.Updater('', '/accounts/showexpiring/0', {asynchronous:false, evalScripts:true, method:'get', parameters:'used=' + encodeURIComponent(used) + '&expiring=' + encodeURIComponent(expiring) + '&timeframe=' + encodeURIComponent(timeframe) + '&companyid=' + encodeURIComponent(companyid)});
}


/////////////////////////////////////////////////////////////////////////
function showHoverOverContent(elementid, content) {

	if(content != undefined) {
		if(content == '' || content == null || content.length == 0) {
			return;
		}
		$(elementid).style.top = (cursor.y - 50) + 'px';
		$(elementid).style.left = (cursor.x - 60) + 'px';
		$(elementid).innerHTML = content;
		$(elementid).style.display = 'block';
		$(elementid).style.background = '#FFFFDD';
	}
}


/////////////////////////////////////////////////////////////////////////
function hideRenewalHoverOverContent() {
	$('renewalhover').style.display = 'none';
}


/////////////////////////////////////////////////////////////////////////
function hideShowAssociationDes(cb) {
	var id = cb.id;
	var assoc = id.replace("building_assoc_", "");
	
	if(cb.checked == true) {
		if($('assocdesignation_' + assoc)) {
			$('assocdesignation_' + assoc).style.display = 'block';
		}

	} else {
		if($('assocdesignation_' + assoc)) {
			$('assocdesignation_' + assoc).style.display = 'none';
		}
	}
}


/////////////////////////////////////////////////////////////////////////
function UnconvertFrequency(num) {

   if(num == '') { num = -1; }
   var conv = ''

	if(num == 0) {
		conv = 'Function Not Used On Site';
	} else if (num == 0.0001) {
		conv = 'Data Unavailable';
	} else if (num == 4) {
		conv = '4 times per day';
	} else if (num == 3) {
		conv = '3 times per day';
	} else if (num == 2) {
		conv = '2 times per day';
	} else if (num == 1) {
		conv = '7 times / week';
	} else if (num == 0.86) {
		conv = '6 times / week';
	} else if (num == 0.71) {
		conv = '5 times / week';
	} else if (num == 0.57) {
		conv = '4 times / week';
	} else if (num == 0.43) {
		conv = '3 times / week';
	} else if (num == 0.29) {
		conv = '2 times / week';
	} else if (num == 0.14) {
		conv = '1 time / week';
	} else if (num == 0.5) {
		conv = 'Every other day';
	} else if (num == 0.07) {
		conv = 'Every other week';
	} else if (num == 0.03001) {
		conv = 'Monthly';
	} else if (num == 0.01005) {
		conv = '4 times / year';
	} else if (num == 0.01004) {
		conv = '3 times / year';
	} else if (num == 0.01003) {
		conv = '2 times / year';
	} else if (num == 0.01002) {
		conv = '1 time / year';
	} else if (num == 0.03) {
		conv = 'As Required';
	} else if (num == 0.0002) {
		conv = 'Never Cleaned';
	}

	return conv;
}


/////////////////////////////////////////////////////////////////////////
function CancelEMail(companyid, mailtype, auth) {

	if(confirm('Cancel this eMail notice?') == true) {
	
		new Ajax.Updater('', '/emaillogs/cancel/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&company_id=' + companyid + '&mailtype=' + mailtype});
	}
}


/////////////////////////////////////////////////////////////////////////
function SendEMail(companyid, mailtype, auth) {

	if(confirm('Send this eMail now?') == true) {
	
		new Ajax.Updater('', '/emaillogs/create/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'authenticity_token=' + encodeURIComponent(auth) + '&company_id=' + companyid + '&mailtype=' + mailtype});
	}
}


/////////////////////////////////////////////////////////////////////////
function ShowReorderScreen() {

	new Ajax.Updater('surveypanel', '/purchases/new/0', {asynchronous:true, evalScripts:true, method:'get'});
}


/////////////////////////////////////////////////////////////////////////
function DisplayStatsGeneral() {

	new Ajax.Updater('surveypanel', '/stats/index/0', {asynchronous:true, evalScripts:true, method:'get'});
}


/////////////////////////////////////////////////////////////////////////
function DisplayStatDetail(paidmode, year, sftype) {

	new Ajax.Updater('surveypanel', '/stats/detail/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'paidmode=' + paidmode + '&sftype=' + sftype + '&year=' + year});
}


/////////////////////////////////////////////////////////////////////////
function MainMenuLinkSaveClearWait(url, auth) {
	saveClearWait('menu_MainMenu');
	new Ajax.Updater('surveypanel', url, {asynchronous:false, evalScripts:true, method:'get', parameters:''});
}


/////////////////////////////////////////////////////////////////////////
function MenuLink(url, auth) {
	saveCurrentPage();
	new Ajax.Updater('surveypanel', url, {asynchronous:false, evalScripts:true, method:'get', parameters:''});
}


/////////////////////////////////////////////////////////////////////////
function MainMenuRefresh() {
	new Ajax.Updater('', '/menu/new', {asynchronous:false, evalScripts:true, method:'get', parameters:''});
}


/////////////////////////////////////////////////////////////////////////
function IndexSetSuspendControls(stripconame, mode) {

	if(mode == 'suspended') {
		$('link_suspend_' + stripconame).style.display = 'none';
		$('link_reactivate_' + stripconame).style.display = '';

	} else if(mode == 'active') {
		$('link_suspend_' + stripconame).style.display = '';
		$('link_reactivate_' + stripconame).style.display = 'none';
	}

}


/////////////////////////////////////////////////////////////////////////
function AddUserBuildingAccess(cobldgid, authid) {
	var sellist = '';

	ob = $('allcompanyusers');
	for (var i = 0; i < ob.options.length; i++) {
		if (ob.options[ i ].selected) {
			if(sellist != '') {
				sellist += ',';
			}
			sellist += ob.options[i].value;
		}
	}

	if(sellist != '') {
		RequestUserBuildingAccess(cobldgid, sellist, 'add', 'building', authid);
	}
}


/////////////////////////////////////////////////////////////////////////
function AddBuildingUserAccess(uid, authid) {
	var sellist = '';

	ob = $('allcompanyusers');
	for (var i = 0; i < ob.options.length; i++) {
		if (ob.options[ i ].selected) {
			if(sellist != '') {
				sellist += ',';
			}
			sellist += ob.options[i].value;
		}
	}

	if(sellist != '') {
		RequestUserBuildingAccess(uid, sellist, 'add', 'user', authid);
	}
}


/////////////////////////////////////////////////////////////////////////
function DeleteUserBuildingAccess(cobldgid, authid) {
	var sellist = '';

	ob = $('allbuildingusers');
	for (var i = 0; i < ob.options.length; i++) {
		if (ob.options[ i ].selected) {
			if(sellist != '') {
				sellist += ',';
			}
			sellist += ob.options[i].value;
		}
	}

	if(sellist != '') {
		RequestUserBuildingAccess(sellist, cobldgid, 'delete', 'building', authid);
	}
}


/////////////////////////////////////////////////////////////////////////
function DeleteBuildingUserAccess(uid, authid) {
	var sellist = '';

	ob = $('allbuildingusers');
	for (var i = 0; i < ob.options.length; i++) {
		if (ob.options[ i ].selected) {
			if(sellist != '') {
				sellist += ',';
			}
			sellist += ob.options[i].value;
		}
	}

	if(sellist != '') {
		RequestUserBuildingAccess(uid, sellist, 'delete', 'user', authid);
	}
}


/////////////////////////////////////////////////////////////////////////
function UpdateHasBelongsMany(updatediv, url, idtable, combinedtable, operation, id, authid) {
	sellist = ''
    var selbox;

	if(operation == 'add') {
		selbox = $('list_' + idtable);
	} else {
		selbox = $('list_' + combinedtable);
	}

	for (var i = 0; i < selbox.options.length; i++) {
		if (selbox.options[i].selected) {
			if(sellist != '') {
				sellist += ',';
			}
			sellist += selbox.options[i].value;
		}
	}

	var mode = operation + 'habtm';
	new Ajax.Updater(updatediv, url, {asynchronous:true, evalScripts:true, method:'get', parameters:'updateids=' + encodeURIComponent(sellist) + '&fixedid=' + encodeURIComponent(id) + '&idtable=' + encodeURIComponent(idtable) + '&combinedtable=' + encodeURIComponent(combinedtable) + '&mode=' + encodeURIComponent(mode) + '&authid=' + encodeURIComponent(authid)});

}

/////////////////////////////////////////////////////////////////////////
function RequestUserBuildingAccess(userid, cobldgid, mode, key, authid) {

	new Ajax.Updater('divuseraccess', '/companybuildings_users/update/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'uid=' + userid + '&cobldgid=' + encodeURIComponent(cobldgid) + '&mode=' + encodeURIComponent(mode) + '&key=' + encodeURIComponent(key) + '&authid=' + encodeURIComponent(authid)});
}


/////////////////////////////////////////////////////////////////////////
function BeginBuildingSurveyNewYear(bsid, authid) {

	new Ajax.Updater('', '/accounts/createbuildingsurveynewyear/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'bsid=' + encodeURIComponent(bsid) + '&authid=' + encodeURIComponent(authid)});

}

/////////////////////////////////////////////////////////////////////////
function BeginBuildingSurveyNewYear_UNUSED(bldgid, authid) {

	new Ajax.Updater('', '/accounts/createbuildingsurvey/0', {asynchronous:true, evalScripts:true, method:'get', parameters:'uid=' + userid + '&cobldgid=' + encodeURIComponent(cobldgid) + '&mode=' + encodeURIComponent(mode) + '&key=' + encodeURIComponent(key) + '&authid=' + encodeURIComponent(authid)});

}



