// THESE VARIABLES SHOULD BE DEFINED GLOBALLY:
// optionalText: the text that is the 1st option of an optional select (e.g. '(optional)')
// itemPrice: the base price of the item
// orderFrm: the element (NOT THE ID!) of the order form
var orderFrm = document.orderForm;
// updateId: the id of the <span> or <div> that will hold the text (toggle visibilty)
var updateEl = document.getElementById('updatedPriceText');
// updateIdPrice: the id of the <span> that holds the actual price
var updateElPrice = document.getElementById('updatedPrice');
// updateElBase: the element <span> that holds the base price
var updateElBase = document.getElementById('basePriceText');
 
function insertPriceText(optAmt, baseAmt) {
  var total = optAmt + baseAmt + itemPrice;
  if ((optAmt>=.01) || (updateElPrice.innerHTML.length>0)) {
    updateElPrice.innerHTML = (total.toFixed(2));
    updateEl.style.visibility='visible';
  }
  var baseTotal = itemPrice+baseAmt;
  updateElBase.innerHTML = '$'+(baseTotal.toFixed(2));
}

function removeOptional(frm) {
  var inputs = frm.getElementsByTagName('select');
  for (var i=0; i<inputs.length; i++)
    if (inputs[i].value==optionalText) {
      inputs[i].parentNode.removeChild(inputs[i]);
    }
  return true;
}
function updatePriceHandlers() {
  var inputs = orderFrm.getElementsByTagName('select');
  for (var i=0; i<inputs.length; i++) {
    var inp = inputs[i];
    inp.onchange=function() {
      insertPriceText(updateOptionsPrice(orderFrm), updateBasePrice(orderFrm));
    }
  }
}
function updateOptionsPrice(frm) {
  var inputs = frm.getElementsByTagName('select');
  var amt = 0;
  for (var i=0; i<inputs.length; i++) {
    var firstOptionValue = inputs[i].options[0].value;  
    var value = inputs[i].value;
    var loc = value.indexOf('(+');
    if ((loc >= 0) && (firstOptionValue==optionalText)) {
      do {
        if ((value.charAt(loc)*1)>0) {
          amt += parseFloat(value.substring(loc));
          break;
        }
        loc++;
      } while (value.charAt(loc));
    }
  }
  return amt;
}

insertPriceText(updateOptionsPrice(orderFrm), updateBasePrice(orderFrm));
updatePriceHandlers();

function updateBasePrice(frm) {
  var inputs = frm.getElementsByTagName('select');
  var amt = 0;
  for (var i=0; i<inputs.length; i++) {
    var firstOptionValue = inputs[i].options[0].value;
    var value = inputs[i].value;
    var loc = value.indexOf('(+');
    if ((loc >= 0) && (firstOptionValue!=optionalText)) {
      do {
        if ((value.charAt(loc)*1)>0) {
          amt += parseFloat(value.substring(loc));
          break;
        }
        loc++;
      } while (value.charAt(loc));
    }
  }
  return amt;
}
