if (!Kwo) var Kwo = {};

var Domo = {
  "error": function(args) {
    if (typeof args == "object" && "result" in args && "msg" in args["result"]) {
      args = args["result"]["msg"];
    }
    if (args instanceof Array) {
      var out = "Oops!\n";
      args.each(function(item) {
        out += item + "\n";
      });
      return(out);
    }
    else {
      return(args.ucfirst());
    }
    return false;
  }
};

Domo.Auth = {

  onLogin: function(args) {
    Kwo.exec("/community/user.login", args,
             {callback: Domo.Auth.onAuthCallback, disable: true});
  },

  onSignUp: function(args) {
    var input = $(args).down(".terms_of_use");
    if (!Object.isUndefined(input) && !input.checked) {
      return Kwo.warn(input.readAttribute("data-confirm"));
    }
    Kwo.exec("/community/user.signup", args,
             {callback: Domo.Auth.onAuthCallback, disable: true});
  },

  onAuthCallback: function(res) {
    console.log(res);
    if (Kwo.hasError(res)) {
      // revoir la gestion d'erreur pour avoir une uniformité entre la version avec ou sans AJAX
      if (res['result']['msg'][0]=='pro-pending') {
        Kwo.go('/pro-pending');
      } else if ($('signup-errors') && $('signup-errors')!="undefined") {
        $('signup-errors').update(Domo.error(res)).show();
        $('signup-errors').setStyle({'display':'block'});
      } else {
        return Kwo.error(res);
      }
      return false;
    }
    if (res["result"]["user_id"]>=1) {
      window["_user_id"] = res["result"]["user_id"];
      if (Kwo.getDialog("auth")) {
        var dialog = Kwo.getDialog("auth");
        dialog.onCallback();
        dialog.close();
      }
      else if ("onAuthCallback" in window) {
        window.onAuthCallback();
      }
      else if (window.location.href.indexOf("sign") != -1) {
        Kwo.home()
      }
      else {
        Kwo.reload();
      }
    } else {
      if (res['result']['isPro']>0) {
        Kwo.go('/pro-pending');
      } else {
        Kwo.home();
      }
    }
  },

  onPasswordRequestCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    this.hide().previous().show();
    Kwo.warn(res);
  },

  onPasswordRequest: function(args) {
    Kwo.exec("/community/password.send", args,
             {callback: Kwo.Auth.onPasswordRequestCallback.bind($(args)),
              disable: true});
  }

};

Domo.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: Domo.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: Domo.Cart.onUpdateCallback, confirm: elt});
  },

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

  onQuantityChange: function(elt) {
    elt = $(elt);
    elt.up("TABLE").select(".total .quantity A")[0].show();
  },

  onUpdate: function(args) {
    Kwo.exec("/domo/cart.update", args,
             {callback: Domo.Cart.onUpdateCallback});
  },

  onPurchaseDelete: function(elt) {
    elt = $(elt);
    var id = elt.readAttribute("data-id");
    var args = {};
    args["purchases[" + id + "]"] = 0;
    if (elt.hasAttribute("data-back")) {
     args["back"] = elt.readAttribute("data-back");;
    }
    Kwo.exec("/domo/cart.update", args,
             {callback: Domo.Cart.onUpdateCallback, confirm: elt});
  },

  onUpdateCallback: function(res) {
    var back = "";
    if (res['result']['back']) {
      back = '/-/back/'+res['result']['back'];
    }
    if (Kwo.hasError(res)) {
      Kwo.error(res);
      Kwo.go("/shop/cart"+back);
      return ;
    }
    if (res["result"]["purchase_count"] >= 1) {
      Kwo.go("/shop/cart"+back);
    }
    else {
      Kwo.go("/shop/cart"+back);
    }
  },

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

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

};

Domo.Order = {

  current_step: null,

  onFinalize: function(elt) {
    elt = $(elt);
    Kwo.exec("/domo/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 = Domo.Order.compose;
      return ;
    }
    Kwo.go("/domo/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("/domo/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("/domo/order.update", [elt, args],
             {disable: elt,
              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");
    //this.current_step.up('tr').classNames = [](this.current_step.readAttribute("data-step"));
    console.log(this.next_step.readAttribute("data-step"));
    this.current_step.up('tr').addClassName(this.next_step.readAttribute("data-step"));
    Kwo.exec("/shop/order." + this.next_step.readAttribute("data-step"), null, {container: $("order-section")});
  }

};

Domo.Devis = {
  create: function(elt) {
    elt = $(elt);
    Kwo.exec("/domo/devis.create", null,
             //[elt, args],
             {//disable: elt,
             callback: Domo.Devis.onCreate
             });
    return false;
  },
  onCreate: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    }
    Kwo.go(res["result"]["callback_url"]);
  },
  remove: function(elt, id) {
    elt = $(elt);
    Kwo.exec("/account/domo/devis.remove",
             {id: id},
             {//disable: elt,
             callback: Domo.Devis.onCreate
             });
    return false;
  }
};

Domo.Login = Class.create(Kwo.Dialog, {

 initialize: function($super, opts) {
   this.opts = opts || {};
   this.name = "auth";
   this.width = window["_auth_width"] || 720;
   this.height = window["_auth_height"] || 450;
   if ("callback" in this.opts) {
     this.onCallback = function () {
       if (Object.isString(this.opts["callback"])) {
         Kwo.go(this.opts["callback"]);
       }
       else {
         this.opts["callback"].call();
       }
     }
   }
   else {
     this.onCallback = function () {
       if ("onAuthCallback" in window) {
         window.onAuthCallback();
       }
     }
   }
   $super("/domo/compte");
 }

});

Domo.User = {

  onEmailSubmit: function(args) {
    Kwo.exec("/account/community/email.save", args,
             {callback: true, disable: true});
  },

  onEmailConfirm: function(elt) {
    Kwo.exec("/community/email.confirm.request", null,
             {callback: $(elt).up("div")});
  },

  onPasswordSubmit: function(args) {
    Kwo.exec("/account/community/password.save", args,
             {callback: true, disable: true, reset: true});
    return true;
  },

  onProfileSubmit: function(args) {
    Kwo.exec("/account/domo/profile.save", args,
             {callback: true, disable: true});
  }

};

// gestion évènementielle
document.observe('dom:loaded',function() {
  if ($('user-signup') && $('user-signup')!="undefined"){
    $('user-signup').observe('submit',function(evt) {
     Event.stop(evt);
      var form = Event.element(evt);
      Domo.Auth.onSignUp(form);
    });
  }
  if ($('form-login') && $('form-login')!="undefined"){
    $('form-login').observe('submit',function(evt) {
     Event.stop(evt);
      var form = Event.element(evt);
      Domo.Auth.onLogin(form);
    });
  }
  if ($('connexion-link') && $('connexion-link')!="undefined") {
    $('connexion-link').observe('click',function(evt) {
     Event.stop(evt);
      page = "/home";
      if (!Kwo.isAuth()) {
      new Domo.Login({callback: page});
        return ;
      }
      Kwo.go(page);
    });
  }
  if ($('update-cart-btn') && $('update-cart-btn')!='undefined') {
    $('update-cart-submit').hide();
    //$('update-cart-btn').hide();
  }
  if (window['_flash']) {
    Kwo.Account.setMessage(_flash);
  }
  
  $$('.box-arrow').each(function(elt) {
    elt.setStyle({'cursor':'pointer'});
    elt.observe('click', function(evt) {
      evt.stop();
      var box = Event.findElement(evt, 'div.box-arrow');
      var box_link = box.down('a.link');
      var box_link_destination = box_link.readAttribute('href');
      Kwo.go(box_link_destination);
    });
  });

});

// --------------

Domo.Nav = {
  init : function() {
    $$('.main-wrapper .wrapper-header .nav li.account, .main-wrapper .wrapper-header .nav li.cart').each(
      function (el) {
        el.observe('mouseover', Domo.Nav.toggle.bindAsEventListener(el, true));
        el.observe('mouseout', Domo.Nav.toggle.bindAsEventListener(el, false));
      }
    );
  },
  toggle : function(event, show) {
    event.stop();
    if (show) {
      this.down('a.btn').addClassName('selected');
      this.down('.widget').show();
    }
    else{
      this.down('a.btn').removeClassName('selected');
      this.down('.widget').hide();
    }
  }
};

// --------------

Domo.Contact = {
  elt: null,
  onMessageSend: function(elt) {
    var elt = $(elt);
    Domo.Contact.elt = elt;
    Kwo.exec("/contact.send", elt,
             {callback: Domo.Contact.onCallback, disable: true});
  },
  onCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    }
    Domo.Contact.elt.up('.callback-container').update(res.result.confirm);
  }
};

Domo.Tabs = {
  init : function() {
    if ($$('.tabs .tab').size()>0) {
      $$('.tabs .tab').each(function(el){ el.observe('click', Domo.Tabs.show.bindAsEventListener(el)); });
      document.observe('dom:loaded',function () {
        $$('.frames .frame').invoke('hide');
        $$('.tabs .tab')[0].addClassName('selected-tab');
        $($$('.tabs .tab')[0].readAttribute('data-frame')).show();
      });
    } else {
      document.observe('dom:loaded',function () {
        $('all_frames').hide();
      });
    }
  },
  show : function(e) {
    e.stop;
    $$('.tabs .tab').invoke('removeClassName', 'selected-tab');
    $$('.frames .frame').invoke('hide');
    this.addClassName('selected-tab');
    $(this.readAttribute('data-frame')).show();
  }
};

Domo.ImgDialog = Class.create(Kwo.Dialog, {
  initialize: function($super, opts, path) {
    this.height = 150;
    this.width = 150;
    this.name = "photo";
    this.title = '';
    this.image = {};
    this.opts = opts || {};
    $super(this.onDisplay.curry(path));
  },
  onDisplay: function(path) {
    this.support.update('<img src="/app/core/pix/loading.gif" style="margin:65px 0 0 11px;" />');
    if (path) {
      this.o_image = new Image();
      this.o_image.src = path;
      this.image = this.o_image;
      this.o_image.onload = this.onLoad.bind(this);
      this.o_image.onerror = this.onError.bind(this);
    } else {
      this.close();
    }
  },
  onLoad: function () {
    var dimensions = document.viewport.getDimensions();
    dimensions.width = 960;
    var ratio = this.o_image.width / this.o_image.height;
    if (this.o_image.width > dimensions.width) {
      this.image.width = dimensions.width - 50;
      this.image.height = this.o_image.width / ratio;
    }
    if (this.o_image.height > dimensions.height) {
      this.image.height = dimensions.height - 50;
      this.image.width =  this.o_image.height * ratio;
    }
    this.height = this.image.height || this.o_image.height;
    this.width = this.image.width || this.o_image.width;
    this.support.update(this.image);
    this.support.setStyle({overflow:'hidden'});
    this.support.update(this.image);
    this.place();
  },
  onError: function() {
    alert("image introuvable");
    this.close();
  }
});

Domo.Diapo = {
  init : function() {
    var thumbs = $$('.diaporama-box .thumbs .thumb');
    thumbs.each(function(el){ el.observe('click', Domo.Diapo.preview.bindAsEventListener(el)); });
    $$('.diaporama-box .zoom')[0].observe('click', Domo.Diapo.zoom);
    (Domo.Diapo.preview.bindAsEventListener($(thumbs[0])))();
  },
  preview : function(e) {
    if (e) e.stop();
    var zoom = $$('.diaporama-box .zoom')[0];
    var type = this.readAttribute('data-type');
    var target = this.readAttribute('data-preview');
    var diaporamaBox = $$('.main-wrapper .wrapper-content .content .diaporama-box')[0];
    if (type == 'image') {
      zoom.writeAttribute('data-zoom', this.readAttribute('data-zoom'));
      zoom.show();
      diaporamaBox.down('#player').hide();
      diaporamaBox.down('.first').setStyle({backgroundImage:"url('" + target + "')"});
    } else if (type == 'video') {
      zoom.hide();
      zoom.writeAttribute('data-zoom', '');
      diaporamaBox.down('.first').setStyle({backgroundImage:'none'});
      diaporamaBox.down('#player').show();
      diaporamaBox.down('#player').update(target);
    }
    return false;
  },
  zoom : function() {
    var zoom = $$('.main-wrapper .wrapper-content .content .diaporama-box .zoom')[0];
    new Domo.ImgDialog(null, zoom.readAttribute('data-zoom'));
  }
};

Domo.Compare = {
  init : function (){
    $$('.grid-compare .add-product .btn-add-compare').each(function(el){ el.observe('click', Domo.Compare.toggle.bindAsEventListener(el)); });
  },
  toggle : function(e) {
    e.stop();
    if (this.hasClassName('selected')) {
      this.removeClassName('selected').setStyle({position:'static'});
      $('products-mosaic').hide();
      return;
    }
    if ($('products-mosaic').visible()) {
      $$('.grid-compare .add-product .btn-add-compare').each(function(el) { el.removeClassName('selected'); el.setStyle({position:'static'})});
      this.addClassName('selected').setStyle({position:'absolute', left:'0', top:'0', zIndex:10});
      return;
    }
    this.addClassName('selected').setStyle({position:'absolute', left:'0', top:'0', zIndex:10});
    $('products-mosaic').show();
  }
};

