// how much for each unit
var kitCost = 116.00;

// the order form iteself
var kitOrderForm;

// holds the value for the total order
var orderTotal = 0.00;

// submit image
var submitImg;

// variables for the form elements
var smallQty, mediumQty, largeQty, xLargeQty, shippingMethod;

// variables for the form elements
var smallCost, mediumCost, largeCost, xLargeCost, shippingCost, totalCost;

/**
* Determine the tax and add the value to the form
*/
function addTax() {
  var hidTax = document.createElement('INPUT');
  if (hidTax.setAttribute) {
    var tax = 0.00;
    tax = parseInt(orderTotal) * 0.06;
    hidTax.setAttribute('name', 'tax_cart');
    hidTax.setAttribute('type', 'hidden');
    hidTax.setAttribute('value', tax);
    kitOrderForm.appendChild(hidTax);
  }
}

/**
* Add Input for the shipping cost
*/
function addShipping() {
  var hidShipping = document.createElement('INPUT');
  if (hidShipping.setAttribute) {
    hidShipping.setAttribute('name', 'shipping_1');
    hidShipping.setAttribute('type', 'hidden');
    hidShipping.setAttribute('value', getShippingCost());
    kitOrderForm.appendChild(hidShipping);
  }
}

/**
* Added hidden inputs to the form for each item in the cart
*/
function addHiddenItem(name, qty, itemNum) {
  var hidAmount = document.createElement('INPUT');
  var hidName = document.createElement('INPUT');
  var hidQty = document.createElement('INPUT');
  if (hidName.setAttribute) {
    hidAmount.setAttribute('name', 'amount_' + itemNum);
    hidAmount.setAttribute('type', 'hidden');
    hidAmount.setAttribute('value', kitCost);

    hidName.setAttribute('name', 'item_name_' + itemNum);
    hidName.setAttribute('type', 'hidden');
    hidName.setAttribute('value', name);

    hidQty.setAttribute('name', 'quantity_' + itemNum);
    hidQty.setAttribute('type', 'hidden');
    hidQty.setAttribute('value', qty);

    // stupid paypal has shipping all fucked up. i can't overide the whole order shipping for some reason so i'll have to force it for the first item
    var sh = getShippingCost();
    if (itemNum == 1 && !isNaN(sh)) {
      addShipping(sh);
    }

    kitOrderForm.appendChild(hidAmount);
    kitOrderForm.appendChild(hidName);
    kitOrderForm.appendChild(hidQty);
  }
}

/**
* Added hidden inputs to the form for each item in the cart
*/
function addItemsToForm() {
  var itemCount = 1;

  // small kits
  if (!isNaN(parseInt(smallQty.value)) && parseInt(smallQty.value) > 0) {
    addHiddenItem('Small Kit', parseInt(smallQty.value), itemCount);
    itemCount++;
  }

  // medium kits
  if (!isNaN(parseInt(mediumQty.value)) && parseInt(mediumQty.value) > 0) {
    addHiddenItem('Medium Kit', parseInt(mediumQty.value), itemCount);
    itemCount++;
  }

  // large kits
  if (!isNaN(parseInt(largeQty.value)) && parseInt(largeQty.value) > 0) {
    addHiddenItem('Large Kit', parseInt(largeQty.value), itemCount);
    itemCount++;
  }

  // x-large kits
  if (!isNaN(parseInt(xLargeQty.value)) && parseInt(xLargeQty.value) > 0) {
    addHiddenItem('X-Large Kit', parseInt(xLargeQty.value), itemCount);
    itemCount++;
  }
}

/**
* Make sure all qty inputs are enabled
*/
function enableFormElements() {
  if (smallQty.disabled) {smallQty.disabled = false;}
  if (mediumQty.disabled) {mediumQty.disabled = false;}
  if (largeQty.disabled) {largeQty.disabled = false;}
  if (xLargeQty.disabled) {xLargeQty.disabled = false;}
  if (shippingMethod.disabled) {shippingMethod.disabled = false;}
}

/**
* Locate all form elements in the document
*/
function findFormElements() {
  smallQty = getElm('smallQty');
  mediumQty = getElm('mediumQty');
  largeQty = getElm('largeQty');
  xLargeQty = getElm('xLargeQty');
  shippingMethod = getElm('shippingMethod');
}

/**
* Locate all table cells that hold item totals
*/
function findTableCells() {
  smallCost = getElm('smallCost');
  mediumCost = getElm('mediumCost');
  largeCost = getElm('largeCost');
  xLargeCost = getElm('xLargeCost');
  shippingCost = getElm('shippingCost');
  totalCost = getElm('totalCost');
}

/**
* get the shipping cost from the select box
*/
function getShippingCost() {
  var curVal = shippingMethod.options.item(shippingMethod.selectedIndex).value;
  if (isNaN(parseInt(curVal))) {
    curVal = '';
  } else if (curVal == '0.00') {
    curVal = 0.00;
  } else {
    curVal *= 1;
  }
  return curVal;
}

/**
* take a number and format it for US currency
*/
function makeMoney(num) {
  num -= 0;
  num = (Math.round(num * 100)) / 100;
  return (num==Math.floor(num)) ? num+'.00' : ((num * 10==Math.floor(num * 10)) ? num+'0' : num);
}

/**
* run through all sizes and shipping to calculate the order total
*/
function updateOrderTotal() {
  var smallTotal = (smallQty.value - 0) * kitCost;
  var mediumTotal = (mediumQty.value - 0) * kitCost;
  var largeTotal = (largeQty.value - 0) * kitCost;
  var xLargeTotal = (xLargeQty.value - 0) * kitCost;
  var shippingTotal = getShippingCost();
  if (isNaN(parseInt(shippingTotal))) {
    shippingTotal = 0;
  }
  totalCost.innerHTML = '$' + makeMoney(smallTotal + mediumTotal + largeTotal + xLargeTotal + shippingTotal);

  // keep track of the order total
  orderTotal = smallTotal + mediumTotal + largeTotal + xLargeTotal - 0;
}

/**
* Update an items total on change
*/
function updateItemOnChange(e) {
  var elm;
  if (typeof e.target == 'object') {
    elm = e.target;
  } else if (typeof e.srcElement == 'object') {
    elm = e.srcElement;
  }

  if (elm) {
    // get the form value
    var qtyVal = elm.value;

    // make sure it's a number and > 0
    if (isNaN(parseInt(qtyVal))) {
      qtyVal = 0;
    } else if (qtyVal < 0) {
      qtyVal = 0;
    }

    if (qtyVal > 0) {
      elm.myCostCell.innerHTML = '$' + makeMoney(qtyVal * kitCost);
    } else {
      elm.myCostCell.innerHTML = '-';
    }

    // make it look nice (remove leading zeros and make <0 numbers just 0)
    elm.value = (qtyVal * 1);

    // now update the order total
    updateOrderTotal();
  }
}

/**
* Update the shipping method
*/
function updateShipping(e) {
  var elm;
  if (typeof e.target == 'object') {
    elm = e.target;
  } else if (typeof e.srcElement == 'object') {
    elm = e.srcElement;
  }

  if (elm) {
    // get the form value
    var shipCost = getShippingCost();

    // make sure it's a number and > 0
    if (isNaN(parseInt(shipCost))) {
      elm.myCostCell.innerHTML = '-';
    } else {
      elm.myCostCell.innerHTML = '$' + makeMoney(shipCost);
    }

    // now update the order total
    updateOrderTotal();
  }
}

/**
* Assign an event listener for change on each input element
*/
function listenForChange(elm) {
  if (elm.addEventListener) {
    elm.addEventListener('change', updateItemOnChange, false);
  } else if (elm.attachEvent) {
    elm.attachEvent('onchange', updateItemOnChange);
  } else if (elm.onchange) {
    elm.onchange = updateItemOnChange;
  }
}

/**
* Listen for a change in shipping method
*/
function listenForShipping(elm) {
  if (elm.addEventListener) {
    elm.addEventListener('change', updateShipping, false);
  } else if (elm.attachEvent) {
    elm.attachEvent('onchange', updateShipping);
  } else if (elm.onchange) {
    elm.onchange = updateShipping;
  }
}

/**
* Get and element by it's id attribute
*/
function getElm(elmId) {
  var elm;

  if (document.getElementById) {
    elm = document.getElementById(elmId);
  } else if (document.all) {
    elm = document.all[elmId];
  }

  return elm;
}

/**
* change the img for the submit img
*/
function turnSubmitOn(e) {
  var elm;
  if (typeof e.target == 'object') {
    elm = e.target;
  } else if (typeof e.srcElement == 'object') {
    elm = e.srcElement;
  }

  elm.src = 'images/order/order-over.jpg';
}

/**
* change the img for the submit img
*/
function turnSubmitOff(e) {
  var elm;
  if (typeof e.target == 'object') {
    elm = e.target;
  } else if (typeof e.srcElement == 'object') {
    elm = e.srcElement;
  }

  elm.src = 'images/order/order-12.jpg';
}

/**
* check the form and submit if it passes
*/
function submitForm() {
  // make sure at least one item is ordered
  var itemsOk = false;
  var smallTotal = (smallQty.value - 0) * kitCost;
  var mediumTotal = (mediumQty.value - 0) * kitCost;
  var largeTotal = (largeQty.value - 0) * kitCost;
  var xLargeTotal = (xLargeQty.value - 0) * kitCost;
  if (smallTotal + mediumTotal + largeTotal + xLargeTotal == 0) {
    alert('Please select at least one item');
  } else {
    itemsOk = true;
  }

  // make sure a shipping method is selected
  if (itemsOk) {
    var shippingOk = false;
    var shipCost = getShippingCost();
    if (!isNaN(parseInt(shipCost))) {
      shippingOk = true;
    } else {
      alert('Please select a Shipping Method');
    }

    // submit form
    if (shippingOk) {
      // add the hidden inputs for each item ordered
      addItemsToForm();

      // add the hidden inputs for each item ordered
      //addTax();

      // add a hidden input for the shipping cost
      //addShipping();

      // send them off to PayPal
      kitOrderForm.submit();
    }
  }
}

/**
* setup rollover and click events for submit img
*/
function listenToSubmit() {
  submitImg = getElm('submitImg');

  if (submitImg.addEventListener) {
    submitImg.addEventListener('mouseover', turnSubmitOn, false);
    submitImg.addEventListener('mouseout', turnSubmitOff, false);
    submitImg.addEventListener('click', submitForm, false);
  } else if (submitImg.attachEvent) {
    submitImg.attachEvent('onmouseover', turnSubmitOn);
    submitImg.attachEvent('onmouseout', turnSubmitOff);
    submitImg.attachEvent('onclick', submitForm);
  } else {
    alert('This form will not work with your browser. Please update to the latese version of your browser and verify that JavaScript is enabled.');
  }
}

function setupForm(e) {
  // get the form
  kitOrderForm = getElm('kitOrderForm');

  // get all of the form elements
  findFormElements();

  // get all of the table cells of the totals
  findTableCells();

  // add a reference for each table cell to it's respective form input
  smallQty.myCostCell = smallCost;
  mediumQty.myCostCell = mediumCost;
  largeQty.myCostCell = largeCost;
  xLargeQty.myCostCell = xLargeCost;
  shippingMethod.myCostCell = shippingCost;

  // listen to the qty inputs for change
  listenForChange(smallQty);
  listenForChange(mediumQty);
  listenForChange(largeQty);
  listenForChange(xLargeQty);
  listenForShipping(shippingMethod);

  // listen for the form submit
  listenToSubmit();

  // enable the inputs
  enableFormElements();
}

if (window.addEventListener) {
  window.addEventListener('load', setupForm, false);
} else if (window.attachEvent) {
  window.attachEvent('onload', setupForm);
} else {
  alert('Please use a modern browser and make sure that JavaScript is enabled.');
}