
Kwo.Cart = {
  addButton: null,

  addByReference: function(elt) {
    if ($(elt).tagName.toUpperCase() === "FORM") {
      var args = $(elt);
      if (args['item_ref'].value=="") {
        alert('Référence vide');
        return false;
      }
      var reference  = args['item_ref'].value;
      var quantity = args['quantity'].value || 1;
      Kwo.exec('/hammel/check.reference',
               {'reference':reference,'quantity':quantity},
               {callback: Kwo.Cart.onByReferenceCallback});
    }
  },
  onByReferenceCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    var args = { item_key : res['result']['values']['item_key'],
                 quantity : res['result']['values']['quantity'] };
    Kwo.exec("/shop/cart.add", args,
             {callback: Kwo.Cart.onCartPurchaseCallback});
    
  },
  addPurchase: function(item_key, quantity) {
    if (Object.isElement(item_key)) {
      var args = {"quantity": 1};
      elt = $(item_key);

      Kwo.Cart.addButton = elt;

      if (elt.tagName.toUpperCase() === "FORM") {
        args = elt;
      }
      else if (elt.readAttribute("data-item-key")) {
        args["item_key"] = elt.readAttribute("data-item-key");

        if (elt.readAttribute("data-parent-key")) {
          args["parent_key"] = elt.readAttribute("data-parent-key");
        }
        if (elt.up(".cart-add-box").down("input.cart-qty")) {
          args["quantity"] = elt.up(".cart-add-box").down("input.cart-qty").getValue();
        }
      }
    }
    else {
      args["item_key"] = item_key;
      args["quantity"] = quantity || 1;
    }

    if (!Kwo.Cart.addButton.hasClassName('disabled')) {
      Kwo.Cart.addButton.addClassName('disabled');
      Kwo.exec("/shop/cart.add", args,
               {callback: Kwo.Cart.onPurchaseCallback});
    }
  },

  confirmPurchase: function(msg) {
    if ("onPurchaseCallback" in window) {
      window.purchaseConfirm.call(this, msg);
    }
    else {
      Kwo.warn(msg);
    }
  },

  empty: function(elt) {
    Kwo.exec("/shop/cart.empty", null,
             {callback: Kwo.Cart.onUpdateCallback, confirm: elt});
  },

  onPurchaseCallback: function(res) {
		//if (typeof console != 'undefined') console.info(res);
    if (Kwo.hasError(res)) return Kwo.error(res);

    if (!res["result"]["availability"]) {
      alert("La quantité demandée dépasse le stock disponible.\nLe solde de votre commande vous sera livré dans les plus brefs délais.")
    }
    var args = {item_key: res["result"]["item_key"],
                quantity: res["result"]["quantity"]};

    if (res["result"]["parent_key"]) {
      args["parent_key"] = res["result"]["parent_key"];
    }
     
		if (typeof MOBILE != 'undefined' && MOBILE){
			Kwo.Cart.view();//Kwo.go("/shop/cart");
		}else{
			new Kwo.Dialog("/shop/cart.confirm", args, {width:400, height:140, name: "cart-confirm"});
    	$("references").down("li.tab a").click(); // Added by IRCF on 2011-09-06 : Update references tab
			Kwo.Cart.addButton.removeClassName('disabled');
		}
  },
  
  onCartPurchaseCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);

    if (!res["result"]["availability"]) {
      alert("La quantité demandée dépasse le stock disponible.\nLe solde de votre commande vous sera livré dans les plus brefs délais.")
    }
    var args = {item_key: res["result"]["item_key"],
                quantity: res["result"]["quantity"]};

    /*if (res["result"]["parent_key"]) {
      args["parent_key"] = res["result"]["parent_key"];
    }*/

    Kwo.Cart.view();//Kwo.go("/shop/cart");
  },
  
  onQuantityChange: function(elt) {
    elt = $(elt);
    if (elt.up("TABLE").select(".total .updater a")[0]) elt.up("TABLE").select(".total .updater a")[0].show();
  },

	// TODO Ajax update
  onUpdate: function(args) {
    Kwo.exec("/shop/cart.update", args, {callback: Kwo.Cart.onUpdateCallback});
  },

  onPurchaseDelete: function(elt) {
    elt = $(elt);
    var id = elt.readAttribute("data-id");
    var args = {};
    args["purchases[" + id + "]"] = 0;
    Kwo.exec("/shop/cart.update", args,
             {callback: Kwo.Cart.onUpdateCallback, confirm: elt});
  },

  onUpdateCallback: function(res) {
    if (Kwo.hasError(res)) {
      Kwo.error(res);
    }else if (res["result"]["purchase_count"] >= 1 && !res["result"]["availability"]) {
			alert("La quantité demandée dépasse le stock disponible.\nLe solde de votre commande vous sera livré dans les plus brefs délais.")
		}
		Kwo.Cart.view();
  },

  view: function() {
    if ($("main")) {
      Kwo.exec("/shop/cart", null, {container: "main"});
			Kwo.Cart.updateWidget();
    }else{
    	Kwo.go("/shop/cart");
		}
  },

  updateWidget: function() {
    if ($("kwo-cart-widget")) {
      Kwo.exec("/shop/cart.widget", null, {container: "kwo-cart-widget"});
    }
  },

	// Added by IRCF on 2011-10-24 : Increase/reduce qty buttons
	increaseQty : function(elt,opts){
		var qty = $(elt).up(1).down('.cart-qty');
		qty.value++;
		if (opts && opts.update){
			//Kwo.Cart.onQuantityChange(elt);
			if (this.changeQtyTimeout) clearTimeout(this.changeQtyTimeout);
			this.changeQtyTimeout = setTimeout(function(){Kwo.Cart.onUpdate(qty);},200);
		}
	},

	reduceQty : function(elt,opts){
		var qty = $(elt).up(1).down('.cart-qty');
		if (qty.value>1){
			qty.value--;
			if (opts && opts.update){
				//Kwo.Cart.onQuantityChange(elt);
				if (this.changeQtyTimeout) clearTimeout(this.changeQtyTimeout);
				this.changeQtyTimeout = setTimeout(function(){Kwo.Cart.onUpdate(qty);},200);
			}
		}
	}

};

Kwo.Order = {
  current_step: null,

  onFinalize: function(elt) {
    $(elt).writeAttribute('old-onclick', $(elt).readAttribute('onclick'));
    $(elt).removeAttribute('onclick');
    elt = $(elt).up("FORM");
    Kwo.exec("/shop/order.update", [elt, {step: "finalize"}],
             {callback: this.onCallback.bind(elt), disable: elt});
  },

  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")});
  },

  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)});
  },

  onStepCallback: 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"});
    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")});
		window.location.href = '#order'; // Anchor added by IRCF on 2011-11-30
  },

  onPurchasesFill: function(elt) {
    elt = $(elt);
    if (!Kwo.hasClickExpired(elt)) return false;
    Kwo.exec("/account/shop/order.fill.purchases",
             {id: elt.readAttribute("data-id")},
             {callback: Kwo.Order.onPurchasesFillCallback});
  },

  onPurchasesFillCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    }
    Kwo.Cart.updateWidget();

    if (!res["result"]["availability"]) {
		  alert("Un ou plusieurs articles demandés dépassent le stock disponible.\nLe solde de votre commande vous sera livré dans les plus brefs délais.")
    }
    Kwo.reload();
  }
};


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),
              disable: args});
  },

  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.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 = 566;
    $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", {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});
  }

});

