/*
 * Here's where you define categories and their discounts
 * Format:
 * 'category label' : discount [%]
 * The discount must be a number
 */
var categories = {
  'Medical Gas' : 30,
  'Dental Supplies (Darby)' : 18,
  'Office Supplies' : 30,
  'Computers and Printers' : 10,
  'Loupes and Headlights' : 15,
  'Medical Waste Services' : 40,
  'Defibrillators' : 33,
  'Web Design and Hosting' : 25,
  'Enzyme Cleaners' : 15,
  'Dental Instruments' : 40
 
};
/**
 * Displays a form with an input element for each category and a div that will show the savings
 */
function displaySavingsForm() {
  document.writeln('<form onSubmit="return false;">');
  var i = 0;
  for (var categoryLabel in categories) {
    var discount = categories[categoryLabel];
    document.writeln('<p><label>'+categoryLabel+':<br>');
    document.writeln('<input type="text" name="categoryAmount'+i+'" value="" id="valueElement'+i+'"'+
      ' onKeyUp="calculateSavings('+i+', '+discount+');"'+
      '><br>');
    document.writeln('Savings: $<span id="savingElement'+i+'"></span></label></p>');
    i++;
  }
  document.writeln('<p><b>Total Estimated UDA Savings: $<span id="totalSavingsElement"></span></b></p>');
  document.writeln('</form>');
  
  sumUpSavings(true);
  // calculate savings after page refresh - will not work in MSIE anyway, the value is simply not present
}
/**
 * Called upon entering the amount to calculate savings from
 */
function calculateSavings(i, discount) {
  var value = document.getElementById('valueElement'+i).value;
  var savings = '';
  
  /*
   * Calculate this category's saving
   */
  if (isFinite(value)) {
    savings = Math.round((discount/100) * value * 100)/100;
    // calculate the percentage and round to two decimal places
  }
  
  /*
   * Display the saving 
   */
  document.getElementById('savingElement'+i).innerHTML = savings;
  sumUpSavings(false);
}
/**
 * Go through all other savings and sum them up
 */
function sumUpSavings(calculateAllSavings) {
  var i = 0;
  var totalSavings = 0;
  for (var categoryLabel in categories) {
    /*
     * Run the calculation function if requested
     */
    if (calculateAllSavings) {
      calculateSavings(i, categories[categoryLabel]);
    }
    
    var categorySaving = document.getElementById('savingElement'+i).innerHTML;
    if (!isNaN(parseFloat(categorySaving))) {
      totalSavings += parseFloat(categorySaving);
    }
    i++;
  }
  /*
   * Round the total
   */
  totalSavings = Math.round(totalSavings * 100) / 100;
  
  /*
   * Display the total savings
   */
  document.getElementById('totalSavingsElement').innerHTML = totalSavings;
}
/*
 * Run the function to actually display the form with categories and input boxes
 */
displaySavingsForm();

