var menuitems = [];



// updatePrices()
// Updates all the prices and totals on the order form
// Pre:
//    - global variable menuitems has been defined
function updatePrices()
{
  // get the order form
  var form = document.getElementById('order');
  
  
  
  // only generate order ID if they don't already have one
  if(form.orderid.value == '0')
  {
    // get random number
    var ranNum = Math.floor(Math.random()*1001);
    var dt = new Date();
    
    // build order ID
    var id = dt.getFullYear() + lz(dt.getMonth() + 1, 2) + lz(dt.getDate(), 2) + lz(ranNum, 4);
    
    // store order ID in the form
    form.orderid.value = id;
  }
  
  
  
  // clear output
  var email =
    'River City Catering New Order Request (' + form.orderid.value + ')\n' +
    'Name: ' + form.fullname.value + '\n' +
    'Phone: ' + form.phone.value + '\n' +
    'Email: ' + form.email.value + '\n' +
    'Event Address: ' + form.address.value + '\n' +
    'Event Date: ' + form.date.value + '\n\n' +
    'Menu Item Selections:\n';
  
  
  
  // Set variables
  var qty = 0;
  var totalqty = 0;
  var price = 0;
  var extraprice = 0;
  var total = 0;
  var subtotal = 0;
  var name = '';
  
  
  // loop through menu items
  for(var i = 0; i < menuitems.length; i++)
  {
    // get all the table cells for this menu item
    // 0: description
    // 1: price
    // 2: quantity
    // 3: subtotal
    var cells = getTableCells(menuitems[i]);
    
    
    // get name of menu item from heading
    name = cells[0].getElementsByTagName('h4')[0].innerHTML;
    
    
    // get the menu item base price
    price = cells[1].innerHTML.substr(1).split('<')[0] * 1;
    extraprice = 0;
    
    
    // get the quantity of menu items
    qty = cells[2].getElementsByTagName('input')[0].value * 1;
    
    // make sure quantity is a number
    if(isNaN(qty))
    {
      // if not, set it to zero
      cells[2].getElementsByTagName('input')[0].value = qty = 0;
    }
    
    
    
    var subemail = "";
    
    var submenuitems = menuitems[i].getElementsByTagName('select');
    
    // loop over each submenu choice
    for(var j = 0; j < submenuitems.length; j++)
    {
      var submenuitem = submenuitems[j];
      
      // check for extra costs
      if(submenuitem.value.indexOf('$1') > -1)
      {
        extraprice += 1;
      }
      else if(submenuitem.value.indexOf('$2') > -1)
      {
        extraprice += 2;
      }
      
      if(qty > 0)
      {
        // add submenu choice to the email
        subemail += '- ' + submenuitem.value + '\n';
      }
    }
    
    
    
    // if quantity is greater than 0 then change the row style
    if(qty > 0)
    {
      // row style for chosen menu items
      menuitems[i].className = 'odd';
      
      // subtotal calculation
      subtotal = qty * (price + extraprice);
      
      // add menu item to email
      email += qty + ' x ' + name + ' ($' + price + ') = $' + 
           subtotal.toFixed(2) + '\n';
      email += subemail;
      
      // update total quantity
      totalqty += qty;
    }
    else
    {
      // regular row style
      menuitems[i].className = 'even';
      
      subtotal = 0;
    }
    

    // add subtotal to the grand total
    total += subtotal;
    
    // update the price field
    cells[1].innerHTML = '$' + price.toFixed(2) +
               (extraprice > 0 ?
                '<br>+ $' + extraprice.toFixed(2) : '');
    
    // update the subtotal
    cells[3].innerHTML = '$' + subtotal.toFixed(2);
    
  }
  
  
  // set the grand total
  
  var salestax = 0;
  
  if(total > 0)
  {
    salestax = total * 0.095;   // calculate tax
  }
  
  // display subtotal and sales tax
  document.getElementById("subtotal").innerHTML = '$' + total.toFixed(2);
  document.getElementById("salestax").innerHTML = '$' + salestax.toFixed(2);
  
  // add tax to total
  total += salestax;
  
  // display grand total
  document.getElementById("grandtotal").innerHTML = '$' + total.toFixed(2);
  form.total.value = total.toFixed(2);
  
  email += "\nGrand Total: $" + total.toFixed(2) + "\n(Includes tax)";
  
  form.emailbody.value = email;
  
  return totalqty;
}



// lz()
// Prepend a number n with leading zeros until it is the given length
function lz(n, length)
{
  n = '' + n;
  
  while(n.length < length)
  {
    n = '0' + n;
  }
  
  return n;
}



// resetOrder()
// Resets order form and updates prices
function resetOrder()
{
  // use timeout so the prices are updated after form reset
  setTimeout('updatePrices()', 0);
}



// submitOrder()
// Checks errors and submits form
function submitOrder()
{
  form = document.getElementById('order');
  
  var totalqty = updatePrices();
  
  var errCol = '#ff9999';
  var bgCol = '#ffffff'
  var critErr = 0;
  var exitFlg = 0;
  var errMsg = 'Errors were found in your order:\n\n';

  // Full name
  if(form.fullname.value == '' || form.fullname.value == null)
  {
    form.fullname.style.backgroundColor = errCol;
    critErr = 1;
  }
  else
  {
    form.fullname.style.backgroundColor = bgCol;
  }
  
  // Phone Number
  if(form.phone.value == '' || form.phone.value == null)
  {
    form.phone.style.backgroundColor = errCol;
    critErr = 1;
  }
  else
  {
    form.phone.style.backgroundColor = bgCol;
  }
  
  // Email address
  if(form.email.value == '' || form.email.value == null) 
  {
    form.email.style.backgroundColor = errCol;
    critErr = 1;
  }
  else 
  {
    form.email.style.backgroundColor = bgCol;
  }
  
  // Event address
  if(form.address.value == '' || form.address.value == null) 
  {
    form.address.style.backgroundColor = errCol;
    critErr = 1;
  }
  else 
  {
    form.address.style.backgroundColor = bgCol;
  }
  
  // Event date
  if(form.date.value == '' || form.date.value == null)
  {
    form.date.style.backgroundColor = errCol;
    critErr = 1;
  }
  else
  {
    form.date.style.backgroundColor = bgCol;
  }
  
  
  
  // check if grand total is 0
  if (form.total.value == "0.00" || totalqty == 0)
  {
    critErr += 2;
  }
  
  
  
  // print output
  if(critErr > 1)
  {
    exitFlg = 1;
    errMsg += "You did not specify any items in your order.\n";
    critErr -= 2;
  }
  if(critErr > 0)
  {
    exitFlg = 1;
    errMsg += "You failed to enter required fields. These fields have been highlighted.\n";
  }
  
  if(exitFlg == 1)
  {
    form.fullname.focus();
    alert(errMsg + "\nPlease correct these errors and resubmit your order.");
    return false;
  }

  return true;
}



// getTableCells()
// Returns all table cells in an array within a given table row
function getTableCells(tablerow)
{
  cells = [];
  
  if(tablerow)
  {
    for(var i = 0; i < tablerow.childNodes.length; i++)
    {
      if(tablerow.childNodes[i].nodeType == 1 &&
         tablerow.childNodes[i].nodeName == 'TD')
      {
        cells.push(tablerow.childNodes[i]);
      }
    }
  }
  
  return cells;
}



// loadEvents()
// Loads events for form elements to update the prices
// Pre:
//    - getElementsByClassName() exists
//      (included from getElementsByClassName-1.0.1.js)
function loadEvents()
{
  // get the order form
  var form = document.getElementById('order');
  
  // get all drop down menus
  var selects = form.getElementsByTagName('select');
  
  // get all quantity fields
  var quantities = getElementsByClassName('quantity', 'input', form);
  
  // loop over each drop down
  for(var i = 0; i < selects.length; i++)
  {
    // set it to update prices when changed
    selects[i].onchange = updatePrices;
  }
  
  // loop over each quantity field
  for(var i = 0; i < quantities.length; i++)
  {
    // set it to update prices when a key is pressed
    quantities[i].onkeyup = updatePrices;
  }
}



// init()
// Initializes some things for the order form
function init()
{
  // get the order form
  var form = document.getElementById('order');
  
  // set submit and reset events
  form.onsubmit = submitOrder;
  form.onreset = resetOrder;
  
  // get all the menu items
  menuitems = getElementsByClassName('menuitem', 'tr', form);
}
