
Kwo.Cart = {

  addPurchase: function(item_key, quantity) {
    var args = {"quantity": 1};
    if (Object.isElement(item_key)) {
      item_key = $(item_key);
      if ($(item_key).tagName.toUpperCase() === "FORM") {
        args = item_key;
      }
      else if ($(item_key).readAttribute("data-item-key")) {
        args["item_key"] = $(item_key).readAttribute("data-item-key");
      }
    }
    else {
      args["item_key"] = item_key;
      args["quantity"] = quantity || 1;
    }
    Kwo.exec("/shop/cart.add", args,
             {callback: Kwo.Cart.onPurchaseCallback});
  },

  deletePurchase: function(elt) {
    elt = $(elt);
    var args = {item_key: elt.readAttribute("data-item-key")};
    Kwo.exec("/shop/purchase.delete", args,
             {callback:Kwo.Cart.view, confirm:elt});
  },

  confirmPurchase: function(msg) {
    if ("onPurchaseCallback" in window) {
      window.purchaseConfirm.call(this, msg);
    }
    else {
      Kwo.warn(msg);
    }
  },

  empty: function(arg) {
    Kwo.exec("/shop/cart.empty", null,
             {callback: Kwo.Cart.onCartUpdate, confirm: arg});
  },

  onPurchaseCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.Cart.updateWidget();
    new Kwo.Dialog("/shop/purchase.confirm", {item_key:res["result"]["item_key"], quantity:res["result"]["quantity"] },
                   {width:650, height:280, className:"layout-hbox"});
  },

  update: function(args) {
    Kwo.exec("/shop/cart.update", args,
             {callback: Kwo.Cart.onCartUpdate});
  },

  onQuantityChange: function(elt) {
    $('cart-proceed-btn').hide();
    $('cart-update-btn').show();
  },

  onCartUpdate: function(res) {
    if (Kwo.hasError(res)) {
      Kwo.error(res);
      Kwo.Cart.view();
      return ;
    }
    if (res["result"]["purchase_count"] >= 1) {
      Kwo.Cart.view();
    }
    else {
      Kwo.go("/shop/cart");
    }
  },

  view: function() {
    Kwo.go("/shop/cart");
  },

  updateWidget: function() {
    if ($("kwo-cart-widget")) {
      Kwo.exec("/shop/cart.widget", null, {container: "kwo-cart-widget"});
    }
  }

};

Kwo.Order = {

  current_step: null,

  onFinalize: function(elt) {
    elt = $(elt).up("FORM");
    Kwo.exec("/shop/order.update", [elt, {step: "finalize"}],
             {callback: this.onCallback.bind(elt), disable: elt});
   /*    Kwo.exec("/shop/order.finalize", args,
             {callback: Kwo.Order.onCallback, disable: true}); */
  },

  compose: function() {
    if (!Kwo.isAuth()) {
      var auth = new Kwo.Class.Auth();
      auth.onCallback = Kwo.Order.compose;
      return ;
    }
    Kwo.go("/shop/order");
  },

  onCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.exec("/shop/payment.request", null,
             {container: $("psp-container")});
  },
  
  changeAddressee: function(elt) {
    elt = $(elt);
    if (elt.checked) {
      $('new_addressee').hide();
    } else {
      $('new_addressee').show();
    }
  },

  onChange: function(elt) {
    var args = $$(".order")[0].down("FORM");
    Kwo.exec("/shop/order.update", args,
             {callback: function (res) {
               if (Kwo.hasError(res)) return Kwo.error(res);
               $("kwo-amounts-box").update('<img src="/app/shop/pix/throbber.gif" />');
               Kwo.exec("/shop/order.amounts", null,
                        {container: "kwo-amounts-box"});
             }});

  },

  onStepNext: function(elt) {
    elt = $(elt);
    this.current_step = elt.up(".order").down(".order-step-selected");
    var args = {step: this.current_step.readAttribute("data-step")};
    Kwo.exec("/shop/order.update", [elt.up("FORM"), args],
             {disable: elt.up("FORM"),
              callback: this.onStepCallback.bind(this)});
  },

  goToStep: function(elt) {
    elt = $(elt);
    Kwo.exec("/shop/order." + elt.readAttribute("data-step"), null, {container: $("order-section"), callback: function() {
      if ($$('.order-step-selected')[0].readAttribute("data-step") == 'payment') {
        $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '-106px'});
        $$('.order')[0].setStyle({'height':parseInt($$('.order-summary')[0].getHeight() + 289)+'px'});
      } else {
        $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '0px'});
        $$('.order')[0].setStyle({'height':'auto'});
        if ($('reminder')) { $('reminder').remove(); }
      }
    }});
    var steps = $(elt).up(".order").select('.order-steps td');
    steps.each(function(el) {
      if ($(el).readAttribute("data-step") == $(elt).readAttribute("data-step")) {
        this.current_step = $(el);
        this.current_step.addClassName("order-step-selected");
      }
      else {
        $(el).removeClassName("order-step-selected");
      }
    });

  },

  onStepCallback: function (res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    }
    if (res['result']['carrier_id'] == 17) {
      AV911.SoColissimo.callDialog(res['result']['addressee_id']);
    } else {
      $("kwo-amounts-box").update('<img src="/app/shop/pix/throbber.gif" />');
      Kwo.exec("/shop/order.amounts", null,
               {container: "kwo-amounts-box", callback: function() {
                 if ($$('.order-step-selected')[0].readAttribute("data-step") == 'payment') {
                   $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '-106px'});
                   $$('.order')[0].setStyle({'height':parseInt($$('.order-summary')[0].getHeight() + 289)+'px'});
                 } else {
                   $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '0px'});
                   $$('.order')[0].setStyle({'height':'auto'});
                   if ($('reminder')) { $('reminder').remove(); }
                 }
               }});
      this.current_step.addClassName("order-step-visited").removeClassName("order-step-selected");
      this.next_step = this.current_step.next().addClassName("order-step-selected");
      Kwo.exec("/shop/order." + this.next_step.readAttribute("data-step"), null, {container: $("order-section"), callback: function() {
        scroll(0, 0);
        if ($$('.order-step-selected')[0].readAttribute("data-step") == 'payment') {
          $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '-106px'});
          $$('.order')[0].setStyle({'height':parseInt($$('.order-summary')[0].getHeight() + 289)+'px'});
        } else {
          $$('.order-summary')[0].setStyle({'position': 'relative', 'top': '0px'});
          $$('.order')[0].setStyle({'height':'auto'});
          if ($('reminder')) { $('reminder').remove(); }
        }
      }});
    }
  }

};


Kwo.Class.Coupon = Class.create(Kwo.Dialog, {

  initialize: function($super, elt) {
    this.name = "coupon";
    this.className = "layout-hbox";
    this.width = 320;
    this.height = 120;
    $super(this.onDisplay, null);
  },

  onDisplay: function() {
    Kwo.exec("/shop/coupon.select", null,
             {container: this.support});
  },

  onCheck: function(args) {
    Kwo.exec("/shop/coupon.check", args,
             {callback: this.onCheckCallback.bind(this)});
  },

  onCheckCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    $("coupon-id").setValue(res["result"]["coupon_id"]);
    $("coupon-code").update(res["result"]["coupon_code"]);
    this.close();
    Kwo.Order.onChange();
  }

});

Kwo.Addressee = {
  'remove': function(element) {
    var id = $(element).readAttribute('data-id');
    Kwo.exec('/shop/addressee.remove', {'id': id});
    $(element).up('td').previous('td.left').innerHTML = '';
    $(element).up('td').innerHTML = '';
  }
}

Kwo.Class.Addressee = Class.create(Kwo.Dialog, {

  initialize: function($super, elt) {
    this.name = "addressee";
    this.args = {id: $(elt).readAttribute("data-id")};
    this.className = "layout-hbox";
    this.width = 500;
    this.height = 440;
    $super("/shop/addressee.edit", this.args);
  },

  onSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/shop/addressee.save", [this.args, elt],
             {callback: this.onCallback.bind(this),
              disable: elt});
  },

  onCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    addressee_id = res["result"]["id"];
    Kwo.exec(/*"/shop/order.shipping"*/
             "/shop/order.billing", {addressee_id: addressee_id},
             {container: $("order-section"),
              callback: function () {
                $("addressee-" + addressee_id).checked = true;
                Kwo.Order.onChange();
              }});
    this.close();
  }

});

Kwo.Composer.Return = Class.create(Kwo.Dialog, {

  initialize: function($super, elt) {
    this.name = "return";
    this.layout = "hbox";
    this.args = {id: $(elt).up("TR").readAttribute("data-id")};
    this.width = 500;
    this.height = 350;
    $super("/shop/order.return.compose");
  },

  onSubmit: function(elt) {
    elt = $(elt);
    Kwo.exec("/shop/order.return.save", [this.args, elt],
             {callback: elt, disable: elt});
  }

});

