// (c) 2006 conscious.co.uk

function calcfuelcost() {
// Calculate fuel costs from number of miles driven, price of a litre and miles per gallon

   var formnames = new Array("milesperyear", "pricelitrefuel", "avgmpg");
   var formdisplayednames = new Array("Number of Miles Driven Per Year", "Normal Price for a Litre of Fuel", "Average MPG");
   var formvals = new Array();


   // get form values      
   for (i=0; i<formnames.length; i++)
      for (j=0,m=document.fuelcostform.elements.length;j<m;j++)
         if (document.fuelcostform.elements[j].name == formnames[i])
            formvals[formnames[i]] = document.fuelcostform.elements[j].value;

   // Error checking
   var isvalidnum = true;
   for (j=0; j<formnames.length; j++) {
      formvals[formnames[j]] = formvals[formnames[j]].replace("£", "");
      if (formvals[formnames[j]] == "") formvals[formnames[j]] = "0";
      for (i=0; i<formvals[formnames[j]].length; i++) {
         if ((formvals[formnames[j]].charAt(i) != "0")
         && (formvals[formnames[j]].charAt(i) != ".")
         && (!parseFloat(formvals[formnames[j]].charAt(i)))) {
            isvalidnum = false;
            alert("Please enter a valid number in the "+formdisplayednames[j]+" field");
            break;

      }
   }
   }
   
   if (isvalidnum) {
            
      var fuelexpenditurepy = ((formvals['milesperyear'] / formvals['avgmpg']) * 4.54 * formvals['pricelitrefuel']) / 100; // calculates cost spent on fuel per year, with 4.54 and 100 representing the approximate conversion from litres to gallons
      // format as money
      if (formvals['avgmpg'] == 0) fuelexpenditurepy = 0.00;
      else fuelexpenditurepy = poundsandpence(((parseInt(fuelexpenditurepy*100)) / 100), false, true);	
	
   // output values
      for (j=0,m=document.fuelcostform.elements.length;j<m;j++)
         if (document.fuelcostform.elements[j].name == 'fuelexpenditurepy')
            document.fuelcostform.elements[j].value = fuelexpenditurepy;	
   }
}



function poundsandpence(numnotrounded, returnasfloat, isthousands) {
// makes number conform to pounds with options of commas denoting thousands
var decbit = (numnotrounded.toString()).split(".");
var decpart = decbit[1];

if ((!returnasfloat) && (isthousands) && (decbit[0].length > 3)) {  // add commas for thousands if appropriate
   var afterthousands = "";
   for (tocommas = 0; tocommas < (decbit[0].length / 3); tocommas++) afterthousands = ","+decbit[0].substring((decbit[0].length-((tocommas+1)*3)), (decbit[0].length-(tocommas*3)))+afterthousands;
   afterthousands = afterthousands.substring(1);

}
else afterthousands = decbit[0];

var wholebit = afterthousands+"."+decpart;

if (!returnasfloat) return wholebit;
else return parseFloat(wholebit);
}