// Soil / Turf Calculator V0.00
var PhoneNo = '01527 550678';						// info for too big an order message
var TonsPerCubicMetre = 1.4;						// number of tons per cubic metre
var TurfWastage = 0.10;							// turf wastage factor (1.10 = 10%)

var MaxTurfOrder = 250;							// Max sqM Turf orderable
var MaxTurfOptions = 250;						// maximum turf area for turf drop-down						

var MaxSoilOrder = 25;							// set to maximum number of soil bags we will ship
var MaxBagOptions = 25;							// max number tommes for Soil drop down list

var diags = false;

var soilentryfields = new Array('wbdims', 'ddims',
			    'al', 'aw', 'ad', 'av',
			    'bl', 'bw', 'bd', 'bv',
                            'cl', 'cw', 'cd', 'cv',
			    'dl', 'dw', 'dd', 'dv');

var turfentryfields = new Array('wbdims',
			    'al', 'aw', 'av',
			    'bl', 'bw', 'bv',
                            'cl', 'cw', 'cv',
			    'dl', 'dw', 'dv');

function showmessage(msg){						// popup a message
  alert(msg);
}

function to2digits(num){						// return 2 decimal digits string of number
  var sign = num < 0 ? '-' : '';					// determine sign
  num = Math.abs(num);
  var whole = Math.floor(num);                				// no of pounds
  var fraction = Math.round((num - whole) * 100);  			// Number of Fraction (2 decimal places)
  if ( fraction > 99 ) fraction = 99;
  var res = fraction < 10 ? "0" + fraction.toString() : fraction.toString();  // make 2 digits
  return(sign + whole.toString() + '.' + res);
}


function createbagoptions(selid){					// generate a range of select sizes
  var sel = document.getElementById(selid);				// our SELECT statement
  var opt = new Option('0', '0', false, false);				// Add in an extra entry at the end
  sel.options[sel.options.length] = opt;
  for (var i=1; i <= MaxBagOptions; i++)				// for all bags
    {
    opt = new Option(i, i, false, false);				// create option
    sel.options[sel.options.length] = opt;				// add in the option
    }
  sel.options[0].selected = true;
}

function createareaoptions(selid){					// generate a range of Areas
  var sel = document.getElementById(selid);				// our SELECT statement
  var opt = new Option('0', '0', false, false);	// Add in an extra entry at the end
  sel.options[sel.options.length] = opt;
  for (var i=1; i <= MaxTurfOptions; i++)				// for all possible areas
    {
    opt = new Option(i, i, false, false);				// create option
    sel.options[sel.options.length] = opt;				// add in the option
    }
  sel.options[0].selected = true;
}

function checknum(prodid, field){					// validate typed info as +ve number
  var num = document.getElementById(field + '_' + prodid).value;
  if ( isNaN(num) || (num < 0) ) 
    {
    alert('Bad number: ' + num);
    num = 0;
    document.getElementById(field + '_' + prodid).value = '0';		// set to 0 if invalid
    }
  return num;
}

function setsoilcaptions(prodid){					// change the units of the column captions
  var wb = document.getElementById('wbdims_' + prodid).value;		// width / breadth dimensions chosen
  var lcaption = 'Length M';						// default values
  var wcaption = 'Width M';
  var dcaption = 'Depth cm';
  if ( wb == 'Feet' ) 
    { 
    lcaption = 'Length ft';
    wcaption = 'Width ft';
    }
  else if ( wb == 'Yards' ) 
    { 
    lcaption = 'Length yd';
    wcaption = 'Width yd';
    }
  var d = document.getElementById('ddims_' + prodid).value;		// depth dimensions chosen
  if ( d == 'Inches' ) 
    { 
    dcaption = 'Depth in';
    }
  document.getElementById('lcaption_' + prodid).innerHTML = lcaption;
  document.getElementById('wcaption_' + prodid).innerHTML = wcaption;
  document.getElementById('dcaption_' + prodid).innerHTML = dcaption;
}


function setturfcaptions(prodid){					// change the units of the column captions
  var wb = document.getElementById('wbdims_' + prodid).value;		// width / breadth dimensions chosen
  var lcaption = 'Length M';						// default values
  var wcaption = 'Width M';
  if ( wb == 'Feet' ) 
    { 
    lcaption = 'Length ft';
    wcaption = 'Width ft';
    }
  else if ( wb == 'Yards' ) 
    { 
    lcaption = 'Length yd';
    wcaption = 'Width yd';
    }
  document.getElementById('lcaption_' + prodid).innerHTML = lcaption;
  document.getElementById('wcaption_' + prodid).innerHTML = wcaption;
}

function calcvol(prodid, length, width, depth, vol){			// calculate one line of the area matrix
  var wb = document.getElementById('wbdims_' + prodid).value;		// width / breadth dimensions chosen
  var wbfactor = 1;							// metric value
  if ( wb == 'Feet' ) 
    { 
    wbfactor = 0.3048;							// 1 ft in M 
    }
  else if ( wb == 'Yards' ) 
    { 
    wbfactor = 0.9144;							// 1 Yard in M
    }
  var d = document.getElementById('ddims_' + prodid).value;		// depth dimensions chosen
  var dfactor = 0.01;							// metric value (cm)
  if ( d == 'Inches' ) 
    { 
    dfactor = 0.0254; 							// 1 inch in M
    }
  // now calculate the volume
  var totvol = to2digits((checknum(prodid, length) * wbfactor) * (checknum(prodid, width) * wbfactor) * (checknum(prodid, depth) * dfactor));
  document.getElementById(vol + '_' + prodid).value = totvol;			// save result (2 digits worth)
  return totvol - 0;							// and return numeric value
}
 
function soilcalc(item, incart){						// something has changed so recalculate everything
 //var prodid = item.id.replace(/.*_/, '');				// extract product ID
  var prodid = item.replace(/.*_/, '');				// extract product ID
  setsoilcaptions(prodid);						// in case units changed
  var price = document.getElementById('pri_' + prodid).value;		// the product unit price
  var toomany = false;
  document.getElementById('tc_' + prodid).value = '';			// clear grand totals
  document.getElementById('Q_' + prodid).value = '';
  var bagssel = document.getElementById('bagsreqd_' + prodid).value - 0;// get the number of bags

  if ( bagssel > 0 )							// we have a pre-set amount
    {
    var totbags = bagssel;						// we have a valid pre-set number of bags
    }
  else									// otherwise: have to make the volume calculation
    {
    var totvol = 0; 							// our total volume
    totvol += calcvol(prodid,'al', 'aw', 'ad', 'av');			// get each line of calulation
    totvol += calcvol(prodid,'bl', 'bw', 'bd', 'bv');
    totvol += calcvol(prodid,'cl', 'cw', 'cd', 'cv');
    totvol += calcvol(prodid,'dl', 'dw', 'dd', 'dv');
    var totbags = Math.ceil(totvol * TonsPerCubicMetre);		// calc # ton bags
    document.getElementById('tv_' + prodid).value = to2digits(totvol);	// set total volume
    }

  document.getElementById('Q_' + prodid).value = totbags;		// show number of bags
  var allbags = price * totbags;					// product cost
  var gtotal = to2digits(allbags);					// make pretty
  document.getElementById('tc_' + prodid).value =  gtotal;		// display total

  if ( totbags > MaxSoilOrder ) toomany = true;				// unless it's the more than MaxSoilOrder option

  if ( toomany )
    { 
    showmessage('Your order is too large to process on-line.\n'
                + 'Maximum is ' + MaxSoilOrder
                + ' tonnes. Please call ' +  PhoneNo + '.');		// tell customer why.
    }

  if ( (totbags == 0) && (incart == true) )				// nothing there and adding to cart?
    {
    showmessage('Order quantity is 0!');				// tell customer why.
    toomany = true;							// and inhibit cart
    }

  if ( diags )  // diagnostic display - remove later
    {
    document.getElementById('info_' + prodid).value = 'Test1';
    document.getElementById('info2_' + prodid).value =  'Test2';
    }

  return (! toomany);
} 
 
function calcarea(prodid, length, width, vol){				// calculate one line of the area matrix
  var wb = document.getElementById('wbdims_' + prodid).value;		// width /  dimensions chosen
  var wbfactor = 1;							// metric value
  if ( wb == 'Feet' ) 
    { 
    wbfactor = 0.3048;							// 1 ft in M 
    }
  else if ( wb == 'Yards' ) 
    { 
    wbfactor = 0.9144;							// 1 Yard in M
    }
  // now calculate the volume
  var totarea = Math.ceil( (checknum(prodid, length) * wbfactor) * (checknum(prodid, width) * wbfactor) );
  document.getElementById(vol + '_' + prodid).value = totarea;		// save result
  return totarea;							// and return numeric value
}
 
function turfcalc(item, incart){						// something has changed so recalculate everything
//var prodid = item.id.replace(/.*_/, '');				// extract product ID
 var prodid = item.replace(/.*_/, '');				// extract product ID
  setturfcaptions(prodid);						// in case units changed
  var toomany = false;
  var price = document.getElementById('pri_' + prodid).value;		// the product unit price
  document.getElementById('tc_' + prodid).value = '';			// clear grand totals
  var bagssel = document.getElementById('turfarea_' + prodid).value - 0;// get the number of bags

  if ( bagssel > 0 )							// we have a pre-set amount
    {
    var totturfarea = bagssel;						// we have a valid pre-set number of bags
    }
  else									// otherwise: have to make the volume calculation
    {
    var totvol = 0; 							// our total volume
    totvol += calcarea(prodid, 'al', 'aw', 'av');			// get each line of calulation
    totvol += calcarea(prodid, 'bl', 'bw', 'bv');
    totvol += calcarea(prodid, 'cl', 'cw', 'cv');
    totvol += calcarea(prodid, 'dl', 'dw', 'dv');
	var TotalTurfWastage = Math.ceil(totvol * TurfWastage);
    var totturfarea = Math.ceil(totvol + TotalTurfWastage);			// add in wastage
    }

  document.getElementById('Q_' + prodid).value = totturfarea;		// set total area
  var allbags = price * totturfarea;					// calculated product cost
  var gtotal = to2digits(allbags);					// make pretty
  document.getElementById('tc_' + prodid).value =gtotal;		// display total

  if ( totturfarea > MaxTurfOrder ) toomany = true;			// unless it's the More than MAX option

  if ( toomany )							// too many?
    {
    showmessage('Your order is too large to process on-line.\n'
              + 'Maximum is ' + MaxTurfOrder
              + ' Square Metres. Please call ' +  PhoneNo + '.');	// tell customer why.
    }

  if ( (totturfarea == 0) && (incart == true) )				// nothing there and adding to cart?
    {
    showmessage('Order quantity is 0!');				// tell customer why.
    toomany = true;							// and inhibit cart
    }

  // diagnostic display - remove later
  if ( diags )
    {
    document.getElementById('info').value = 'Diag1';
    document.getElementById('info2').value = 'Diag2';
    }

  return (! toomany); 
} 

function enableentryfields(prodid, fieldlist){				// enable all user input fields
  for ( var i=0; i < fieldlist.length; i++ )
    {
    document.getElementById(fieldlist[i] + '_' + prodid).disabled = false;
    }   
 }
 
function disableentryfields(prodid, fieldlist){				// disable all user input fields
  for ( var i=0; i < fieldlist.length; i++ )
    {
    document.getElementById(fieldlist[i] + '_' + prodid).disabled = true;
    }   
 }
 
function soilsetoverride(item){						// check whether we want N bags or our own calculation
 // var prodid = item.id.replace(/.*_/, '');				// extract product ID
  var prodid = item.replace(/.*_/, '');				// extract product ID
  
  var val = document.getElementById('bagsreqd_' + prodid).value;
  
  if ( val == '0' )							// we want to calculate
    {
    enableentryfields(prodid, soilentryfields);
    soilcalc(item);
    }
  else 									// pre set number of bags
    {
    disableentryfields(prodid, soilentryfields)
    soilcalc(item);							// calculate using preset number
    }
} 

function turfsetoverride(item){						// check whether we want N bags or our own calculation
  //var prodid = item.id.replace(/.*_/, '');				// extract product ID
  var prodid = item.replace(/.*_/, '');				// extract product ID
  var val = document.getElementById('turfarea_' + prodid).value;
  if ( val == '0' )							// we want to calculate
    {
    enableentryfields(prodid, turfentryfields);
    turfcalc(item);
    }
  else 									// pre set number of bags
    {
    disableentryfields(prodid, turfentryfields);
    turfcalc(item);							// calculate using preset number
    }
}

function calc_order()
{
	
	// Turf
	if(document.getElementById('tu_pr').value != 0 || document.getElementById('tu_pr').value != ''  )
	{
		document.getElementById('Turf_Premier').value = Math.abs(document.getElementById('tu_pr').value * 2.65);
	}
	else
	{
		document.getElementById('Turf_Premier').value = 0;
	}
	
	
	if(document.getElementById('tu_st').value != 0 || document.getElementById('tu_st').value != ''  )
	{
		document.getElementById('Turf_Standard').value = Math.abs(document.getElementById('tu_st').value * 2.15);
	}
	else
	{
		document.getElementById('Turf_Standard').value	= 0;
	}
	
	if(document.getElementById('tu_ec').value != 0 || document.getElementById('tu_ec').value != ''  )
	{
		 document.getElementById('Turf_Econimix').value = Math.abs(document.getElementById('tu_ec').value * 1.95);
	}
	else
	{
		document.getElementById('Turf_Econimix').value = 0;	
	}
	
	//Topsoil
	if(document.getElementById('to_bo').value != 0 || document.getElementById('to_bo').value != ''  )
	{
		 document.getElementById('Topsoil_Bordermix').value = Math.abs(document.getElementById('to_bo').value * 57.50);
	}
	else
	{
		document.getElementById('Topsoil_Bordermix').value = 0;	
	}
	
	if(document.getElementById('to_st').value != 0 || document.getElementById('to_st').value != ''  )
	{
		 document.getElementById('Topsoil_Standard').value = Math.abs(document.getElementById('to_st').value * 45.00);
	}
	else
	{
		document.getElementById('Topsoil_Standard').value = 0;	
	}
	
	if(document.getElementById('to_mu').value != 0 || document.getElementById('to_mu').value != ''  )
	{
		 document.getElementById('Topsoil_Mushroom').value = Math.abs(document.getElementById('to_mu').value * 67.50);
	}
	else
	{
		document.getElementById('Topsoil_Mushroom').value = 0;	
	}

	if(document.getElementById('to_la').value != 0 || document.getElementById('to_la').value != ''  )
	{
		 document.getElementById('Topsoil_Landscape').value = Math.abs(document.getElementById('to_la').value * 77.50);
	}
	else
	{
		document.getElementById('Topsoil_Landscape').value = 0;	
	}
	
	//Fertilizers
	if(document.getElementById('fe_20kg').value != 0 || document.getElementById('fe_20kg').value != ''  )
	{
		 document.getElementById('Fertilizers_20kg').value = Math.abs(document.getElementById('fe_20kg').value * 27.50);
	}
	else
	{
		document.getElementById('Fertilizers_20kg').value = 0;	
	}
	
	if(document.getElementById('fe_10kg').value != 0 || document.getElementById('fe_10kg').value != ''  )
	{
		 document.getElementById('Fertilizers_10kg').value = Math.abs(document.getElementById('fe_10kg').value * 17.50);
	}
	else
	{
		document.getElementById('Fertilizers_10kg').value = 0;	
	}
	
	var total = 0;
	
	total += Math.abs(document.getElementById('Turf_Premier').value); 
	total += Math.abs(document.getElementById('Turf_Standard').value); 
	total += Math.abs(document.getElementById('Turf_Econimix').value); 
	
	total += Math.abs(document.getElementById('Topsoil_Bordermix').value); 
	total += Math.abs(document.getElementById('Topsoil_Standard').value); 
	total += Math.abs(document.getElementById('Topsoil_Mushroom').value); 
	total += Math.abs(document.getElementById('Topsoil_Landscape').value); 
	
	total += Math.abs(document.getElementById('Fertilizers_20kg').value); 
	total += Math.abs(document.getElementById('Fertilizers_10kg').value); 
	
	total += Math.abs(document.getElementById('shipping').value); 
	
	document.getElementById('total').value = total; 
	
	/*alert(document.getElementById('Turf_Premier').value);
	alert(document.getElementById('Turf_Standard').value);
	alert(document.getElementById('Turf_Econimix').value);
	*/
	
	
	
	
	
}