var UAD = {};

UAD.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
UAD.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;

// Display --------
UAD.Display = {
  "init": function() {
    if (Prototype.Browser.IE) {
      var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
      if (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7) {
        $$('.png').each(UAD.Display.alphaBackgrounds);
        $$("img.png, input.png").each(UAD.Display.fnLoadPngs);
      }
      $$('.clear').each(function(el) {
        el.update('&nbsp;')
      });
    }
  },
  "alphaBackgrounds": function(e) {
    var bg = e.currentStyle.backgroundImage;
    if (bg.match(/\.png/i) != null) {
      var mypng = bg.substring(5,bg.length-2);
      e.setStyle({
        filter : "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + mypng + "', sizingMethod='" + (e.currentStyle.backgroundRepeat == "no-repeat" ? "crop" : "scale") + "')",
        backgroundImage : "none"
      });
    }
  },
  "fnLoadPngs": function(img) {
    if (img.src.match(/\.png$/i) != null) {
      var src = img.src;
      var div = document.createElement("DIV");
      div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizing='scale')";
      div.style.width = img.width + "px";
      div.style.height = img.height + "px";
      img.replaceNode(div);
    }
  },
  "rollOver": function(way, el) {
    var img = $(el);
    if(way == 'over') img.writeAttribute('src', '/app/uad/pix/menu/menu-'+ img.readAttribute('name') +'-active.jpg');
    else img.writeAttribute('src', '/app/uad/pix/menu/menu-'+ img.readAttribute('name') +'.jpg');
  }
};


// Panier --------
UAD.Panier = {
  "purchase_id": null,
  "item_key": null,
  "quantity": null,
  "options": null,
  "comple":null,
  "height":null,
  "view": function() {
    Kwo.go("/achat.panier");
  },
  "addAchat": function(item_key, quantity, options, comple,height) {
    UAD.Panier.item_key = item_key;
    UAD.Panier.quantity = quantity;
    UAD.Panier.options = options;
    UAD.Panier.comple = comple;
    UAD.Panier.height = height;
    Kwo.exec("/shop/cart.purchase.add",
    {
      "item_key":item_key,
      "quantity":quantity || 1,
      "options":options,
      "comple": comple || 0
    },

    {
      "callback": UAD.Panier.onAchatCallback
    });
  },
  "editAchat": function(purchase_id, quantity, options, comple) {
    UAD.Panier.purchase_id = purchase_id;
    UAD.Panier.quantity = quantity;
    UAD.Panier.options = options;
    UAD.Panier.comple= comple;
    Kwo.exec("/shop/cart.purchase.edit",
    {
      "purchase_id":purchase_id,
      "quantity":quantity || 1,
      "options":options,
      "comple": comple || 0
    },

    {
      "callback": UAD.Panier.onEditCallback
    });
  },
  "onEditCallback": function(res) {
    if(Kwo.hasError(res)) {
      alert(res.result.msg);
    }
    UAD.Panier.updateWidget();
    Kwo.go('/achat.panier');
  },
  "actionComplement": function(item_key, quantity, options, comple) {
    UAD.Panier.item_key = item_key;
    UAD.Panier.quantity = quantity;
    UAD.Panier.options = options;
    UAD.Panier.comple = comple;
    new Kwo.Dialog("/modal.complement.action",
    {
      "item_key":item_key,
      "options":options,
      "comple": comple || 0
    },

    {
      'height':300,
      'width':600
    });
  },
  "onAchatCallback": function(res) {
    if(Kwo.hasError(res)) {
      alert(res.result.msg);
    }
    UAD.Panier.updateWidget();
    UAD.Panier.addConfirmModal(UAD.Panier.item_key,
      UAD.Panier.quantity,
      UAD.Panier.options,
      res.result.cart_id,
      UAD.Panier.comple,
      UAD.Panier.height);
  },
  "addConfirmModal": function(item_key, quantity, options, cart_id, comple,height) {
    new Kwo.Dialog('/modal.cart.add',
    {
      'item_key':item_key,
      'quantity':quantity,
      'options':options,
      'cart_id':cart_id,
      'comple': comple
    }, {'height':height, 'width':600});
  },
  "update": function(el,height) {
    if(location.pathname == "/achat.panier") {
      Kwo.exec("/shop/cart.update", el, {
        "callback": UAD.Panier.onPanierUpdate
      });
    } else {
      Kwo.exec("/shop/cart.update", el, {
        "callback": function (res) {
          //UAD.Panier.addConfirmModal(el.first().readAttribute('data-item-key'), el.first().value, el.first().readAttribute('data-mpn'), el.first().readAttribute('data-cart-id'),"",height);
          Kwo.exec('/modal.cart.add', {'item_key': el.first().readAttribute('data-item-key'), 'cart_id': el.first().readAttribute('data-cart-id'), 'options': el.first().readAttribute('data-mpn'),'comple':0}, {'container':'cart-add-modal'});
        }
      });
    }
  },
  "empty": function(arg) {
    Kwo.exec("/panier.empty", null, {
      "callback": UAD.Panier.onPanierUpdate,
      "confirm": arg
    });
  },
  "onPanierUpdate": function(res) {
    var args = {};
    if(Kwo.hasError(res)) {
      var a = res.result.msg[0].split(' | ');
      args["error_id"] = a[0];
    }
    Kwo.exec('/panier', args, {
      'container':'cart-view'
    });
  },
  "updateWidget": function() {
    if($("basket")) {
      Kwo.exec("/block.panier", null, {
        'container':'basket'
      });
    }
  },
  "incrementQty": function(input_id, quantity,height) {
    $$('.min-plus').each(function(n) {n.setAttribute("onclick", "return false;");});
    $$(input_id).each(function(n) {n.value = parseInt(n.value) + parseInt(n.value) / quantity});
    UAD.Panier.update($$(input_id),height);
    UAD.Panier.updateWidget();
  },
  "decrementQty": function(input_id, quantity,height) {
    if(quantity<=0) {return false;}
    else {
      $$('.min-plus').each(function(n) {n.setAttribute("onclick", "return false;");});
      $$(input_id).each(function(n) {n.value = parseInt(n.value) - parseInt(n.value) / quantity});
      UAD.Panier.update($$(input_id),height);
      UAD.Panier.updateWidget();
    }
  },
  'deleteCompletedModal': function(purchase_id) {
    UAD.Panier.updateWidget();
  },
  "deleteConfirmModal": function(cart_id, produit_id, mpn) {
    new Kwo.Dialog('/modal.cart.remove', {'cart_id':cart_id, 'produit_id':produit_id, 'mpn':mpn}, {'height':300,'width':600});
  },
  "deletePurchase": function(input_id) {
    $$(input_id).each(function(n) {n.value = 0;
      var parent = $(n).up('.block');
      Effect.toggle(parent.id,'appear', {duration:0.45});
    });
    UAD.Panier.update($$(input_id));
    UAD.Panier.updateWidget();
  },
  "deleteCoupon": function() {
    Kwo.exec("/order.remove.coupon", null, {
      "callback": UAD.Panier.onPanierUpdate
    });
  },
  "showCoupon": function() {
    if($('cartCoupon').getStyle('display')=='none') {
      $('cartCoupon').show();
      $('menu-code-reduc-showit').hide();
      $('menu-code-reduc-hideit').show();
    } else {
      $('cartCoupon').hide();
      $('menu-code-reduc-hideit').hide();
      $('menu-code-reduc-showit').show();
    }
  },
  "showCredit": function() {
    if($('cartCredit').getStyle('display')=='none') {
      $('cartCredit').show();
      $('menu-credit-showit').hide();
      $('menu-credit-hideit').show();
    } else {
      $('cartCredit').hide();
      $('menu-credit-hideit').hide();
      $('menu-credit-showit').show();
    }
  },
  "reload": function(res) {
    if (res["result"]["err_cagnotte"] == 1) {
      $('err-cagnotte').update(res.result.msg);
      $('err-cagnotte').show();
      return false;
    }
    if (res["result"]["err_coupon"] == 1) {
      $('err-coupon').update(res.result.msg);
      $('err-coupon').show();
      //steffi _gaq.push
      return false;
    }
    else {
      Kwo.exec('/panier', null, {
        'container':'cart-view',
        'callback':function(res) {
          if(Kwo.hasError(res)) {
            alert(res.result.msg);
          }

          if($('shipping_method1').getValue() == 1) {
            $('sel_pc').focus();
          }
          else {
            $('sel_wh').focus();
          }
        }
      });
    }
  },
  "selectLivraison": function() {
    $('shipping_method1').checked = true;
  },
  "selectEntrepot": function() {
    $('shipping_method2').checked = true;
  },
  "livraisonAddrToggle": function() {
    $('panel-facturation').toggle();
    if($('panel-facturation').visible()) {
      $('panel-livraison').setStyle({
        'width':'49%'
      });
    }
    else {
      $('panel-livraison').setStyle({
        'width':'80%'
      });
    }
  },
  "updateCarrier": function(shipment_id, deliverytype_id, id) {
    Kwo.exec("/order.update.carrier", {
      'shipping_method': 1,
      'shipment_id':shipment_id,
      'carrier_id': id
    }, {
      "callback": this.refreshShipping.bind(this, deliverytype_id)
    });
  },
  "updateWarehouse": function(shipment_id, deliverytype_id, id) {
    Kwo.exec("/order.update.carrier", {
      'shipping_method': 2,
      'shipment_id':shipment_id,
      'warehouse_id': id
    }, {
      "callback": this.refreshShipping.bind(this, deliverytype_id)
    });
  },
  "refreshShipping": function(deliverytype_id) {
    Kwo.exec("/achat.block.delivery", {
      'id':deliverytype_id
    }, {
      'container':'block-delivery-'+deliverytype_id
    });
  },
  "toggleDeliveryInfo": function(shipment_id) {
    $('delivery-reco-'+shipment_id).toggle();
  },
  "togglePaiement": function(el) {
    $('payment-frame').update("<img style='padding-left: 356px;' src='http://www.usineadesign.com/app/uad/pix/bg/bg-spinner.gif' alt='spinner' />");
    $$('.box-actif').each(function(el) {
      Element.toggleClassName(el, 'box-actif');
    });
    $$('.topPanier-paiement').each(function(el) {
      Element.toggleClassName(el, 'topPanier-paiement');
    });
    $$('.payment_type').each(function(el) {
      el.checked = 0;
    });
    Element.toggleClassName(el, 'box-actif');
    $$('.box-actif .panier-bg').first().toggleClassName('topPanier-paiement');
    $$('.box-actif input[type=radio]').first().checked = 1;
    var payment_type = $$('.box-actif input[type=radio]').first().value;

    /* $('payment-frame').setAttribute('src', '/order.payment.fork?payment_type='+payment_type); */
    Kwo.exec("/order.payment.fork", {
      "payment_type":$$('.box-actif input[type=radio]').first().value
    }, {
      "container": 'payment-frame'
    });
  }
};


// Order --------
UAD.Order = {
  "elt": null,
  "fromCartUpdate": function(el) {
    UAD.Order.elt = $(el);
    var form = el.up('form');
    Kwo.exec("/order.update", form, {
      "callback": UAD.Panier.reload
    });
  },
  "updateAddresses": function(el) {
    var errors = 0;
    $$('.input-verif').each(function(el) {
      el = $(el);
      if(el.value.blank() || UAD.Form.checkElt(el)) {
        el.next('div.form-error', 0).show();
        el.addClassName('error');
        errors++;
      }
    });
    if(errors > 0) {
      return false;
    }
    Kwo.exec('/addressee.store', el, {
      'callback':Kwo.reload
    });
  },
  "storeMyInfo": function(el) {
    var errors = 0;
    if ($$('input:checked[type="radio"][name="addressee[civility]"]').pluck('value') == '') {
      $('civility-error').show()
      $('civility-error').removeClassName('hide')
      errors++;
    } else {
      $('civility-error').addClassName('hide')
    }
    if ($('email-error').innerHTML != '' && $('email-error').visible() == true) {
      errors++;
    }

    if ($('checkbox-cgv').checked == false) {
      $('cgv-failed').removeClassName('hide')
      errors++;
    } else {
      $('cgv-failed').addClassName('hide')
    }
    $$('.input-verif').each(function(el) {
      el = $(el);
      if(el.value.blank() || UAD.Form.checkElt(el)) {
        el.next('div.form-error', 0).show();
        el.addClassName('error');
        errors++;
      }
    });
    if(errors > 0) {
      return false;
    }

    Kwo.exec('/myinfo.store', el, {'callback':function(res) {
      if (el["lead"]) {
        Kwo.go('/achat.livraison', {'lead':1});
      } else {
        Kwo.go('/achat.livraison');
      }
    }});
  },
  "storeAddresses": function(el) {
    var errors = 0;
    $$('.input-verif').each(function(el) {
      el = $(el);
      if(el.value.blank() || UAD.Form.checkElt(el)) {
        el.next('div.form-error', 0).show();
        el.addClassName('error');
        errors++;
      }
    });
    if(errors > 0) {
      return false;
    }
    Kwo.exec('/addressee.store', el, {
      'callback':Kwo.reload
    });
  },
  "compose": function() {
    Kwo.go("/achat.info");
  },
  "shippingMethodSelection": function(){
    var val = Form.getInputs('livraison','radio','carrier').find(function(radio) {
      return radio.checked;
    }).value;
    if(val != "w"){
      $('panel-pickup').hide();
      if($('same_adresses').checked){
        $('panel-facturation').show();
      }else{
        $('panel-facturation').hide();
      }
      $('panel-livraison').show();
      $('same-facturation').show();
    } else {
      $('panel-pickup').show();
      $('panel-facturation').show();
      $('panel-livraison').hide();
      $('same-facturation').hide();
    }
  },
  "selectLivraison": function() {
    $('shipping_method1').checked = true;
  },
  "selectEntrepot": function() {
    Kwo.exec('/warehouse.addressee', {
      'wh_id':$('sel_wh').value
    }, {
      'callback':function(res){
        $('whse_address').update(res.result);
      }
    })
  },
  "selectDeliveryType": function(id) {
    $$('.delivery-picker').each(function(element) {
      element.innerHTML = "";
    });
    $$('.check-deliverytype-1').each(function(element) {
      element.hide();
    });
    $$('.check-deliverytype-2').each(function(element) {
      element.show();
    });
    $$('.border-delivery').each(function(element) {
      element.removeClassName('border-delivery block-no-border block-active')
    });
    $('border-delivery-'+id).addClassName('border-delivery block-no-border block-active')
    $('deliverytype-'+id+'-unselected').hide();
    $('deliverytype-'+id+'-selected').show();
    $('block-delivery-'+id).update('<img src="http://www.usineadesign.com/app/uad/pix/bg/bg-spinner.gif" style="padding-left: 50%;" alt="spinner" />');
    Kwo.exec('/achat.block.delivery', {
      'id':id
    }, {
      'container':'block-delivery-'+id
    });
    uad.gaPageViewTracker($('block-delivery-'+id).select('.dialog,.gaTrackPageview'));
    if(id=="1") {_gaq.push(['_trackEvent','Livraison','radio_essentiel']);}
    if(id=="2") {_gaq.push(['_trackEvent','Livraison','radio_simplicite']);}
    if(id=="3") {_gaq.push(['_trackEvent','Livraison','radio_classique']);}
    if(id=="4") {_gaq.push(['_trackEvent','Livraison','radio_confort']);}
  },
  "finalize": function(el) {
    var errors = 0;
    $$('.input-verif-reco').each(function(el) {
      el = $(el);
      if(el.value.blank() || UAD.Form.checkElt(el)) {
        el.next('div.form-error', 0).show();
        el.addClassName('error');
        errors++;
      }
    });
    if(errors > 0) {
      return false;
    }
    Kwo.exec('/addressee.store', el, {
      'callback':UAD.Order.payment
    });
  },
  "payment": function() {
    Kwo.go("/achat.paiement");
  }
};



// Payment --------
UAD.Payment = {
  "btn": null,
  "load": function(el) {
    UAD.Payment.btn = $(el);
    if (!UAD.Payment.btn.disabled) {
      UAD.Payment.btn.disabled = true;
      Kwo.exec('/order.payment.fork', UAD.Payment.btn, {
        'container':'payment'
      });
    }
  }
};

// Carousel --------
UAD.Carousel = {
  "cell_width": 100,
  "cellbig_width": 146,
  "left_pos_limit": 0,
  
  "left": function(name, nbre_cells,plus,fleche) {
    if (!plus) {
      plus = 5;
    }
    
    var left_pos = parseInt($('carousel-list-'+name).getStyle('left'));
    var cell_width = parseInt($('carousel-list-'+name).childNodes[1].getStyle('width').replace("px", ""))+plus;
    if(left_pos < UAD.Carousel.left_pos_limit) {
      if(fleche) {
        $(fleche).setStyle({display: "none"});
      }
      new Effect.Move('carousel-list-'+name, {
        x:UAD.Carousel.left_pos_limit + cell_width*nbre_cells,
        y:0,
        duration:0.8,
        afterFinish: function(){
          if(fleche) {
            $(fleche).setStyle({display: "block"});
          }
          if($('carousel-list-'+name).getStyle('left')=='8px') {$('carousel-list-'+name).setStyle({left: "0px"});}
        }
      });
    }
  },
  
  "right": function(name, nbre_cells,plus,fleche) {
    if (!plus) {
      plus = 5;
    }
    
    var right_pos = parseInt($('carousel-list-'+name).getStyle('left'));
    if (!right_pos) {
      right_pos = 0;
    }
    var cell_width = parseInt($('carousel-list-'+name).childNodes[1].getStyle('width').replace("px", ""))+plus;
    var right_pos_limit = ($('carousel-list-'+name).childElements().length-nbre_cells-1) * cell_width * -1;
    if(right_pos > right_pos_limit) {
      if(fleche) {
        $(fleche).setStyle({display: "none"});
      }
      new Effect.Move('carousel-list-'+name, {
        x:0 - cell_width*nbre_cells,
        y:0,
        duration:0.8,
        afterFinish: function(){
          if(fleche) {
            $(fleche).setStyle({display: "block"});
          }
          if($('carousel-list-'+name).getStyle('left')=='-400px') {$('carousel-list-'+name).setStyle({left: "-392px"});}
        }
      });
    }
  },
  
  "slider": function(content,div,id,side) {
    $$('div[class="spinner-'+div+'"]').each(function(element) {
      element.show();
    });
    Kwo.exec("/block.carousel.slider", {
      'content':content ,
      'id':id,
      'side':side,
      'container':div
    }, {
      'container':div
    });
  },
  "initCarrousselPerso": function(){
    var count = $$('#personnalisation li').length - 1;
    var old = Math.floor(Math.random() * (count-3));
    var nouv = old+3;
    $('perso-cell-'+old).show();
    $('perso-cell-'+(old+1)).show();
    $('perso-cell-'+(old+2)).show();
    UAD.Carousel.refreshCell(old,nouv);
  },
  "refreshCell": function(old,nouv){
    var count = $$('#personnalisation li').length - 1;
    setTimeout(function(){
      $('perso-cell-'+old).hide();
      $('perso-cell-'+nouv).show();
      (nouv == count)? nouv = 0 : nouv++;
      (old == count)? old = 0 : old++;
      UAD.Carousel.refreshCell(old,nouv);
    }, 10000);
  }
};

// Recherche Avancée ----
UAD.Search = {
  "display": null,
  "id":null,
  "label":null,
  "spinner": function() {
    $('catalogue').update("<img style='padding-top: 50px; display: block; margin: auto;' src='http://www.usineadesign.com/app/uad/pix/bg/bg-spinner.gif' alt='spinner' />");
  },
  "toggle": function() {
    UAD.Produit.showMenuContent('recherche');
    Kwo.exec("/search.update", {
      'toggle':true
    });
  },
  "select": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp,option) {
    if(document.location.pathname == '/recherche-avancee' || document.location.pathname == '/recherche-avancee#') {
      Kwo.exec("/search.update", {
        'option':option
      }, {
        'callback':UAD.Search.selectCallbackAdv
      });
    } else {
      UAD.Search.spinner();
      Kwo.exec("/catalog.list.results", {
        'id':id,
        'display':display,
        'limit':limit,
        'offset':offset,
        'sort':sort,
        'search':search,
        'order':order,
        'adv':adv,
        'off':off,
        'link':link,
        'limit_sp':limit_sp,
        'option':option
      }, {
        'container':'catalogue'
      });
    }
  },
  "selectType": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp, type) {
    if(document.location.pathname == '/recherche-avancee' || document.location.pathname == '/recherche-avancee#') {
      Kwo.exec("/search.update", {
        'type':type
      }, {
        'callback':UAD.Search.selectCallbackAdv
      });
    } else {
      UAD.Search.spinner();
      //Kwo.exec("/search.update", {'type':type}, {'callback':UAD.Search.selectCallback});
      Kwo.exec("/catalog.list.results", {
        'id':id,
        'display':display,
        'limit':limit,
        'offset':offset,
        'sort':sort,
        'search':search,
        'order':order,
        'adv':adv,
        'off':off,
        'link':link,
        'limit_sp':limit_sp,
        'type':type
      }, {
        'container':'catalogue'
      });
    }
  },
  "selectSf": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp,sf) {
    UAD.Search.spinner();
    Kwo.exec("/catalog.list.results", {
      'id':id,
      'display':display,
      'limit':limit,
      'offset':offset,
      'sort':sort,
      'search':search,
      'order':order,
      'adv':adv,
      'off':off,
      'link':link,
      'limit_sp':limit_sp,
      'sousfamille':sf
    }, {'container':'catalogue'});
  },
  "selectFam": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp,famille) {
    UAD.Search.spinner();
    Kwo.exec("/catalog.list.results", {
      'id':id,
      'display':display,
      'limit':limit,
      'offset':offset,
      'sort':sort,
      'search':search,
      'order':order,
      'adv':adv,
      'off':off,
      'link':link,
      'limit_sp':limit_sp,
      'famille':famille
    }, {'container':'catalogue'});
  },
  "selectGam": function(gam) {
    if(document.location.pathname == '/recherche-avancee' || document.location.pathname == '/recherche-avancee#') {
      Kwo.exec("/search.update", {
        'gam':gam
      }, {
        'callback':UAD.Search.selectCallbackAdv
      });
    } else {
      UAD.Search.spinner();
      Kwo.exec("/search.update", {
        'gam':gam
      }, {
        'callback':UAD.Search.selectCallback
      });
    }
  },
  "selectRub": function(rub) {
    if(document.location.pathname == '/recherche-avancee' || document.location.pathname == '/recherche-avancee#') {
      Kwo.exec("/search.update", {
        'rub':rub
      }, {
        'callback':UAD.Search.selectCallbackAdv
      });
    } else {
      UAD.Search.spinner();
      Kwo.exec("/search.update", {
        'rub':rub
      }, {
        'callback':UAD.Search.selectCallback
      });
    }
  },
  "reinit": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp) {
    if(document.location.pathname == '/recherche-avancee' || document.location.pathname == '/recherche-avancee#') {
      Kwo.exec("/search.update", {
        'init':1,
        'option':0
      }, {
        'callback':UAD.Search.selectCallbackAdv
      });
    } else {
      UAD.Search.spinner();
      Kwo.exec("/catalog.list.results", {
        'id':id,
        'display':display,
        'limit':limit,
        'offset':offset,
        'sort':sort,
        'search':search,
        'order':order,
        'adv':adv,
        'off':off,
        'link':link,
        'limit_sp':limit_sp,
        'reset':true
      }, {
        'container':'catalogue'
      });
    }
  },
  "selectCallback": function(res) {
    //Kwo.exec("/block.catalog.recherche", {"display": UAD.Search.display, "id":UAD.Search.id, "label":UAD.Search.label}, {'container':'content-main-left-recherche'});
    Kwo.exec("/catalog.list.results", {
      "display": UAD.Search.display,
      "id":UAD.Search.id,
      "adv":1,
      "label":UAD.Search.label
    }, {
      'container':'catalogue'
    });
  },
  "selectCallbackAdv": function(res) {
    Kwo.exec("/adv.search.fields", {}, {
      'container':'adv-search-fields'
    });
  },
  "submitQuery": function() {
    var query;
    query = $('search-input').value;
    Kwo.go("/catalog.list", {
      'adv':1,
      'query':query
    });
  },
  "submitQueryAdv": function() {
    var sea;
    sea = $('search-input-adv').value;
    Kwo.exec("/search.update", {
      'sea':sea
    }, {
      'callback':UAD.Search.submitCallback
    });
  }
}

// Produit --------
UAD.Produit = {
  "getInfo": function(propertie) {

    $('onglets').select('a[class="active"]').each(function(element) {
      element.removeClassName("active");
    });
    $$('div[class="product-details"]').each(function(element) {
      element.hide();
    });
    $$('#'+propertie)[0].show();
  },
  "cartIncrementQty": function(input_id) {
    $(input_id).value = parseInt($(input_id).value) + 1;
  },
  "cartDecrementQty": function(input_id) {
    if($(input_id).value > 1) {
      $(input_id).value = parseInt($(input_id).value) - 1;
    }
  },
  "cartRefreshQty": function(input_id) {
    $(input_id).value = Math.round(parseInt($(input_id).value));
    if($(input_id).value == 'NaN') $(input_id).value = 1;
  },
  "toggleSidebarInfo": function(id) {
    var title = $$('#'+id+' .title')[0];
    var content = $$('#'+id+' .content')[0];
    var arrow = $$('#'+id+' .arrow img')[0];

    if(title.hasClassName('inactive')) {
      title.removeClassName('inactive');
      title.addClassName('active');
      arrow.writeAttribute('src', 'http://usineadesign.scene7.com/is/image/usineadesign/btn-arrow-down');
      content.show();
    }
    else {
      title.removeClassName('active');
      title.addClassName('inactive');
      arrow.writeAttribute('src', 'http://usineadesign.scene7.com/is/image/usineadesign/btn-arrow-right');
      content.hide();
    }
  },
  "showMenuContent": function(name) {
    if($('produit-'+name+'-content').getStyle('display')=='none') {
      //$('produit-'+name+'-content').show();
      new Effect.SlideDown('produit-'+name+'-content',{
        duration:0.5,
        fps:2000
      });
      $('produit-'+name+'-showit').hide();
      $('produit-'+name+'-hideit').show();

    }
    else {
      //$('produit-'+name+'-content').hide();
      new Effect.SlideUp('produit-'+name+'-content',{
        duration:0.5,
        fps:2000
      });
      $('produit-'+name+'-hideit').hide();
      $('produit-'+name+'-showit').show();
    }
  }
};

// Listes produit
UAD.Liste = {
  "spinner": function() {
    $('catalogue').update("<img style='padding-top: 50px; display: block; margin: auto;' src='http://www.usineadesign.com/app/uad/pix/bg/bg-spinner.gif' alt='spinner' /><p style='padding-left: 200px;padding-bottom:300px; color: rgb(119, 119, 119);'>Merci de patienter quelques instants, votre recherche va bientôt apparaître</p>");
  },
  "update": function(id,display,limit,offset,sort,search,order,adv,off,link,limit_sp,page) {
    if(page > 0){
      $('slideshowM').hide();
      $('content-searchField').setStyle({minHeight: ""});
      if($('catalogue')) uad.gaTracker($('catalogue').select('.gaTrackEvent'));
      if($('preciser')) uad.gaTracker($('preciser').select('.gaTrackEvent'));
    }
    else{
      if(!$('slideshowM').visible()) Effect.SlideDown('slideshowM');
    }
    if ( history.pushState ) history.pushState( {}, document.title, link+page);
    Kwo.exec("/catalog.list.results", {
      'id':id,
      'display':display,
      'limit':limit,
      'offset':offset,
      'sort':sort,
      'search':search,
      'order':order,
      'adv':adv,
      'off':off,
      'link':link,
      'limit_sp':limit_sp,
      'page':page
    }, {
      'container':'catalogue',
      'callback' : function () {
        Effect.ScrollTo('catalogue', {duration: 1.7},{
          beforeStart: function () {
            new Effect.Fade('catalogue', {duration:1,from: 1.0, to:0.3});
          }
        });
        uad.gaTracker($('catalogue').select('.gaTrackEvent'));
      }
    });
    if ( history.pushState ) history.pushState( {}, document.title, link+offset);
  },
  'offset': function(offset) {
    $('p-offset').value = offset;
    $('p-limit').remove();
    $('pagination-filters').submit();
  },
  'limit': function(limit) {
    $('p-limit').value = limit;
    if (limit == 1000) $('p-offset').disable();
    $('pagination-filters').submit();
  }
};

// Personnalisation --------
UAD.Perso = {
  "produit_id": null,
  "corner": null,
  "ambiance": null,
  "shareMPN": function(mpn) {
    $$(".product-share-button")[0].writeAttribute("onclick", "new Kwo.Dialog('/share/notification.prompt', {'produit_id': "+UAD.Perso.produit_id+", 'options' : '"+mpn+"'}, {'height':550, 'width':400})");
  },
  "printMPN": function(mpn) {
    $$(".product-print-button")[0].writeAttribute("href", "/produit.print/-/id/"+UAD.Perso.produit_id+"?mpn="+mpn);
  },
  "bookmarkMPN": function(mpn) {
    if($$(".sauvegarder")[0]!=undefined)
      $$(".sauvegarder")[0].writeAttribute("onclick", "new Kwo.Dialog('/community/bookmark.compose', {'produit_id': "+UAD.Perso.produit_id+", 'option': '"+mpn+"'}, {'height':230,'width':500});");

  },
  "customiserThumb": function(corner_page) {
    var i=0;
    $("customizer").getElementsBySelector('li').each(function(el){
      if (i==parseInt(corner_page))
        el.writeAttribute("class", "selected");
      i++;
    });
  },
  "toggleOptionPrice": function(el) {
    var el = $(el);
    var price = el.up('div').down('.price');
    price.toggle();
  },
  "updateImage": function(url, url_thumb) {
    $$('.s7-image').each(function(el){
      el.writeAttribute('src', url);
    });
    $('s7-image').writeAttribute('src', url);
    var compteur = 0;
    $$('.one').each(function(c){
      c.writeAttribute('src', url_thumb[compteur]);
      compteur++;
    })
  },
  "modal360": function(produit_id) {
    new Kwo.Dialog('/modal.pdt.360',
    {
      'produit_id':produit_id,
      'mpn':$$('.kwo-bookmark-button')[0].readAttribute('data-url')
    },

    {
      'width':870,
      'height':620
    });
  },
  "modalZoom": function(produit_id) {
    new Kwo.Dialog('/modal.pdt.zoom',
    {
      'produit_id':produit_id,
      'mpn':$$('.kwo-bookmark-button')[0].readAttribute('data-url')
    },

    {
      'width':740,
      'height':620
    });
  },
  "setCorner": function(produit_id, root, path, id_corner)
  {
    UAD.Perso.updatePanel(produit_id, root, path, id_corner);
  },
  "zoomIn": function(div,idImage,url,up)
  {
    if(UAD.Perso.getParamValue('wid',url)<1250)
    {
      $(div).fade({
        duration: 0.2,
        from: 0,
        to: 1
      }).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)) +'" id="'+idImage+'">');
      UAD.Perso.preLoad(UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)+up), function()
      {
        $$('handle3.selected').each(function(d){
          var chaine = d.getStyle('top');
          var reg = new RegExp("(px)", "g");
          var size = chaine.replace(reg,"");
          if(size>0)
          {
            if(size<15) size = 15;
            else size = size - 15;
            d.style.top = size+'px';
          }
        });
        $(div).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)+up) +'" id="'+idImage+'">');
      });
    }
  },
  "zoomOut": function(div,idImage,url,down,sizeOriginal)
  {
    if(UAD.Perso.getParamValue('wid',url)>UAD.Perso.getParamValue('wid',sizeOriginal))
    {
      $(div).fade({
        duration: 0.2,
        from: 0,
        to: 1
      }).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)) +'" id="'+idImage+'">');
      UAD.Perso.preLoad(UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)-down), function()
      {
        $$('handle3.selected').each(function(d){
          var chaine = d.getStyle('top');
          var reg = new RegExp("(px)", "g");
          var size = chaine.replace(reg,"");
          if(size<132)
          {
            size = (size*1) + 8;
            d.style.top = size+'px';
          }
        });
        $(div).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)-down) +'" id="'+idImage+'">');
      });
    }
  },
  "slideZoom": function(div,idImage,sizeOriginal)
  {
    if(sizeOriginal=="")
    {
      sizeoriginal = 700;
    }
    else
    {
      sizeoriginal = UAD.Perso.getParamValue('wid',sizeOriginal);
    }
    size = (sizeoriginal*1);
    new Control.Slider('handle3', 'track3', {
      axis: 'vertical',
      range: $R(size+500+50, sizeoriginal-50),
      values: [sizeoriginal, size+50, size+100, size+150, size+200, size+250, size+300, size+350, size+400, size+450, size+500],
      sliderValue: 1,
      onSlide: function(v){
        $$('handle3.selected').each(function(d){
          var chaine = d.getStyle('top');
          var reg = new RegExp("(px)", "g");
          var size = chaine.replace(reg,"");
          if(size>=0)
          {
            if(size<8) size = 8;
            else size = size - 8;
            d.style.top = size+'px';
          }
        });
      },
      onChange: function(v){
        UAD.Perso.load(div,($('s7-image').getAttribute('src')),idImage,v);
      }
    });
    $$('handle3.selected').each(function(x){
      x.style.top = '132px';
    });
  },
  "load" : function(div,url,idImage,size)
  {
    //$(div).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', ((UAD.Perso.getParamValue('wid',url))*1)) +'" id="'+idImage+'">');
    $(div).style.opacity = 0.4;
    //$(div).update("<img style='padding-top: 225px; text-align: center;' src='/app/uad/pix/bg/bg-spinner.gif' alt='spinner' />");
    UAD.Perso.preLoad(UAD.Perso.changeUrlParam(url, 'wid',  size ), function()
    {
      $(div).style.opacity = 1;
      $(div).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', size ) +'" id="'+idImage+'">');
    /*$(div).fade({
      duration: 0.2,
      from: 0,
      to: 1
    }).update('<img src="'+ UAD.Perso.changeUrlParam(url, 'wid', size ) +'" id="'+idImage+'">');*/
    });
  },
  "changeUrlParam": function (search, key, val)
  {
    var newParam = key + '=' + val,
    params = '?' + newParam;
    if (search) {
      params = search.replace(new RegExp('[\?&]' + key + '[^&]*'), '?' + newParam);
    }
    return params;
  },
  "getParamValue": function(param,url)
  {
    var u = url == undefined ? document.location.href : url;
    var reg = new RegExp('(\\?|&|^)'+param+'=(.*?)(&|$)');
    matches = u.match(reg);
    if(matches != null)
      return matches[2] != undefined ? decodeURIComponent(matches[2]).replace(/\+/g,' ') : '';
  },
  "getSizeDefault": function(param,url)
  {
    var u = url == undefined ? document.location.href : url;
    var reg = new RegExp('(\\?|&|^)'+param+'=(.*?)(&|$)');
    matches = u.match(reg);
    if(matches != null)
      return matches[2] != undefined ? decodeURIComponent(matches[2]).replace(/\+/g,' ') : '';
  },
  "drag": function(div)
  {
    new Draggable(div);
  },
  "fade": function(div)
  {
    new Effect.Appear(div, {
      duration:2,
      fps:25,
      from:0.0,
      to:1.0
    });
  },
  "preLoad": function() {
    var args = $A(arguments);
    var callback = Object.isFunction(args.last()) ? args.pop() : Prototype.emptyFunction;
    var urls = Object.isArray(args[0]) ? $A(args[0]) : args;
    var loaded = 0;
    //var images = $A();

    var onload = function() {
      if (++loaded == urls.length) {
        callback();
      }
    };

    urls.each(function(url) {
      //$('slide-prod-big').update('<img id="s7-image" src="/app/uad/pix/icon-loader.gif" class="preloader"/>');
      var image = new Image();
      image.onload = image.onerror = onload;
      image.src = url;
    //images.push(image);
    });
  },
  "showClass": function(div)
  {
    $$("."+div+"").each(function(c){
      c.style.display = '';
    })
  },
  "hideClass": function(div)
  {
    $$("."+div+"").each(function(c){
      c.style.display = 'none';
    })
  },
  "emailVisionSimple": function(segment,email,div)
  {
    var the_email = $(email).value;
    document.getElementById(div).innerHTML='<img width=\'1\' height=\'1\' src=\'http://tre.emv3.com/D2UTF8?emv_tag=8D472E010000A329&emv_ref=EdX7CqkdE6VJ8SA9MOPeWxffXEh9HtjD-zjde6lHW8LQKYw&EMVADMIN4_FIELD='+segment+'&EMAIL_FIELD='+ the_email;
  },
  "emailVisionClassique": function(segment,email,nom,prenom,mdp,div)
  {
    // MD5 début
    function array(n) {
      for(i=0;i<n;i++) this[i]=0;
      this.length=n;
    }

    function integer(n) {
      return n%(0xffffffff+1);
    }

    function shr(a,b) {
      a=integer(a);
      b=integer(b);
      if (a-0x80000000>=0) {
        a=a%0x80000000;
        a>>=b;
        a+=0x40000000>>(b-1);
      } else
        a>>=b;
      return a;
    }

    function shl1(a) {
      a=a%0x80000000;
      if (a&0x40000000==0x40000000)
      {
        a-=0x40000000;
        a*=2;
        a+=0x80000000;
      } else
        a*=2;
      return a;
    }

    function shl(a,b) {
      a=integer(a);
      b=integer(b);
      for (var i=0;i<b;i++) a=shl1(a);
      return a;
    }

    function and(a,b) {
      a=integer(a);
      b=integer(b);
      var t1=(a-0x80000000);
      var t2=(b-0x80000000);
      if (t1>=0)
        if (t2>=0)
          return ((t1&t2)+0x80000000);
        else
          return (t1&b);
      else
      if (t2>=0)
        return (a&t2);
      else
        return (a&b);
    }

    function or(a,b) {
      a=integer(a);
      b=integer(b);
      var t1=(a-0x80000000);
      var t2=(b-0x80000000);
      if (t1>=0)
        if (t2>=0)
          return ((t1|t2)+0x80000000);
        else
          return ((t1|b)+0x80000000);
      else
      if (t2>=0)
        return ((a|t2)+0x80000000);
      else
        return (a|b);
    }

    function xor(a,b) {
      a=integer(a);
      b=integer(b);
      var t1=(a-0x80000000);
      var t2=(b-0x80000000);
      if (t1>=0)
        if (t2>=0)
          return (t1^t2);
        else
          return ((t1^b)+0x80000000);
      else
      if (t2>=0)
        return ((a^t2)+0x80000000);
      else
        return (a^b);
    }

    function not(a) {
      a=integer(a);
      return (0xffffffff-a);
    }

    /* Début de l'algorithme */

    var state = new array(4);
    var count = new array(2);
    count[0] = 0;
    count[1] = 0;
    var buffer = new array(64);
    var transformBuffer = new array(16);
    var digestBits = new array(16);

    var S11 = 7;
    var S12 = 12;
    var S13 = 17;
    var S14 = 22;
    var S21 = 5;
    var S22 = 9;
    var S23 = 14;
    var S24 = 20;
    var S31 = 4;
    var S32 = 11;
    var S33 = 16;
    var S34 = 23;
    var S41 = 6;
    var S42 = 10;
    var S43 = 15;
    var S44 = 21;

    function F(x,y,z) {
      return or(and(x,y),and(not(x),z));
    }

    function G(x,y,z) {
      return or(and(x,z),and(y,not(z)));
    }

    function H(x,y,z) {
      return xor(xor(x,y),z);
    }

    function I(x,y,z) {
      return xor(y ,or(x , not(z)));
    }

    function rotateLeft(a,n) {
      return or(shl(a, n),(shr(a,(32 - n))));
    }

    function FF(a,b,c,d,x,s,ac) {
      a = a+F(b, c, d) + x + ac;
      a = rotateLeft(a, s);
      a = a+b;
      return a;
    }

    function GG(a,b,c,d,x,s,ac) {
      a = a+G(b, c, d) +x + ac;
      a = rotateLeft(a, s);
      a = a+b;
      return a;
    }

    function HH(a,b,c,d,x,s,ac) {
      a = a+H(b, c, d) + x + ac;
      a = rotateLeft(a, s);
      a = a+b;
      return a;
    }

    function II(a,b,c,d,x,s,ac) {
      a = a+I(b, c, d) + x + ac;
      a = rotateLeft(a, s);
      a = a+b;
      return a;
    }

    function transform(buf,offset) {
      var a=0, b=0, c=0, d=0;
      var x = transformBuffer;

      a = state[0];
      b = state[1];
      c = state[2];
      d = state[3];

      for (i = 0; i < 16; i++) {
        x[i] = and(buf[i*4+offset],0xff);
        for (j = 1; j < 4; j++) {
          x[i]+=shl(and(buf[i*4+j+offset] ,0xff), j * 8);
        }
      }

      /* tour 1 */
      a = FF ( a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
      d = FF ( d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
      c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
      b = FF ( b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
      a = FF ( a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
      d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
      c = FF ( c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
      b = FF ( b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
      a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
      d = FF ( d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
      c = FF ( c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
      b = FF ( b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
      a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
      d = FF ( d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
      c = FF ( c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
      b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

      /* tour 2 */
      a = GG ( a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
      d = GG ( d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
      c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
      b = GG ( b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
      a = GG ( a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
      d = GG ( d, a, b, c, x[10], S22,  0x2441453); /* 22 */
      c = GG ( c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
      b = GG ( b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
      a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
      d = GG ( d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
      c = GG ( c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
      b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
      a = GG ( a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
      d = GG ( d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
      c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
      b = GG ( b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

      /* tour 3 */
      a = HH ( a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
      d = HH ( d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
      c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
      b = HH ( b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
      a = HH ( a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
      d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
      c = HH ( c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
      b = HH ( b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
      a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
      d = HH ( d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
      c = HH ( c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
      b = HH ( b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
      a = HH ( a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
      d = HH ( d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
      c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
      b = HH ( b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */

      /* tour 4 */
      a = II ( a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
      d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
      c = II ( c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
      b = II ( b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
      a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
      d = II ( d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
      c = II ( c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
      b = II ( b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
      a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
      d = II ( d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
      c = II ( c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
      b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
      a = II ( a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
      d = II ( d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
      c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
      b = II ( b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */

      state[0] +=a;
      state[1] +=b;
      state[2] +=c;
      state[3] +=d;

    }

    function init() {
      count[0]=count[1] = 0;
      state[0] = 0x67452301;
      state[1] = 0xefcdab89;
      state[2] = 0x98badcfe;
      state[3] = 0x10325476;
      for (i = 0; i < digestBits.length; i++)
        digestBits[i] = 0;
    }

    function update(b) {
      var index,i;

      index = and(shr(count[0],3) , 0x3f);
      if (count[0]<0xffffffff-7)
        count[0] += 8;
      else {
        count[1]++;
        count[0]-=0xffffffff+1;
        count[0]+=8;
      }
      buffer[index] = and(b,0xff);
      if (index  >= 63) {
        transform(buffer, 0);
      }
    }

    function finish() {
      var bits = new array(8);
      var        padding;
      var        i=0, index=0, padLen=0;

      for (i = 0; i < 4; i++) {
        bits[i] = and(shr(count[0],(i * 8)), 0xff);
      }
      for (i = 0; i < 4; i++) {
        bits[i+4]=and(shr(count[1],(i * 8)), 0xff);
      }
      index = and(shr(count[0], 3) ,0x3f);
      padLen = (index < 56) ? (56 - index) : (120 - index);
      padding = new array(64);
      padding[0] = 0x80;
      for (i=0;i<padLen;i++)
        update(padding[i]);
      for (i=0;i<8;i++)
        update(bits[i]);

      for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
          digestBits[i*4+j] = and(shr(state[i], (j * 8)) , 0xff);
        }
      }
    }

    /* Fin de l'algorithme MD5 */

    function hexa(n) {
      var hexa_h = "0123456789abcdef";
      var hexa_c="";
      var hexa_m=n;
      for (hexa_i=0;hexa_i<8;hexa_i++) {
        hexa_c=hexa_h.charAt(Math.abs(hexa_m)%16)+hexa_c;
        hexa_m=Math.floor(hexa_m/16);
      }
      return hexa_c;
    }

    var ascii="01234567890123456789012345678901" +
    " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
    "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

    function MD5(message)
    {
      var l,s,k,ka,kb,kc,kd;

      init();
      for (k=0;k<message.length;k++) {
        l=message.charAt(k);
        update(ascii.lastIndexOf(l));
      }
      finish();
      ka=kb=kc=kd=0;
      for (i=0;i<4;i++) ka+=shl(digestBits[15-i], (i*8));
      for (i=4;i<8;i++) kb+=shl(digestBits[15-i], ((i-4)*8));
      for (i=8;i<12;i++) kc+=shl(digestBits[15-i], ((i-8)*8));
      for (i=12;i<16;i++) kd+=shl(digestBits[15-i], ((i-12)*8));
      s=hexa(kd)+hexa(kc)+hexa(kb)+hexa(ka);
      return s;
    }
    // MD5 fin
    var the_email = $(email).value;
    var the_mdp = "";
    var md5 = "";
    var the_titre = "";
    var the_prenom = "";
    var the_nom = "";
    //for(i=0;i<3;i++) {if(document.forms.emvForm1.TITLE_FIELD[i].checked==true) {the_titre=document.forms.emvForm1.TITLE_FIELD[i].value;}}
    if($(prenom)!=null) {
      the_prenom = encodeURI($(prenom).value);
    }
    if($(nom)!=null) {
      the_nom = encodeURI($(nom).value);
    }
    if($(mdp)!=null) {
      md5 = MD5(the_mdp);
    }
    document.getElementById(div).innerHTML='<img width=\'1\' height=\'1\' src=\'http://tre.emv3.com/D2UTF8?emv_tag=8D472E010000A329&emv_ref=EdX7CqkdE6VJ8SA9MOPeWxffXEh9HtjD-zjde6lHW8LQKYw&EMVADMIN4_FIELD='+segment+'&EMAIL_FIELD='+the_email+'&TITLE_FIELD='+the_titre+'&FIRSTNAME_FIELD='+the_prenom+'&LASTNAME_FIELD='+the_nom+'&EMVADMIN1_FIELD='+md5;
  },
  "show": function(div)
  {
    $(div).style.display = '';
  },
  "hide": function(div)
  {
    $(div).style.display = 'none';
  },
  "getcords": function(e)
  {
    mouseX = Event.pointerX(e);
    mouseY = Event.pointerY(e);
  },
  "pointerX": function(e)
  {
    if (Prototype.Browser.IE) return window.event.x + (document.all ? event.clientX + document.documentElement.scrollLeft : document.layers ? e.x : evt.clientX + document.documentElement.scrollLeft);
    else return e.pageX;
  }
};


// F.A.Q --------
UAD.Faq = {
  "toggleAnswer": function(id) {
    var toggle = $$('#'+id+' .answer-toggle')[0];
    var answer = $$('#'+id+' .answer')[0];
    if(!answer.visible()) {
      toggle.hide();
      answer.show();
    }
    else {
      toggle.show();
      answer.hide();
    }
  }
};


// Vote --------
UAD.Vote = {
  "zoom": function(id) {
    var zoom = $(id);
    zoom.addClassName('active');
    $$('.vote-zoom').each(function(elt) {
      if (elt != zoom ) {
        elt.hide();
      }
    });
    zoom.setStyle({
      zIndex:50
    });
    zoom.show();
  },
  "close": function(id) {
    var zoom = $(id);
    zoom.removeClassName('active');
    zoom.hide();
    zoom.setStyle({
      zIndex:1
    });
  }
};


// Creation --------
UAD.Creation = {
  "getInfo": function(creation_id, att) {
    Kwo.exec("/block.crea.infos", {
      'id':creation_id,
      'att':att
    }, {
      'container':'crea-infos-box'
    });
  }
};


// Parrainage --------
UAD.Parrainage = {
  "add": function(email) {
    $('gd-email').clear();
    Kwo.exec("/service.godson", {
      'email':email
    }, {
      'callback':function(res) {
        var list = $('godsons-list');
        list.insert({
          bottom : res['result']["html"]
        });
      }
    });
  },
  "remove": function(el) {
    var el = $(el);
    el.up('.godson-email').remove();
  }
};


// Rating --------
UAD.Rating = {
  "onThumb": function(elt, direction) {
    elt = $(elt);
    var args = {};
    args["item_key"] = elt.readAttribute("data");
    args["direction"] = direction;
    Kwo.exec("/rating/thumb", args, {
      'callback': UAD.Rating.onThumbCallback.bind(elt)
    });
  },
  "onThumbCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    var label = $('label');
    label.update(res["result"]["callback_msg"]);
    $('thumb-result').update(res["result"]["vote"]);
  }
};

// Membre --------
UAD.Membre = {
  onProfileSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/profile.save", elt, {
      disable:true,
      callback:true
    });
  },
  onPrecisionsSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/precisions.save", elt, {
      disable:true,
      callback:true
    });
  },
  onDesignerSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/designer.save", elt, {
      disable:true,
      callback:true
    });
  },
  onEntrepriseSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/entreprise.save", elt, {
      disable:true,
      callback:true
    });
  },
  onCreationEdit: function(elt) {
    Kwo.exec("/account/uad/designer.creation", {"id": $(elt).readAttribute("data-id")}, {container: "creation-edit"});
    $("creation-edit").scrollTo();

  },
  onCreationSave: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/designer.furniture.save", elt, {
      disable:true,
      callback:true
    });
  },
  onCreationRemove: function(elt) {
    elt = $(elt);
    Kwo.exec("/account/uad/designer.creation.remove", {
      'id': elt.readAttribute("data-id")
    },

    {
      confirm:elt,
      callback:true
    });
  },
  onSponsorshipRemove: function(id) {
    Kwo.exec("/account/uad/sponsorship.remove", {
      'id':id
    }, {
      callback:true
    });
  }
};


// Contact --------
UAD.Contact = {
  "checkEmail": function(email) {
    Kwo.exec("/check.email", {
      'email': email
    }, {
      'container': 'email-error'
    });
  },
  "askcall": function(num) {
    Kwo.exec("/s.client.callme", {
      'num':num
    }, {
      'container': 'block-call-me',
      'callback': UAD.Contact.askcallback
    });
  },
  "askcallback": function(num) {
    $("telephone").value = 'Merci!';
  },
  "askcall2": function(num, id) {
    Kwo.exec("/s.client.callme", {
      'num':num,
      'id':id
    }, {
      'callback': function(){
        $("telephone").value = 'Merci!';
        $("callback-reply").innerHTML = 'Votre demande a bien été prise en compte';
      }
    });
  },
  onCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    this.reset();
    this.down(".button-box").update(res["result"]["callback_msg"]);
  },

  onFaqSelect: function(elt) {
    elt = $(elt);
    if (elt.getValue() == 0) {
      $("faq-questions").update('<option value="0">--</option>');
      $("faq-answer").hide();
      return ;
    }
    var args = {
      "id": elt.getValue(),
      "top": "0:--",
      "bottom": "-1:Aucune question ne correspond à ma demande"
    }
    Kwo.exec("/faq/questions", args, {
      callback: $("faq-questions")
    });

  },
  onQuestionSelect: function(elt) {
    elt = $(elt);
    if (elt.getValue() == 0) {
      return ;
    }
    else if (elt.getValue() == -1) {
      $("faq-answer").hide();
      $$(".contact-form")[0].show();
      return;
    }
    $$(".contact-form")[0].hide();
    $("answer-content").update().show();
    $("faq-answer").show();
    Kwo.exec("/faq/answer", {
      "id": elt.getValue()
    },

    {
      callback: $("answer-content")
    });
  },
  onSubmit: function(elt) {
    elt = $(elt);
    Kwo.exec("/uad/contact.send", [elt, {
      "faq_id": $("faq-select").getValue()
    }],

    {
      disable:elt,
      callback: UAD.Contact.onCallback.bind(elt)
    });


  }
};


// Form control --------
UAD.Form = {
  "checkRequiredElts": function(){
    var inputs = $$('.input-verif');
    errors = 0;
    inputs.each(function(el) {
      el = $(el);
      if(UAD.Form.checkElt(el) || el.value == '') {
        errors++;
      }
    });
    return (errors > 0) ? false : true;
  },
  "check": function(elt) {
    elt = $(elt);
    var value = elt.value;
    var error_div = elt.next('div.form-error', 0);
    var has_error = UAD.Form.checkElt(elt);
    if (value.blank()) {
      has_error = true;
    }
    if (has_error === true) {
      //error_div.show();
      elt.addClassName('error');
    }
    else {
      //error_div.hide();
      if(elt.hasClassName('error')) {
        elt.removeClassName('error');
      }
    }
  },
  "checkNoEmpty": function(elt) {
    elt = $(elt);
    var value = elt.value;
    var error_div = elt.next('div.form-error', 0);
    var has_error = (UAD.Form.checkElt(elt) && elt.value != '');

    if (has_error === true) {
      error_div.show();
      elt.addClassName('error');
    }
    else {
      error_div.hide();
      if(elt.hasClassName('error')) {
        elt.removeClassName('error');
      }
    }
  },
  "checkElt": function(elt) {
    elt = $(elt);
    var control_type = elt.readAttribute('data-control-type');
    if(control_type != 'civ')
    {
      var value = elt.value;
    }
    var has_error = false;
    switch (control_type) {
      case 'txt':
        has_error = UAD.Form.checkText(value);
        break;
      case 'cp':
        has_error = UAD.Form.checkPostalCode(value);
        break;
      case 'phone':
        has_error = UAD.Form.checkPhone(value);
        break;
      case 'alphanum':
        has_error = UAD.Form.checkAlphaNum(value);
        break;
      case 'email':
        has_error = UAD.Form.checkEmail(value);
        break;
      case 'pwd':
        has_error = UAD.Form.checkPwd(value);
        break;
      case 'name':
        has_error = UAD.Form.checkNames(value);
        break;
      case 'empty':
        has_error = UAD.Form.checkEmpty(value);
        break;
      case 'civ':
        has_error = UAD.Form.checkCivility(elt);
        break;
    }
    return has_error;
  },
  "checkPostalCode": function(str) {
    var expr = new RegExp("^[0-9]");
    if (expr.test(str)) return false;
    return true;
  },
  "checkPhone": function(str) {
    var expr = new RegExp("^[0-9]{8,16}$");
    if (expr.test(str)) return false;
    return true;
  },
  "checkText": function(str) {
    var expr = new RegExp("^[A-Za-z0-9_\-]{3,30}$");
    if (expr.test(str)) return false;
    return true;
  },
  "checkAlphaNum": function(str) {
    var expr = new RegExp("[a-zA-Z0-9]");
    if (expr.test(str)) return false;
    return true;
  },
  "checkEmail": function(str) {
    var expr = new RegExp("^[A-Za-z0-9.+_-]+@[A-Za-z0-9.-]{2,}[.][A-Za-z]{2,4}$");
    if (expr.test(str)) return false;
    return true;
  },
  "checkPwd": function(str) {
    var expr = new RegExp("^[A-Za-z0-9!@#$%=^&*()_+]{6,20}$");
    if (expr.test(str)) return false;
    return true;
  },
  "checkNames": function(str) {
    var expr = new RegExp("^[a-zA-Z0-9\ _éèêëàâîïûü-]{2,30}$");
    if (expr.test(str)) return false;
    return true;
  },
  "checkEmpty": function(str) {
    return str.blank();
  },
  "checkCivility": function(elt) {

    if(elt.options[elt.selectedIndex].value == "") {
      return true;
    }
    else {
      return false;
    }
  }


};

// Onglets --------
UAD.Onglet = {
  "afficher": function (element, content) {
    var parent = element.parentNode.parentNode;
    var cible = parent.readAttribute("target");
    var result = parent.next('div');
    Kwo.exec(cible,
    {
      "content":content
    },

    {
      "varnish":true,
      "container":result.id,
      "callback":element.parentNode.getElementsBySelector('li').each(function(el){
        (element==el)?el.setAttribute("class", "onglet-actif"):el.setAttribute("class", "onglet-passif");
      })
    });
  },

  "afficherSuivant": function (rubriques, gammes, key, theme, type) {
    Kwo.exec("/uad/block.collection.list.famille",
    {
      'rubriques_imp':rubriques,
      'gammes_imp':gammes,
      'key':key,
      'theme':theme,
      'type':type
    },

    {
      "varnish":true,
      "container":'block-collections-list-famille'
    });

  }
};

UAD.Dialog = {
  "escapeHandler": function(event) {
    if(Kwo.getDialog()) {
      if(event.keyCode == Event.KEY_ESC) {
        Kwo.getDialog().close();
      }
      else if(event.keyCode == 32) {
        Kwo.getDialog().place();
        event.stopPropagation();
      }
    }
  },
  "serviceClient": function() {
    new Kwo.Dialog('/block.serviceclient',
    {},
    {
      'height':280,
      'width':200
    });
  }
};

UAD.Socolissimo = Class.create(Kwo.Dialog, {

  initialize: function($super, args, callback) {
    this.name = "prompt";
    this.callback = callback;
    if (Object.isString(args)) {
      args = {
        "title": args
      };
    }
    if ((screen.width>=1440) && (screen.height>=768))
    {
      $super(this.refresh, args, {
        width: 999,
        height: 750
      });
    }
    else
    {
      $super(this.refresh, args, {
        width: 999,
        height: 500
      });
    }
  },

  refresh: function(args) {
    var iframe = $(document.createElement("iframe"));
    iframe.setAttribute('name', 'frame_colissimo');
    iframe.setAttribute('height', '100%');
    iframe.setAttribute('width', '100%');
    this.support.appendChild(iframe);
    $('form_colissimo').submit();
  //Kwo.exec("http://google.com", args, {container: this.support});
  }

});

document.observe("dom:loaded", function() {
  setTimeout(UAD.Display.init, 100);
});

UAD.B2b = {
  onSubmit: function(elt) {
    elt = $(elt);
    if (document.formb2b.company.value == "")
    {
      alert("Veuillez entrez un nom de société.");
      return false;
    }
    else if (document.formb2b.l_name.value == "")
    {
      alert("Veuillez entrez votre nom.");
      return false;
    }
    else if (document.formb2b.f_name.value == "")
    {
      alert("Veuillez entrez votre prénom.");
      return false;
    }
    else if (document.formb2b.country.value == "")
    {
      alert("Veuillez entrez le pays.");
      return false;
    }
    else if (document.formb2b.position.value == "")
    {
      alert("Veuillez entrez votre poste.");
      return false;
    }
    else if (document.formb2b.mail.value == "")
    {
      alert("Veuillez entrez une adresse e-mail.");
      return false;
    }
    else if (document.formb2b.phone.value == "")
    {
      alert("Veuillez entrez un numéro de téléphone.");
      return false;
    }
    else if (document.formb2b.help.value == "")
    {
      alert("Veuillez entrez un message.");
      return false;
    }
    else if (document.formb2b.b_hour.value == "" ||
      document.formb2b.e_hour.value== "")
      {
      alert("Veuillez entrez un intervalle d'heure où nous pourrions vous rappeler.");
      return false;
    }
    else if (document.formb2b.planning.checked == "" && 
      document.formb2b.event.checked == "" &&
      document.formb2b.equipment.checked == "" &&
      document.formb2b.provider.checked == "" &&
      document.formb2b.reseller.checked == "" &&
      document.formb2b.vision.checked == "" &&
      document.formb2b.prescriber.checked == "")
      {
      alert("Veuillez selectionner au moins un projet.");
      return false;
    }
    else
    {
      exp_mail = /^[a-z0-9\.\-_]+@[a-z0-9\.\-_]+\.[a-z]{2,3}$/i;
      exp_hour = /\d/;
      if (exp_hour.test(document.formb2b.b_hour.value) == false ||
        exp_hour.test(document.formb2b.e_hour.value) == false)
        {
        alert("Entrez un nombre d'heures valide pour vous rappeler.");
        return false;
      }
      else if (exp_mail.test(document.formb2b.mail.value) == false)
      {
        alert("Entrez une adresse mail valide.");
        return false;
      }
    }
    Kwo.exec("/b2b", elt,{
      callback: UAD.B2b.onCallback.bind(elt)
    });
  },

  onCallback: function(res) {
    $('result-b2b').show(); /*show() force l'affichage (contraire = hide())*/
    res
  }
};

UAD.Tools = {
  "getParameter": function(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }
};



UAD.Agenda = {
  "showEvents": function(el) {
    var el = $(el);
    Kwo.exec('/magazine.agenda.events', {'date': el.readAttribute('data-date')}, {'container': 'agenda-events'});
  },
  "updateWidget": function(el) {
    var el = $(el);
    Kwo.exec('/magazine.agenda.widget', {'date': el.readAttribute('data-date')}, {'container': 'agenda-widget'});
  }
};

UAD.Thematique = {
  "view": function(el) {
    var el = $(el);
    new Kwo.Dialog('/thematique', {'id': el.readAttribute('data-id')}, {'height':380, 'width':595});
  }
};

UAD.Commentaire = {
  "view": function(el) {
    var el = $(el);
    el.up("tr").removeClassName("new");
    el.removeClassName("button4").addClassName("button2");
    el.up("tr").down("td.ico_msg").down("img").src = "/app/uad/pix/ico/message-small-open.png";
    new Kwo.Dialog('/account/uad/designer.comment', {'id': el.readAttribute('data-id')}, {'height':400, 'width':500});
  },
  "save": function(args) {
    var agrs = $(args);
    Kwo.exec('/comment/comment.add', args, {'callback':Kwo.reload})
  }
};

UAD.Blog = {
  "onBlogEdit": function() {
    new Kwo.Dialog("/account/uad/designer.blog.edit", {}, {"height":500, "width":600});
  },
  "onBlogSave": function(el) {
    var el = $(el);
    Kwo.exec("/account/uad/designer.save", el, {disable: true, callback: true});
  },
  "onBilletEdit": function(el) {
    Kwo.exec("/account/uad/designer.billet", {"id": $(el).readAttribute("data-id")}, {container: "billet-edit"});
    $("billet-edit").scrollTo();
  },
  "onBilletSave": function(el) {
    var el = $(el);
    Kwo.exec("/account/uad/designer.billet.save", el, {disable: true, callback: Kwo.reload});
  },
  "onBilletRemove": function(el) {
    var el = $(el);
    Kwo.exec("/account/uad/designer.billet.remove", {id: el.readAttribute("data-id")}, {confirm: el, callback: true});
  },
  "onBilletToggle": function(el) {
    var el = $(el);
    Kwo.exec("/account/uad/designer.billet.toggle", {id: el.readAttribute("data-id"), status: el.getValue()}, {callback: true});
  },
  "onFollow": function(el) {
    Kwo.exec("/designer.blog.follow",
             {blog_id: $(el).readAttribute("data-blog-id")},
             {callback: UAD.Blog.onFollowCallback});
  },
  "onFollowCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    $("blog-follow").hide();
    $("blog-quit").show();
  },
  "onQuit": function(el) {
    Kwo.exec("/designer.blog.quit",
             {blog_id: $(el).readAttribute("data-blog-id")},
             {callback: UAD.Blog.onQuitCallback});
  },
  "onQuitCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    $("blog-quit").hide();
    $("blog-follow").show();
  }
};

UAD.Estimation = {
  "onEstimate": function(elt) {
    var elt = $(elt);
    var args = {"item_key": elt.readAttribute("data-item"),
                "price": elt.previous("span").readAttribute("data-price")};
    Kwo.exec("/uad/creation.estimate", args, {callback:UAD.Estimation.onEstimateCallback.bind(elt)});
  },
  "onEstimateCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    this.replace("<span>" + res["result"]["callback_msg"] + "</span>");
  }
};

UAD.Creation = {
  "onCarrouselPrev": function() {
    var selected = $('creation-carrousel').down('li.selected');
    var count = $$('#creation-carrousel li').size();
    if (selected.previous('li')) {
      var previous = selected.previous('li');
    } else {
      var previous = $('creation-carrousel').down('li', count-1);
    }
    $$('#creation-carrousel li').invoke('removeClassName', 'selected');
    previous.addClassName('selected');
    $$('#creation-thumbnails li').invoke('removeClassName', 'selected');
    $('creation-thumbnails').down('li.thumb'+previous.readAttribute("data-n")).addClassName('selected');
  },
  "onCarrouselNext": function() {
    var selected = $('creation-carrousel').down('li.selected');
    if (selected.next('li')) {
      var next = selected.next('li');
    } else {
      var next = $('creation-carrousel').down('li', 0);
    }
    $$('#creation-carrousel li').invoke('removeClassName', 'selected');
    next.addClassName('selected');
    $$('#creation-thumbnails li').invoke('removeClassName', 'selected');
    $('creation-thumbnails').down('li.thumb'+next.readAttribute("data-n")).addClassName('selected');
  },
  "onThumb": function(el) {
    var el = $(el);
    $$('#creation-thumbnails li').invoke('removeClassName', 'selected');
    el.up('li').addClassName('selected');
    $$('#creation-carrousel li').invoke('removeClassName', 'selected');
    $('creation-carrousel').down('li.image'+el.readAttribute("data-n")).addClassName('selected');
  }
};

UAD.Reportage = {
  "onOpen": function(el) {
    var el = $(el);
    new Kwo.Dialog("/magazine.reportage", {"id": el.readAttribute("data-id")}, {"height":845, "width":645});
  },
  "onNavigate": function(direction) {
    var slides = $$('#stage .slide');
    var current = $('stage').down('.selected');
    if (direction == 'prev') {
      var upcoming = $('stage').down('.slide', slides.size()-1);
      if (current.previous('.slide')) upcoming = current.previous('.slide');
    }
    else {
      var upcoming = $('stage').down('.slide', 0);
      if (current.next('.slide')) upcoming = current.next('.slide');
    }
    $$('#stage .slide').invoke('removeClassName', 'selected');
    upcoming.addClassName('selected');
    UAD.Reportage.thumbSelection(upcoming.readAttribute('data-index'));
  },
  "onThumbSelect": function(el) {
    var index = $(el).readAttribute('data-index');
    UAD.Reportage.thumbSelection(index);
    $$('#stage .slide').invoke('removeClassName', 'selected');
    $('stage').down('.slide'+index).addClassName('selected');
  },
  "thumbSelection": function(index) {
    $$('#thumbnails li').invoke('removeClassName', 'selected');
    $('thumbnails').down('.thumb'+index).addClassName('selected');
  }
};

UAD.User = {
  "onCrop": function(file) {
    new Kwo.Dialog("/account/uad/avatar.crop", {"image": file}, {"width":700, "height":500});
  },
  "initCropper": function() {
    new Cropper.ImgWithPreview(
    	'avatar',
    	{
    		previewWrap: 'previewWrap',
    		minWidth: 230,
    		minHeight: 230,
    		ratioDim: {x: 230, y: 230},
    		onEndCrop: UAD.User.onEndCrop
    	}
    );
  },
  "onEndCrop": function(coords, dimensions) {
    if ($('x1') && $('x2') && $('y1') && $('y2')) {
      $('x1').value = coords.x1;
  	  $('y1').value = coords.y1;
  	  $('x2').value = coords.x2;
  	  $('y2').value = coords.y2;
  	  $('width').value = dimensions.width;
  	  $('height').value = dimensions.height;
    }
  },
  
  "onFurnitureCrop": function(file) {
    new Kwo.Dialog("/account/uad/designer.furniture.crop", {"image": file, "i":i}, {"width":800, "height":580});
  },
  "initFurnitureCropper": function() {
    new Cropper.ImgWithPreview(
    	'furniture',
    	{
    		previewWrap: 'previewWrap',
    		minWidth: 101,
    		minHeight: 101,
    		ratioDim: {x: 323, y: 323},
    		onEndCrop: UAD.User.onEndCrop
    	}
    );
  },
  "onEndCrop": function(coords, dimensions) {
    if ($('x1') && $('x2') && $('y1') && $('y2')) {
      $('x1').value = coords.x1;
  	  $('y1').value = coords.y1;
  	  $('x2').value = coords.x2;
  	  $('y2').value = coords.y2;
  	  $('width').value = dimensions.width;
  	  $('height').value = dimensions.height;
    }
  },
  "onFurnitureSet": function(args) {
    if (Kwo.getDialog()) Kwo.getDialog().close();
    Kwo.exec("/account/uad/furniture.picture.save", args, {callback: UAD.User.onFurnitureCallback});
  },
  "onAvatarSet": function(args) {
    if (Kwo.getDialog()) Kwo.getDialog().close();
    Kwo.exec("/account/community/avatar.save", args, {callback: UAD.User.onAvatarCallback});
  },
  "onAvatarCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.exec("/account/uad/avatar.edit", null, {container: $("avatar-box")});
  },
  "onFurnitureCallback": function(res) {
    for (i = 1; i <= 4; i++) {
      if ($("elt-image-target-"+i).down('img').src.match("empty.gif")){
        var img_target = $("elt-image-target-"+i).down('img');
        var input_target = $("elt-input-target-"+i).down('input');
        img_target.src = res.result.filepath;
        input_target.value = res.result.name;
        img_target.show();
        break;
      }
      else{ 
        continue;
      }
    }
  }
};

UAD.Rating = {
  "container": null,
  "isBinded": false,
  "registry": {},

  "bind": function() {
    if (UAD.Rating.isBinded === true) return false;
    UAD.Rating.isBinded = true;
    $$(".creation-rate-box").each(function (element) {
      Event.observe(element, "click", UAD.Rating.onClick, true);
    });
    $$(".creation-rate-box img").each(function (element) {
      Event.observe(element, "mouseout", UAD.Rating.onMove, true);
      Event.observe(element, "mouseover", UAD.Rating.onMove, true);
    });
  },
  "onClick": function(event) {
    event = event || window.event;
    UAD.Rating.container = Event.element(event);
    var arr = UAD.Rating.container.id.split("-");
    var entry = arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3];
    if (UAD.Rating.registry[entry] == true) return ;
    UAD.Rating.registry[entry] = true;
    var btn = $$('.creation-rate-btn')[0].down('a');
    btn.update("Validez");
    btn.writeAttribute("data-note", arr[4]);
  },
  "onValidate": function(elt) {
    var elt = $(elt);
    if (!UAD.Rating.container) {
      alert('Vous devez choisir votre note en cliquant sur les étoiles avant de valider votre vote');
      return ;
    }
    Kwo.exec("/rating/ping",
             {"model_id": elt.readAttribute("data-model-id"),
              "record_id": elt.readAttribute("data-record-id"),
              "note": elt.readAttribute("data-note")},
             {"callback": UAD.Rating.onValidateCallback});
  },
  "onValidateCallback": function(res) {
    if (res["error"] >= 1) Kwo.error(res["result"]["msg"]);

    var stars_container =  UAD.Rating.container.up("div");
    stars_container.stopObserving("click", UAD.Rating.onClick, true);
    stars_container.up("div.creation-rate").down("div.creation-rate-btn")
                   .update(res["result"]["callback_msg"]);
    //if (!Kwo.isAuth()) {
      //new Kwo.Class.Snippet('uad.offline.vote');
      //new Kwo.Dialog("/creation.vote.modal", null, {"width":600, "height":420});
    //}
  },
  "onMove": function(event) {
    event = event || window.event;
    var arr = Event.element(event).id.split("-");
    var entry = arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3];
    if (UAD.Rating.registry[entry] == true) return ;
    var sig = entry + "-";
    var i = 1;
    if (event.type.endsWith("out")) {
      while (i < 6) {
        if (!$(sig + i)) break;
        if ($(sig + i).src.match("over")) {
          var s= "over";
        } else {
          var s = $(sig + i).src.match("off") ? "off" : "on";
        }
        $(sig + i).src = $(sig + i).src.sub(s, $(sig + i).className);
        i++;
      }
    }
    else {
      var num = parseInt(arr[4]);
      for (i = 1; i <= num; i++) {
        if ($(sig + i).src.match("off")) {
          $(sig + i).src = $(sig + i).src.sub("-off", "-over");
        } else {
          $(sig + i).src = $(sig + i).src.sub("-on", "-over");
        }
      }
      while (i < 6) {
        if (!$(sig + i)) break;
        $(sig + i).src = $(sig + i).src.sub("-over", "-off");
        i++;
      }
    }
  }
};

UAD.Chars = {
  "onType": function(elt, container, limit) {
    var left = limit - $(elt).getValue().length;
    $(container).update(left);
  }
};

UAD.Inbox = {
  "read": function(el) {
    var el = $(el);
    el.up("tr").removeClassName("new");
    el.removeClassName("button4").addClassName("button2");
    el.up("tr").down("td.ico_msg").down("img").src = "/app/uad/pix/ico/message-small-open.png";
    new Kwo.Dialog("/account/social/message", {"id": el.readAttribute("data-id")}, {"width":500, "height":450});
  }
};

UAD.Contrib = {
  "open": function(el) {
    var el = $(el);
    new Kwo.Dialog("/account/uad/menu.contact.modal", {"subject": el.readAttribute("data-subject")}, {"width":500, "height":420});
  },
  "send": function(args) {
    var args = $(args);
    Kwo.exec("/account/uad/menu.contact.send", args, {"callback": UAD.Contrib.sendCallback});
  },
  "sendCallback": function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.getDialog().close();
  }
};

 UAD.Interstitiel = { 
   "pushEmailvision" : function(email){
        document.getElementById('emailvisionform1').innerHTML='<img width="1" height="1" src="http://tre.emv3.com/D2UTF8?emv_tag=40001D4097A48C00&emv_ref=EdX7CqkdEh7L8SA9MOPeWxfTKEx6HdnH-jHaCq0-K8DZKJM&EMAIL_FIELD='+email+'&SEGMENT_FIELD=france2salonnow&EMVADMIN4_FIELD=france2salonnow&NEWSLETTERS_FIELD=|nouveaute|promo|conseil|exclu|&SOURCE_FIELD=site_newsletter1"/>';
        $('EMAIL_FIELD2').value = "merci !";
        return false
   },
   "SetCookie" : function(name, value, days) {
        var expire = new Date ();
        expire.setTime (expire.getTime() + (24 * 60 * 60 * 1000) * days);
        document.cookie = name + "=" + escape(value) + "; expires=" +expire.toGMTString();
   }, 
   "GetCookie" : function (name) {
        var startIndex = document.cookie.indexOf(name);
        if (startIndex != -1) {
            var endIndex = document.cookie.indexOf(";", startIndex);
            if (endIndex == -1) endIndex = document.cookie.length;
            return unescape(document.cookie.substring(startIndex+name.length+1, endIndex));
        }
        else {
            return null;
        }
    }, 
    "DeleteCookie" : function (name) {
        var expire = new Date ();
        expire.setTime (expire.getTime() - (24 * 60 * 60 * 1000));
        document.cookie = name + "=; expires=" + expire.toGMTString();
    }, 
    "PopupStatic" : function () {
        var cookie = UAD.Interstitiel.GetCookie("PopupStaticInterstitiel");
        if(cookie==null) {
            UAD.Interstitiel.SetCookie("PopupStaticInterstitiel",1,300);
        }
        else {
            if(cookie==1) {$('modal-interstitiel-warper').show();UAD.Interstitiel.SetCookie("PopupStaticInterstitiel",2,300);return false;}
            else {return false;}
        }
    }, 
    "Delete" : function () {
        UAD.Interstitiel.DeleteCookie("PopupStaticInterstitiel");
    }
};

