


function round(number, x)
{
     x = (!x ? 2: x);
     temp = Math.round(number * Math.pow(10, x)) / Math.pow(10,x);

     //check to see whether padding of 2 zeros is needed.
     if (temp == Math.floor(temp))
     {
          temp = temp+".00";
     }
     else
     {
          //check to see whether padding of 1 zero is needed.
          if (temp*10 == Math.floor(temp*10))
          {
               temp =  temp + '0';
          }
     }

     return temp;
}

function showLayer(whichLayer) 
{
	
	var elem, vis;
	
	elem = getElement(whichLayer);
	vis = elem.style;
	
	if (vis.display='none')
		toggleLayer(elem);
		
}

function hideLayer(whichLayer)
{
	var elem, vis;
	
	elem = getElement(whichLayer);
	vis = elem.style;
	
	if (vis.display='block')
		toggleLayer(elem);
		
}


function getElement(whichLayer) {
	var elem;
	if( document.getElementById ) // this is the way the standards work
		elem = document.getElementById( whichLayer );
	else if( document.all ) // this is the way old msie versions work
		elem = document.all[whichLayer];
	else if( document.layers ) // this is the way nn4 works
		elem = document.layers[whichLayer];
	
	return elem
}


function toggleLayer(elem)
{ 
    
  var vis;
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function startQuestions()
{

	
	hideLayer('numberRiders');
	hideLayer('results');	
	hideLayer('zeroEmissions');
}

function processForm()
{
	
	if (validateForm())
	{
		showLayer('results');
		computeResults();
	}
	
	
}

function validateForm()
{
	var validForm, err;
	validForm = true;
	err = "";
	
	if (!isValidNumber(document.cost.total_distance.value))
	{
		err = addErrLine(err,'Commute distance is not valid.');
		validForm = false;
	}
	
	if (!isValidNumber(document.cost.days_per_month.value))
	{
		err = addErrLine(err,'Days worked per month is not valid.');
		validForm = false;
	}
	
//STOP REPORTING ERRORS	reportErrors(validForm, err)
	
	return validForm;
	
}

function isValidNumber(text)
{
	if (text == '') return false;
	
	//if (isNumeric(text) == false) return false;
	
	return true;
	

}

function IsNumeric(sText)
{

   

   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }


function addErrLine(err, errText)
{
	if (!(errText == ""))
		return err + errText + '\n';
		
	return err;
	
}


function reportErrors(isValid, err)
{
	if (isValid == false)
	{
		alert(err);	
	}
	
}

function computeResults()
{
	
	// CONSTANTS
	CFUEL = 4.5;
	
	total_distance = parseFloat(document.cost.total_distance.value) || 0;
	days_per_month = parseFloat(document.cost.days_per_month.value) || 0;
	miles_per_gallon = parseFloat(document.cost.cboMPG.value) || 0;
	//txtMPG = parseFloat(document.cost.txtMpg.value) || 0;
	fuel_cost = CFUEL;
	carpoolNumber = parseFloat(document.cost.carpoolNumber.value) || 0;
	incentiveAmount = parseFloat(document.cost.incentiveAmount.value) || 0;
	incentiveCount = parseFloat(document.cost.incentiveCount.value) || 0;
	doCarpool = getCheckedValue(document.cost.radCarpool);
	howTraveling = getCheckedValue(document.cost.radHow);
	
	
	
	estimated_monthly_cost = - (total_distance*days_per_month/miles_per_gallon*fuel_cost) ;
	
	document.cost.monthlyCost.value  = "$" + round(estimated_monthly_cost);
		
	estimated_annual_cost = estimated_monthly_cost * 12;

	document.cost.zevSavings.value = zevSavings(estimated_annual_cost);
	document.cost.yearlyCost.value = "$" + round(estimated_annual_cost);
	document.cost.onePersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 1);
	document.cost.twoPersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 2);
	document.cost.threePersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 3);
	document.cost.fourPersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 4);
	document.cost.fivePersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 5);
	document.cost.sixPersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 6);
	document.cost.sevenPersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 7);
	document.cost.eightPersonCost.value = "$" + perPersonSavings(estimated_annual_cost, 8);
	
	setEmissionsInfo(doCarpool, howTraveling, carpoolNumber);
	createCostChart(estimated_annual_cost, doCarpool, carpoolNumber, howTraveling);
	filterResults(carpoolNumber, doCarpool, howTraveling);
}

function setEmissionsInfo(doCarpool, howTraveling, carpoolNumber)
{
	//Emissions ROG + NOx + PM10 + CO2
	//Taken from EMFAC2007, v2.3 (Nov 1 2006), statewide average annual emissions
	gramsPerMile = 0.332+0.391+0.220+4.032;
	gramsPerTripEnd = 1.189+0.535+0.015+10.113;
	valleyMilesTotal = 48067452;
	valleyTrips = 8260110;
		
	gramsPerYear = (valleyMilesTotal * gramsPerMile) + (gramsPerTripEnd * 2);
	gramsPerLb = 453.6;
	lbPerTon = 2000;
	valleyLbsPerYear = (gramsPerYear / gramsPerLb) / lbPerTon;
	
	document.cost.valleyLbsPerYear.value = round(valleyLbsPerYear);
	document.cost.valleyMilesPerYear.value = valleyMilesTotal;	
	
	if (howTraveling == "zev")
	{
		document.cost.reducedLbsPerYear.value = -round(valleyLbsPerYear);
		document.cost.reducedMilesPerYear.value = -valleyMilesTotal;
		return;
	}
	
	if (doCarpool == "no")
	{
		document.cost.reducedLbsPerYear.value = 0//round(valleyLbsPerYear);
		document.cost.reducedMilesPerYear.value = 0// valleyMilesTotal;
	} else
	{
		carpoolFactor = (carpoolNumber - 1)/carpoolNumber;
		adjustedGramsPerYear = gramsPerYear * carpoolFactor;
		adjustedTonsPerYear = (adjustedGramsPerYear / gramsPerLb) / lbPerTon;
		adjustedMilesPerYear = valleyMilesTotal * carpoolFactor;
		document.cost.reducedLbsPerYear.value = -round(adjustedTonsPerYear);
		document.cost.reducedMilesPerYear.value = -adjustedMilesPerYear;
	}
}

function createCostChart(annual_cost, doCarpool, carpoolNumber, howTraveling)
{
	//For each person move markers
	numPeople = 8
	spacing = 65
	
	//first person is at position 0 so don't touch
	for (markNum = 1; markNum <= numPeople; markNum++  )
	{
		leftOffset = (spacing * (markNum-1)) + 'px'
		
		document.getElementById('mark' + markNum).style.left = leftOffset
		document.getElementById('markCost' + markNum).style.left = leftOffset
		document.getElementById('cost' + markNum).innerHTML = "$" + perPersonSavings(annual_cost, markNum);
	}

	document.getElementById('endCost').innerHTML = zevSavings(annual_cost)
	
	resetMarkWeight();
	
	if (doCarpool == "no" && howTraveling == "car" )
	{
		document.getElementById('mark1').style.fontWeight = "bold";
		document.getElementById('markCost1').style.fontWeight = "bold"; 
		
	}
	
	if (doCarpool == "yes" && howTraveling == "car" )
	{
		document.getElementById('mark' + carpoolNumber).style.fontWeight = "bold";
		document.getElementById('markCost' + carpoolNumber).style.fontWeight = "bold";
	}
	
	if (howTraveling == "zev" )
	{
		document.getElementById('mark9').style.fontWeight = "bold";
		document.getElementById('markCost9').style.fontWeight = "bold";
	}
	
	
}

function resetMarkWeight()
{
		
	numMarks = 9
	for (markNum = 1; markNum <= numMarks; markNum++)
	{
		document.getElementById('mark' + markNum).style.fontWeight = "normal";
		document.getElementById('markCost' + markNum).style.fontWeight = "normal";
	}	
}


function zevSavings(annualCost)
{
	incentiveAmount = parseFloat(document.cost.incentiveAmount.value) || 0;
	incentiveCount = parseFloat(document.cost.incentiveCount.value) || 0;
	yearlyIncentive = (incentiveAmount * incentiveCount);

	return round(-estimated_annual_cost + yearlyIncentive) || 0;
	
}

function perPersonSavings(annualCost, people)
{
	incentiveAmount = parseFloat(document.cost.incentiveAmount.value) || 0;
	incentiveCount = parseFloat(document.cost.incentiveCount.value) || 0;
	yearlyIncentive = (incentiveAmount * incentiveCount);
	
	if (people > 1)
	{
		return round(estimated_annual_cost/people + yearlyIncentive) || 0;
	}
	
	return round(estimated_annual_cost - yearlyIncentive) || 0;
	 
}

function filterResults(carpoolNumber, doCarpool, howTraveling)
{

	if (howTraveling == 'car')
	{
		hideLayer("zeroEmissions");
		showLayer("carpoolResults");
		showLayer("results");
		
		for (person = 1;  person <= 8; person++)
		{
			showLayer("Person" + person);
		}
		
		
		if (doCarpool == 'yes')
		{
			for (person = 1;  person <= 8; person++)
			{
				if (carpoolNumber > person) hideLayer("Person" + person);
			}
			
		} 
	}
	
	if (howTraveling == 'zev')
	{
		showLayer("zeroEmissions");	
		hideLayer("carpoolResults");
	}
	
	
}


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined) 
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}





