function isValidAmount(s) {
	var numPeriods = 0;
	var numDollarSigns = 0;

	// '$' is OK if it is first or last


	for (var i = 0; i < s.length; ++i) {
		var c = s.charAt(i);

		if (c == '.') {
			++numPeriods;
			continue;
		}

		if (c == '$') {
			++numDollarSigns;
			continue;
		}

		if (c < '0' || c > '9') {
			return false;
		}
	}

	if (numPeriods > 1) {
		return false;
	}
	
	if (numDollarSigns > 1) {
		return false;
	}

	// Decimal pt has to be one of the last 3 chars
	if (numPeriods == 1) {
		var pos = s.indexOf('.');
		if (pos < s.length - 3) {
			return false;
		}
	}


	// Dollar sign must be first or last
	if (numDollarSigns == 1) {
		var pos = s.indexOf('$');
		if (pos != 0 && pos != s.length - 1) {
			return false;
		}
	}

	return true;
}


function setElementColor(elm, isValid) {
	if (isValid) {
		elm.style.backgroundColor = "#FFFFFF";
	}
	else {
		elm.style.backgroundColor = "#FF0000";
	}
}


function calculateHit() {

	var solarElm = document.getElementById('solar');
	var windElm = document.getElementById('wind');
	var subconElm = document.getElementById('subcontracting');
	var resultDiv = document.getElementById('result');

	// Get rid of commas
	var solarStr = solarElm.value.replace(/,/g, "");
	var windStr = windElm.value.replace(/,/g, "");
	var subconStr = subconElm.value.replace(/,/g, "");

	var solarOK = isValidAmount(solarStr);
	var windOK = isValidAmount(windStr);
	var subconOK = isValidAmount(subconStr);
	
	// Now strip dollar signs	
	solarStr = solarStr.replace(/\$/g, "");
	windStr = windStr.replace(/\$/g, "");
	subconStr = subconStr.replace(/\$/g, "");


	setElementColor(solarElm, solarOK);
	setElementColor(windElm, windOK);
	setElementColor(subconElm, subconOK);

	if (solarOK && windOK && subconOK) {
		var solar = parseInt(parseFloat(solarStr));
		var wind = parseInt(parseFloat(windStr));
		var subcon = parseInt(parseFloat(subconStr));

		var total = (solar * .027) + (wind * .053) + (subcon * .00857);
		
		// Premium before inspection fee must be at least 1200
		total = Math.max(total, 1200);

		// Add inspection fee
		total += 350;

		// Round to int
		total = Math.round(total);

		resultDiv.innerHTML = '$' + total;
	}
	else {
		resultDiv.innerHTML = '---';
	}
}

