/******************************************
Called in grab function and in onBlur to 
reset empty fields to zero for summing 
purposes
******************************************/
function zeroBlankFields()	{
		if(!this.value) this.value  = 0;
}

/******************************************
Called onFocus of input field to clear 
value of a field
******************************************/
function clearZeroField()	{
	if(this.value == 0) this.value = "";
}

/******************************************
Called onFocus of input field to blur
******************************************/
function blurFunction()	{
	this.blur();
}

/******************************************
Changes the contents of an element in much
the same way as 'innerHTML', but this is a
more reliable solution
******************************************/
function replaceElementContent(elementID, newContent) {
	var element = document.getElementById(elementID);
	while(element.firstChild) {
		element.removeChild(element.firstChild);
	}
	element.appendChild(document.createTextNode(newContent));
	
	if(document.getElementById(elementID+"Input")) {
		document.getElementById(elementID+"Input").value = newContent;
	}
}

/******************************************
Row Totals Function. Calculates the 
total price and total install time for a
specified row and populates the 
corresponding total boxes.
******************************************/
function calculateRowValues(CorI, itemNumber) {
	qtyValue = document.getElementById(CorI+ "qtyInput" +itemNumber).value;
	pricePerUnitValue = document.getElementById(CorI+ "ppuInput"+itemNumber).value;
	installTimePerUnitValue = document.getElementById(CorI+ "timePerUnitInput"+itemNumber).value;
	
	document.getElementById(CorI+ "totalPriceInput"+itemNumber).value = qtyValue * pricePerUnitValue;
	document.getElementById(CorI+ "totalInstallInput"+itemNumber).value = qtyValue * installTimePerUnitValue;
}


/******************************************
Runs all calculation functions after
validation and populates the 'total' row
at the end of the table
******************************************/
function doSavingsCalculations() {
	/* calculate "C" table totals */
	CqtyTotalSum = 0;
	CPriceTotalSum = 0;
	CTimeTotalSum = 0;
	
	for (var j = 0; j < totalConventionalItems; j++) {
		calculateRowValues("C",j);
		
		CqtyTotalSum += parseInt(qtyValue);
		CPriceTotalSum += parseInt(document.getElementById("CtotalPriceInput"+j).value);
		CTimeTotalSum += parseInt(document.getElementById("CtotalInstallInput"+j).value);
	}
	
	/* write "C" table totals */
	replaceElementContent("CQtyTotal",CqtyTotalSum);
	replaceElementContent("CPriceTotal",CPriceTotalSum);
	replaceElementContent("CTimeTotal",CTimeTotalSum);	
	
	
	/* calculate and write switchboard install time */
	CpowerPanelsInstall = parseInt(document.getElementById("CtotalInstallInput0").value);
	ClightingPanelsInstall = parseInt(document.getElementById("CtotalInstallInput1").value);
	CtransformerInstall = parseInt(document.getElementById("CtotalInstallInput2").value);
	ClightingContactorsInstall = parseInt(document.getElementById("CtotalInstallInput3").value);
	
	document.getElementById("ItimePerUnitInput0").value = (CpowerPanelsInstall + ClightingPanelsInstall + CtransformerInstall + ClightingContactorsInstall) * 0.25;
	
	
	/* calculate "I" table totals */
	IqtyTotalSum = 0;
	IPriceTotalSum = 0;
	ITimeTotalSum = 0;	
	
	for (var j = 0; j < totalIntegratedItems; j++) {
		calculateRowValues("I",j);		
		
		IqtyTotalSum += parseInt(qtyValue);
		IPriceTotalSum += parseInt(document.getElementById("ItotalPriceInput"+j).value);
		ITimeTotalSum += parseFloat(document.getElementById("ItotalInstallInput"+j).value);
	}
	
	
	/* write "I" table totals */
	replaceElementContent("IQtyTotal",IqtyTotalSum);
	replaceElementContent("IPriceTotal",IPriceTotalSum);
	replaceElementContent("ITimeTotal",ITimeTotalSum);	
	
	
	/* set variables for summary box calculations */
	var powerPanelsQty = parseInt(document.getElementById("CqtyInput0").value);
	var lightingPanelsQty = parseInt(document.getElementById("CqtyInput1").value);
	var transformerQty = parseInt(document.getElementById("CqtyInput2").value);
	var lightingContactorsQty = parseInt(document.getElementById("CqtyInput3").value);
	var integratedSwitchboardQty = parseInt(document.getElementById("IqtyInput0").value);
	var laborRateValue = parseInt(document.getElementById("laborRateInput").value);
	
	
	/* calculate summary totals */
	var summaryItemsSaved = ((powerPanelsQty * 3) + (lightingPanelsQty * 3) + transformerQty + lightingContactorsQty) - integratedSwitchboardQty;
	var summaryConnectionsSaved = (powerPanelsQty * 4) + (lightingPanelsQty * 4) + (transformerQty * 7) + (lightingContactorsQty * 3);
	
	var summaryInstallHoursSavings = CTimeTotalSum - ITimeTotalSum;
		
	var summaryLaborCostSavings = laborRateValue * summaryInstallHoursSavings;	
	var summaryLaborCostSavingsStr = "$" + summaryLaborCostSavings.toFixed(2);
	
	var summaryTotalCostSavings = CPriceTotalSum - IPriceTotalSum + summaryLaborCostSavings;
	var summaryTotalCostSavingsStr = "$" + summaryTotalCostSavings.toFixed(2);
	
	
	/* write summary totals */
	replaceElementContent("summaryItemsSaved",summaryItemsSaved);
	replaceElementContent("summaryConnectionsSaved",summaryConnectionsSaved);
	replaceElementContent("summaryInstallHoursSavings",summaryInstallHoursSavings);	
	replaceElementContent("summaryLaborCostSavings",summaryLaborCostSavingsStr);
	replaceElementContent("summaryTotalCostSavings",summaryTotalCostSavingsStr);
}


/******************************************
Validator that runs on form submission then
run the actual calculation function
******************************************/
function validateCalculatorFields(formObject) {
	calcForm = document.getElementById(formObject);

	focusFirstInvalid = "";
	for (var i = 0; i < calcForm.length; i++) {
		if (!calcForm.elements[i].className || !/\btotalInput\b/.test(calcForm.elements[i].className)) {
			if(calcForm.elements[i].value.search(/^\d+$/) == -1 && calcForm.elements[i].type != "hidden" && calcForm.elements[i].id != "projectNameInput" && calcForm.elements[i].id != "customerNameInput") {
				if(focusFirstInvalid == "") {
					focusFirstInvalid = calcForm.elements[i];
				}
			}
		}
	}
	
	if(focusFirstInvalid != "") {
		//alert(focusFirstInvalid);
		alert("Please enter whole number values only.");
		focusFirstInvalid.focus();
		focusFirstInvalid.value = "";
	} else {
		doSavingsCalculations(); /* DEFINED IN DOCUMENT */
		document.getElementById("requestQuoteButton").style.visibility = "visible";
	}
}

/******************************************
Init function that attaches onfocus and
onblur items to input fields
******************************************/

function attachmentsForCalculatorInputs(formObject) {
	
	/* identify form */
	calcForm = document.getElementById(formObject);
	totalConventionalItems = 0;
	totalIntegratedItems = 0;
	
	for (var i = 0; i < calcForm.length; i++) {
		inputItem = calcForm.elements[i];
		if(inputItem.id == "projectNameInput" || inputItem.id == "customerNameInput") continue;
		
		/* set events for active inputs */
		if(inputItem.value == "") {
			inputItem.value = 0;
		}
				
		inputItem.onfocus = clearZeroField;
		inputItem.onblur = zeroBlankFields;
		inputItem.setAttribute('autocomplete','off');
	
		/* set events for 'total' inputs */
		if (inputItem.className && /\btotalInput\b/.test(inputItem.className)) {
			inputItem.onfocus = blurFunction;
			inputItem.onselect = blurFunction;
		}
	
		/* count 'C' rows and 'I' rows (based on number of inputs with class of 'CqtyInput' and 'IqtyInput' */
		if (inputItem.className && /\bCqtyInput\b/.test(inputItem.className)) {
			totalConventionalItems++;
		}
		
		if (inputItem.className && /\bIqtyInput\b/.test(inputItem.className)) {
			totalIntegratedItems++;
		}
	}
}

/******************************************
Init function that writes regurgitated
values (taken from URL parameters) for
INDEX page
******************************************/
function writeRegurgitatedValuesInputPage() {
	document.getElementById("projectNameInput").value = getParam("projectNameInput");
	document.getElementById("customerNameInput").value = getParam("customerNameInput");
	if(getParam("laborRateInput")){
		document.getElementById("laborRateInput").value = getParam("laborRateInput");
	} else {
		document.getElementById("laborRateInput").value = 65;
	}
		
	/*** c table values ***/
	//power panels
	if(getParam("CqtyInput0")){
		document.getElementById("CqtyInput0").value = getParam("CqtyInput0");
	} else {
		document.getElementById("CqtyInput0").value = 1;
	}
	if(getParam("CppuInput0")){
		document.getElementById("CppuInput0").value = getParam("CppuInput0");
	} else {
		document.getElementById("CppuInput0").value = 5000;
	}
	document.getElementById("CtotalPriceInput0").value = getParam("CtotalPriceInput0");
	if(getParam("CtimePerUnitInput0")){
		document.getElementById("CtimePerUnitInput0").value = getParam("CtimePerUnitInput0");
	} else {
		document.getElementById("CtimePerUnitInput0").value = 13;
	}
	document.getElementById("CtotalInstallInput0").value = getParam("CtotalInstallInput0");
	
	//lighting panels
	if(getParam("CqtyInput1")){
		document.getElementById("CqtyInput1").value = getParam("CqtyInput1");
	} else {
		document.getElementById("CqtyInput1").value = 4;
	}
	if(getParam("CppuInput1")){
		document.getElementById("CppuInput1").value = getParam("CppuInput1");
	} else {
		document.getElementById("CppuInput1").value = 1000;
	}
	document.getElementById("CtotalPriceInput1").value = getParam("CtotalPriceInput1");
	if(getParam("CtimePerUnitInput1")){
		document.getElementById("CtimePerUnitInput1").value = getParam("CtimePerUnitInput1");
	} else {
		document.getElementById("CtimePerUnitInput1").value = 13;
	}
	document.getElementById("CtotalInstallInput1").value = getParam("CtotalInstallInput1");
	
	//transformer
	if(getParam("CqtyInput2")){
		document.getElementById("CqtyInput2").value = getParam("CqtyInput2");
	} else {
		document.getElementById("CqtyInput2").value = 2;
	}
	if(getParam("CppuInput2")){
		document.getElementById("CppuInput2").value = getParam("CppuInput2");
	} else {
		document.getElementById("CppuInput2").value = 5000;
	}
	document.getElementById("CtotalPriceInput2").value = getParam("CtotalPriceInput2");
	if(getParam("CtimePerUnitInput2")){
		document.getElementById("CtimePerUnitInput2").value = getParam("CtimePerUnitInput2");
	} else {
		document.getElementById("CtimePerUnitInput2").value = 18;
	}
	document.getElementById("CtotalInstallInput2").value = getParam("CtotalInstallInput2");
	
	//lighting contactors
	if(getParam("CqtyInput3")){
		document.getElementById("CqtyInput3").value = getParam("CqtyInput3");
	} else {
		document.getElementById("CqtyInput3").value = 2;
	}
	if(getParam("CppuInput3")){
		document.getElementById("CppuInput3").value = getParam("CppuInput3");
	} else {
		document.getElementById("CppuInput3").value = 1000;
	}
	document.getElementById("CtotalPriceInput3").value = getParam("CtotalPriceInput3");
	if(getParam("CtimePerUnitInput3")){
		document.getElementById("CtimePerUnitInput3").value = getParam("CtimePerUnitInput3");
	} else {
		document.getElementById("CtimePerUnitInput3").value = 7;
	}
	document.getElementById("CtotalInstallInput3").value = getParam("CtotalInstallInput3");
	
	//conduit and cable
	if(getParam("CqtyInput4")){
		document.getElementById("CqtyInput4").value = getParam("CqtyInput4");
	} else {
		document.getElementById("CqtyInput4").value = 1;
	}
	if(getParam("CppuInput4")){
		document.getElementById("CppuInput4").value = getParam("CppuInput4");
	} else {
		document.getElementById("CppuInput4").value = 3000;
	}
	document.getElementById("CtotalPriceInput4").value = getParam("CtotalPriceInput4");
	document.getElementById("CtimePerUnitInput4").value = getParam("CtimePerUnitInput4");
	document.getElementById("CtotalInstallInput4").value = getParam("CtotalInstallInput4");
	
	//other equipment
	document.getElementById("CqtyInput5").value = getParam("CqtyInput5");
	document.getElementById("CppuInput5").value = getParam("CppuInput5");
	document.getElementById("CtotalPriceInput5").value = getParam("CtotalPriceInput5");
	document.getElementById("CtimePerUnitInput5").value = getParam("CtimePerUnitInput5");
	document.getElementById("CtotalInstallInput5").value = getParam("CtotalInstallInput5");
	
	//other equipment
	document.getElementById("CqtyInput6").value = getParam("CqtyInput6");
	document.getElementById("CppuInput6").value = getParam("CppuInput6");
	document.getElementById("CtotalPriceInput6").value = getParam("CtotalPriceInput6");
	document.getElementById("CtimePerUnitInput6").value = getParam("CtimePerUnitInput6");
	document.getElementById("CtotalInstallInput6").value = getParam("CtotalInstallInput6");
	
	//c table totals
	replaceElementContent("CQtyTotal",getParam("CQtyTotalInput"));
	replaceElementContent("CPriceTotal",getParam("CPriceTotalInput"));
	replaceElementContent("CTimeTotal",getParam("CTimeTotalInput"));
	
	/*** i table values ***/
	
	//isb
	if(getParam("IqtyInput0")){
		document.getElementById("IqtyInput0").value = getParam("IqtyInput0");
	} else {
		document.getElementById("IqtyInput0").value = 1;
	}
	if(getParam("IppuInput0")){
		document.getElementById("IppuInput0").value = getParam("IppuInput0");
	} else {
		document.getElementById("IppuInput0").value = 27000;
	}
	document.getElementById("ItotalPriceInput0").value = getParam("ItotalPriceInput0");
	document.getElementById("ItimePerUnitInput0").value = getParam("ItimePerUnitInput0");
	document.getElementById("ItotalInstallInput0").value = getParam("ItotalInstallInput0");
	
	//other equipment
	document.getElementById("IqtyInput1").value = getParam("IqtyInput1");
	document.getElementById("IppuInput1").value = getParam("IppuInput1");
	document.getElementById("ItotalPriceInput1").value = getParam("ItotalPriceInput1");
	document.getElementById("ItimePerUnitInput1").value = getParam("ItimePerUnitInput1");
	document.getElementById("ItotalInstallInput1").value = getParam("ItotalInstallInput1");
	
	//other equipment
	document.getElementById("IqtyInput2").value = getParam("IqtyInput2");
	document.getElementById("IppuInput2").value = getParam("IppuInput2");
	document.getElementById("ItotalPriceInput2").value = getParam("ItotalPriceInput2");
	document.getElementById("ItimePerUnitInput2").value = getParam("ItimePerUnitInput2");
	document.getElementById("ItotalInstallInput2").value = getParam("ItotalInstallInput2");
	
	//i table totals
	replaceElementContent("IQtyTotal",getParam("IQtyTotalInput"));
	replaceElementContent("IPriceTotal",getParam("IPriceTotalInput"));
	replaceElementContent("ITimeTotal",getParam("ITimeTotalInput"));
	
	/*** summary values ***/
	replaceElementContent("summaryItemsSaved",getParam("summaryItemsSavedInput"));
	replaceElementContent("summaryConnectionsSaved",getParam("summaryConnectionsSavedInput"));
	replaceElementContent("summaryInstallHoursSavings",getParam("summaryInstallHoursSavingsInput"));	
	replaceElementContent("summaryLaborCostSavings",getParam("summaryLaborCostSavingsInput"));
	replaceElementContent("summaryTotalCostSavings",getParam("summaryTotalCostSavingsInput"));
}



/******************************************
Init function that writes regurgitated
values (taken from URL parameters) for
REQUEST QUOTE page
******************************************/
function writeRegurgitatedValuesQuotePage() {
	
	replaceElementContent("projectNameInput",getParam("projectNameInput"));
	replaceElementContent("customerNameInput",getParam("customerNameInput"));
	replaceElementContent("laborRateInput",getParam("laborRateInput"));
	
	/*** c table values ***/
	replaceElementContent("CqtyInput0",getParam("CqtyInput0"));
	replaceElementContent("CppuInput0",getParam("CppuInput0"));
	replaceElementContent("CtotalPriceInput0",getParam("CtotalPriceInput0"));
	replaceElementContent("CtimePerUnitInput0",getParam("CtimePerUnitInput0"));
	replaceElementContent("CtotalInstallInput0",getParam("CtotalInstallInput0"));
	
	replaceElementContent("CqtyInput1",getParam("CqtyInput1"));	
	replaceElementContent("CppuInput1",getParam("CppuInput1"));
	replaceElementContent("CtotalPriceInput1",getParam("CtotalPriceInput1"));
	replaceElementContent("CtimePerUnitInput1",getParam("CtimePerUnitInput1"));
	replaceElementContent("CtotalInstallInput1",getParam("CtotalInstallInput1"));
	
	replaceElementContent("CqtyInput2",getParam("CqtyInput2"));
	replaceElementContent("CppuInput2",getParam("CppuInput2"));
	replaceElementContent("CtotalPriceInput2",getParam("CtotalPriceInput2"));
	replaceElementContent("CtimePerUnitInput2",getParam("CtimePerUnitInput2"));
	replaceElementContent("CtotalInstallInput2",getParam("CtotalInstallInput2"));
	
	replaceElementContent("CqtyInput3",getParam("CqtyInput3"));
	replaceElementContent("CppuInput3",getParam("CppuInput3"));
	replaceElementContent("CtotalPriceInput3",getParam("CtotalPriceInput3"));
	replaceElementContent("CtimePerUnitInput3",getParam("CtimePerUnitInput3"));
	replaceElementContent("CtotalInstallInput3",getParam("CtotalInstallInput3"));
	
	replaceElementContent("CqtyInput4",getParam("CqtyInput4"));
	replaceElementContent("CppuInput4",getParam("CppuInput4"));
	replaceElementContent("CtotalPriceInput4",getParam("CtotalPriceInput4"));
	replaceElementContent("CtimePerUnitInput4",getParam("CtimePerUnitInput4"));
	replaceElementContent("CtotalInstallInput4",getParam("CtotalInstallInput4"));
	
	replaceElementContent("CqtyInput5",getParam("CqtyInput5"));
	replaceElementContent("CppuInput5",getParam("CppuInput5"));
	replaceElementContent("CtotalPriceInput5",getParam("CtotalPriceInput5"));
	replaceElementContent("CtimePerUnitInput5",getParam("CtimePerUnitInput5"));
	replaceElementContent("CtotalInstallInput5",getParam("CtotalInstallInput5"));
	
	replaceElementContent("CqtyInput6",getParam("CqtyInput6"));
	replaceElementContent("CppuInput6",getParam("CppuInput6"));
	replaceElementContent("CtotalPriceInput6",getParam("CtotalPriceInput6"));
	replaceElementContent("CtimePerUnitInput6",getParam("CtimePerUnitInput6"));
	replaceElementContent("CtotalInstallInput6",getParam("CtotalInstallInput6"));
	
	replaceElementContent("CQtyTotal",getParam("CQtyTotalInput"));
	replaceElementContent("CPriceTotal",getParam("CPriceTotalInput"));
	replaceElementContent("CTimeTotal",getParam("CTimeTotalInput"));
	
	/*** i table values ***/
	replaceElementContent("IqtyInput0",getParam("IqtyInput0"));
	replaceElementContent("IppuInput0",getParam("IppuInput0"));
	replaceElementContent("ItotalPriceInput0",getParam("ItotalPriceInput0"));
	replaceElementContent("ItimePerUnitInput0",getParam("ItimePerUnitInput0"));
	replaceElementContent("ItotalInstallInput0",getParam("ItotalInstallInput0"));
	
	replaceElementContent("IqtyInput1",getParam("IqtyInput1"));
	replaceElementContent("IppuInput1",getParam("IppuInput1"));
	replaceElementContent("ItotalPriceInput1",getParam("ItotalPriceInput1"));
	replaceElementContent("ItimePerUnitInput1",getParam("ItimePerUnitInput1"));
	replaceElementContent("ItotalInstallInput1",getParam("ItotalInstallInput1"));
	
	replaceElementContent("IqtyInput2",getParam("IqtyInput2"));
	replaceElementContent("IppuInput2",getParam("IppuInput2"));
	replaceElementContent("ItotalPriceInput2",getParam("ItotalPriceInput2"));
	replaceElementContent("ItimePerUnitInput2",getParam("ItimePerUnitInput2"));
	replaceElementContent("ItotalInstallInput2",getParam("ItotalInstallInput2"));
	
	replaceElementContent("IQtyTotal",getParam("IQtyTotalInput"));
	replaceElementContent("IPriceTotal",getParam("IPriceTotalInput"));
	replaceElementContent("ITimeTotal",getParam("ITimeTotalInput"));
	
	/*** summary values ***/
	replaceElementContent("summaryItemsSaved",getParam("summaryItemsSavedInput"));
	replaceElementContent("summaryConnectionsSaved",getParam("summaryConnectionsSavedInput"));
	replaceElementContent("summaryInstallHoursSavings",getParam("summaryInstallHoursSavingsInput"));	
	replaceElementContent("summaryLaborCostSavings",getParam("summaryLaborCostSavingsInput"));
	replaceElementContent("summaryTotalCostSavings",getParam("summaryTotalCostSavingsInput"));
}

/*******************************************************
functions to copy over project and customer name fields
*******************************************************/
function projectNameDupe() {
	if(document.getElementById('projectNameInput').value == "") {
		document.getElementById('projectNameInput').value = "(not provided)";
	}else{
		document.getElementById('projectNameInput').value = document.getElementById('projectNameInput').value;
	}
}

function customerNameDupe() {
	if(document.getElementById('customerNameInput').value == "") {
		document.getElementById('customerNameInput').value = "(not provided)";
	}else{
		document.getElementById('customerNameInput').value = document.getElementById('customerNameInput').value;
	}
}

//get url parameter by name
function getParam(paramName) {
	var regexS = "[\\?&]"+ paramName +"=([^&#]*)";
	var regex = new RegExp( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	
	if( results == null ) {
		return "";
	} else {		
		var paramValue = results[1];
		
		paramValue = paramValue.replace(/\+/g," ");
		paramValue = paramValue.replace(/\%24/g,"$");
		paramValue = paramValue.replace(/\%28/g,"(");
		paramValue = paramValue.replace(/\%29/g,")");
		
		return paramValue;
	}
}

// function to write hidden inputs
function writeHiddenInput(inputName,urlParamName) {
	document.writeln("<input type=\"hidden\" name=\""+inputName+"\" id=\""+inputName+"\" value=\""+getParam(urlParamName)+"\" />");		
}



// VALIDATION VARS
var validationErrorTitle = "Please complete the following information to continue:\n\n";
var validationErrorBody = "";
var postValidateFocus = "";


/*******************************************************************
Sets the first field with an error to be focused after validation.
*******************************************************************/
function setFirstInvalid(inputObj) {
	if(!validationErrorMessage)	{postValidateFocus = document.getElementById(inputObj);}
}
// This function checks for a valid email address
function validateEmail(fieldID)	{
	var fldObj = document.getElementById(fieldID);
	if(fldObj.value.search(/^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$/) == -1) {
		return false;
	}
}
