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).toFixed(4) + "1").toFixed(2));
  },

  // recalculates item pricing based on selected option(s). args contains the
  // following entries:
  //  items: list of items to reprice. each item contains:
  //    id: dom id suffix
  //    base_price: for single item, base price w/o options
  //    our_price: our price w/o options
  //    pack_size: quantity per pack
  //  instant_savings_pct: discount percentage to apply
  //  discount_pct: discount percentage to apply
  //  options: array of option ids for the item
  update_options: function(args) {
    if (!args)
      return;

    // get total price for selected options
    var options_price = 0;
    args.options.each(function(option_id) {
      var select = $('opt_' + option_id);
      var price = Number(select[select.selectedIndex].getAttribute('price'));
      options_price += price;
    });

    // calculate each pack's pricing
    args.items.each(function(item) {

      var base_price;
      var our_price;
      var savings;
      var you_pay;
      var pack_size = Number(item.pack_size) || 1;

      if (item.base_price)
        base_price = App.round2(Number(item.base_price) + options_price);
      our_price = Number(App.round2(Number(item.our_price) / pack_size + options_price));
      you_pay = our_price;
      var instant_savings_amt = Number(App.round2(you_pay * Number(args.instant_savings_pct) * 0.01));
      you_pay -= instant_savings_amt;
      var discount_amt = Number(App.round2(you_pay * Number(args.discount_pct) * 0.01));
      you_pay -= discount_amt;
      savings = our_price - you_pay;

      // update pricing elements
      var el;
      el = $('base_price_' + item.id); if (el) el.set('html', App.round2(base_price * pack_size));
      el = $('our_price_' + item.id); if (el) el.set('html', App.round2(our_price * pack_size));
      el = $('savings_' + item.id); if (el) el.set('html', App.round2(savings * pack_size));
      el = $('you_pay_' + item.id); if (el) el.set('html', App.round2(you_pay * pack_size));
      el = $('per_unit_' + item.id); if (el) el.set('html', App.round2(you_pay));
    });
  }

};

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