// Number.toFixed is broken in IE; this is a workaround
// cf. http://www.codingforums.com/showthread.php?t=102421
Number.prototype.toFixedRound=function(n) {
  var N = this;
  N = Math.round(N*Math.pow(10, n));
  N /= Math.pow(10, n);
  return(N.toFixed(n));
}

window.App = {

  // returns a String representing x rounded to 2 decimals, using "round up"
  // rather than "banker's rounding", for compatibility with S4T::Util->round2.
  // x can be a Number or String.
  round2: function(x) {
    return(Number(Number(x).toFixedRound(4) + "1").toFixedRound(2));
  }

};

window.checkQTY = function(what) {
  if ($splat(what.bulk).some(function(cb) { return cb.checked }))
    return true;
  alert('This item sells in different quantity packs. You must choose a quantity to proceed. Thank you.');
  return false;
}

window.addEvent('domready', function() {
  new Autocompleter.Request.JSON('s_title', '/go/suggest', {
    minLength: 1,
    maxChoices: 20,
    delay: 300,
    cache: true,
    width: 'auto',
    autoSubmit: true
  });
});

PriceDetails = function(props) {
  this.id = props.id;
  this.instant_savings_pct = props.instant_savings_pct;
  this.discount_pct = props.discount_pct;
  this.packs = props.packs;
  this.form = $('buy_' + this.id);
  this.find_bulk();
  this.find_options();
  var obj = this;
  window.addEvent('domready', function() { obj.update_options() });
  this.form.addEvent('submit', function() { return(obj.validate_form()) });
};

// validate form on submit, by ensuring that all required options are
// selected
PriceDetails.prototype.validate_form = function() {
  for (var i = 0; i < this.options.length; i++) {
    var select = this.options[i];
    if (select.getAttribute('required') == 'yes' && select.selectedIndex <= 0) {
      alert("Please select a value for '" + select.getAttribute('label') + "'");
      return(false);
    }
  }
  return(true);
}

// find option selects within the form, and set event handler for option changes
PriceDetails.prototype.find_options = function() {
  var obj = this;
  obj.options = obj.form.getElements('select').filter(function(item) { return item.name.match(/^opt_/) });
  obj.options.each(function(el) {
    el.addEvent('change', function() { obj.update_options() });
  });
}

// find bulk checkboxes corresponding to each pack size and sets event handlers
// for check box clicks
PriceDetails.prototype.find_bulk = function() {
  if (this.packs.length <= 1)
    return;
  var bulk = [];
  var obj = this;
  this.packs.each(function(pack) {
    var el = $("bulk_" + pack.id);
    if (el) {
      bulk.push(el);
      el.addEvent('click', function() { obj.bulk_selected(el) });
    }
  });
  this.bulk = bulk;
}

// called when one of the bulk check boxes is selected. deselects the other
// pack size and marks this one as current, then updates the pricing.
PriceDetails.prototype.bulk_selected = function(el) {
  var obj = this;
  obj.packs.each(function(pack) {
    input = $("bulk_" + pack.id);
    if (input) {
      var tr = input.getParent('tr');
      if (input == el) {
        input.checked = true;
        tr.addClass('current');
      }
      else {
        input.checked = false;
        tr.removeClass('current');
      }
    }
  });
  obj.update_pricing();
}

// calculates pricing for each pack based on current options, and then
// updates the pricing details
PriceDetails.prototype.update_options = function() {

  var obj = this;
  this.packs.each(function(pack) {
    // calculate each value per piece based on selected options
    var qty = Number(pack.qty);
    var our_price = Number(App.round2(Number(pack.our_price) / qty));
    var options_amt = Number(App.round2(obj.options_amt_per_unit()));
    var options_price = Number(App.round2(Number(our_price) + options_amt));
    var instant_savings_amt = Number(App.round2(options_price * Number(obj.instant_savings_pct) * -0.01));
    var instant_savings_price = Number(App.round2(options_price + instant_savings_amt));
    var discount_amt = Number(App.round2(instant_savings_price * Number(obj.discount_pct) * -0.01));
    var per_unit = Number(App.round2(instant_savings_price + discount_amt));

    // set pricing values per unit
    pack.per_unit = App.round2(per_unit);
    if ($('per_unit_' + pack.id)) $('per_unit_' + pack.id).innerHTML = pack.per_unit;

    // set pricing values per pack
    pack.options_amt = App.round2(options_amt * qty);
    pack.options_price = App.round2(options_price * qty);
    pack.instant_savings_amt = App.round2(instant_savings_amt * qty);
    pack.discount_amt = App.round2(discount_amt * qty);
    pack.you_pay = App.round2(pack.per_unit * qty);
    if ($('you_pay_' + pack.id)) $('you_pay_' + pack.id).innerHTML = pack.you_pay;
  });
  obj.update_pricing();
}

// updates pricing details for current pack entry
PriceDetails.prototype.update_pricing = function() {

  // find currently selected pack
  var pack = this.packs[0];
  this.packs.each(function(entry) {
    var input = $('bulk_' + entry.id);
    if (input && input.checked)
      pack = entry;
  });

  // update values not dependent on options
  if ($('base_price')) $('base_price').innerHTML = pack.base_price;
  if ($('on_sale_amt')) $('on_sale_amt').innerHTML = pack.on_sale_amt;
  if ($('cart_incentive_amt')) $('cart_incentive_amt').innerHTML = pack.cart_incentive_amt;
  if ($('our_price')) $('our_price').innerHTML = pack.our_price;
  if ($('options_amt')) $('options_amt').innerHTML = pack.options_amt;
  if ($('options_price')) $('options_price').innerHTML = pack.options_price;
  if ($('instant_savings_amt')) $('instant_savings_amt').innerHTML = pack.instant_savings_amt;
  if ($('discount_amt')) $('discount_amt').innerHTML = pack.discount_amt;
  if ($('you_pay')) $('you_pay').innerHTML = pack.you_pay;
}

// calculates options amount per unit from current drop-downs
PriceDetails.prototype.options_amt_per_unit = function() {
  var amt = 0;
  this.options.each(function(select) {
    var price = Number(select[select.selectedIndex].getAttribute('price'));
    amt += price;
  });
  return(amt);
}

