if (!Kwo) var Kwo = {};

var AV911 = {};

AV911.Utility = {
  _clickObs: false,
  _topPanel: null,
  incrementElt : function(elt, btn) {
    if (!$(elt)) return;
    var _min  = ($(elt).readAttribute('quantity_min') ? parseInt($(elt).readAttribute('quantity_min')) : 1);
    var _max  = ($(elt).readAttribute('quantity_max') ? parseInt($(elt).readAttribute('quantity_max')) : 1);
    var _step = ($(elt).readAttribute('step') ? parseInt($(elt).readAttribute('step')) : 1);
    if ((parseInt($(elt).value) + _step ) <= _max) $(elt).value = parseInt($(elt).value) + _step;
    AV911.Utility.manageButtons(btn, $(btn).previous('input.decrement-btn'), _min, _max, $(elt).value);
  },
  decrementElt : function(elt, btn) {
    if (!$(elt)) return;
    var _min  = ($(elt).readAttribute('quantity_min') ? parseInt($(elt).readAttribute('quantity_min')) : 1);
    var _max  = ($(elt).readAttribute('quantity_max') ? parseInt($(elt).readAttribute('quantity_max')) : 1);
    var _step = ($(elt).readAttribute('step') ? parseInt($(elt).readAttribute('step')) : 1);
    if ((parseInt($(elt).value) - _step ) >= _min)  $(elt).value = parseInt($(elt).value) - _step;
    AV911.Utility.manageButtons($(btn).next('input.increment-btn'), $(btn), _min, _max, $(elt).value);
  },
  manageButtons: function(incr, decr, min, max, qty) {
    if (qty == min) {
      $(decr).addClassName('disabled').writeAttribute('disabled', 'disabled');
      if (max > qty) {
        $(incr).removeClassName('disabled').removeAttribute('disabled');
      }
    }
    else if (qty == max) {
      $(incr).addClassName('disabled').writeAttribute('disabled', 'disabled');
      $(decr).removeClassName('disabled').removeAttribute('disabled');
    }
    else {
      [$(decr), $(incr)].each(function(btn) {
        $(btn).removeClassName('disabled').removeAttribute('disabled');
      });
    }
  },
  openPageinDialog: function(code) {
     new Kwo.Dialog("/content.dialog", {"code": code},
                   {width:700, height:400, className:"layout-hbox"});
  },
  clickTopPanel: function(event) {
    var elt = event.findElement('.button_connection');
    var tar = Event.element(event);
    if (!Object.isElement(elt)) { return; }
    
    event.stop();
    if (tar == $('sublog')) {
      Kwo.Auth.onSignIn($('sublog').up('form'));
    } else {
      elt.stopObserving('mouseout');
      document.observe('click', AV911.Utility.hideTopPanel.bindAsEventListener(elt, elt));
    }
  },
  showTopPanel: function(event) {
    var elt = event.findElement('.button_connection');
    if (!elt) elt = event.findElement('.button_cart');
    if (!Object.isElement(elt)) { return; }
    
    event.stop();
    if (AV911.Utility._topPanel && AV911.Utility._topPanel != elt) AV911.Utility.hideTopPanel(AV911.Utility._topPanel);
    AV911.Menu.changePosition('static'); 
    AV911.Utility._topPanel = elt;
    AV911.Menu.hideSelect();
    $(elt).down('span.intercale').show();  
    if ($(elt).hasClassName('button_connection')) $(elt).down('span.abso_connection_box').show();
    if ($(elt).hasClassName('button_cart')) $(elt).down('span.abso_cart_box').show();
  },
  hideTopPanel: function(event, element) {
    if (element) {
      var elt = element;
      $('button_connection').observe('mouseout', AV911.Utility.hideTopPanel.bindAsEventListener($('button_connection')));
    } else {
      var elt = event.findElement('.button_connection');
      if (!elt) elt = event.findElement('.button_cart');
    }
    if (!Object.isElement(elt)) { return; }
    
    event.stop();
    AV911.Menu.changePosition('relative'); 
    $(elt).down('span.intercale').hide(); 
    if ($(elt).hasClassName('button_connection')) $(elt).down('span.abso_connection_box').hide();
    if ($(elt).hasClassName('button_cart')) $(elt).down('span.abso_cart_box').hide();
    AV911.Utility._topPanel = null;
    AV911.Menu.showSelect();
    document.stopObserving('click');
  }
};

AV911.Menu = {

  lvl2height : 0,
  menu_el: null,

  showMenu : function(el) {

    $$('div.sub-menu, div.sousmenu_box').each(function(submenu) { AV911.Menu.hideMenu($(submenu)); });
    var li = $(el).up('li.lvl1');
    li.addClassName('isOpen');
    var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
    if (isIE6) marginLeft = li.readAttribute('position-ie-6');
    else marginLeft = li.readAttribute('position');
    //alert(marginLeft);
    if (isIE6) marginLeft = parseInt(marginLeft) - 18;
    li.down('div.sousmenu_box').setStyle({'left' : '-'+marginLeft+'px'});
    li.down('div.intercale').setStyle({'width' : li.getWidth()+'px'});

    var intercale_width = isIE6 ? (li.getWidth() - 2) : li.getWidth();
    li.down('div.intercale').setStyle({'width': intercale_width+'px'});

    li.down('div.intercale').setStyle({'marginLeft' : marginLeft+'px'});
    $(el).show();
    if ($(el).down('a.lvl2_link')) {
    	AV911.Menu.lvl2height = $(el).down('a.lvl2_link').getHeight();
  	}
    AV911.Menu.hideSelect();
    AV911.Menu.menu_el = el;
    
    new PeriodicalExecuter(function () {
      this.stop();
      document.observe('mousemove', function(event){
      	var thisElem = Event.element(event);
      	//console.log(thisElem.classNames());
        if (thisElem && (thisElem.hasClassName('sousmenu_box, lvl1') || thisElem.up('.sousmenu_box, .lvl1'))) {
        	 return true;
        } else {
        	document.stopObserving('mousemove');
        	AV911.Menu.hideMenu(AV911.Menu.menu_el);
      	}
      });
    }, 0.5);
    
  },
  hideMenu : function(el) {   
    if (!$(el) || !$(el).up('li.lvl1')) return;
    var li = $(el).up('li.lvl1');
    li.removeClassName('isOpen');
    $(el).hide();
    AV911.Menu.showSelect();
    AV911.Menu.menu_el = null;
  },
  /*showSubMenu : function(el) {
    $(el).up('.lvl2_box').select('ul.lvl3_box').each(function(ul) { $(ul).hide(); });
    $$('li.lvl2').each(function(li) { $(li).removeClassName('selected'); });

    var li_lv2_count = $(el).up('ul.lvl2_box').select('li.lvl2').length;
    var lvl2_box_height = li_lv2_count * AV911.Menu.lvl2height;
    var lvl3_box_height = $(el).select('li.lvl3').length * 22;

    if (lvl2_box_height > lvl3_box_height) {
      $(el).setStyle({'height': lvl2_box_height + 'px'});
      $(el).up('.lvl2_box').setStyle({'height': lvl2_box_height + 'px'});
    } else {
      $(el).up('.lvl2_box').setStyle({'height': (lvl3_box_height + 20) + 'px'});
    }
    $(el).up('li.lvl2').addClassName('selected');
    $(el).show();
  },
  hideSubMenu : function(el) {
    $(el).show();
  },*/


  /* ---------------------------------------------------- */
  showSubMenu2 : function(el) {
    el = $(el);
    $$('ul.lvl3_box').each(function(ul) { $(ul).hide(); });
    $$('li.lvl2').each(function(li) { $(li).removeClassName('selected'); });

    el.up('li.lvl2').addClassName('selected');

    $('lvl3-box-' + el.readAttribute("data-id")).show();
  },
  hideSubMenu2 : function(el) {
    $(el).show();
  },
  /* ------------------------------------------- */



  showSimpleMenu : function(el) {
    $$('div.sub-menu, div.sousmenu_box').each(function(submenu) { AV911.Menu.hideMenu($(submenu)); });
    var li = $(el);
    var submenu = li.down('div.sub-menu', 0);
    //alert(li.getWidth());
    if (submenu.getWidth() < li.getWidth()) {
      submenu.setStyle({'width' : li.getWidth()+'px'});
    }  
    li.addClassName('isOpen');
    marginLeft = li.readAttribute('position');

    var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
    var resize_intercale = li.down('div.intercale').readAttribute('noresize') ? 0 : 1 ;
    var intercale_width  = isIE6 && resize_intercale ? (li.getWidth() - 2) : li.getWidth();
    
    li.down('div.intercale').setStyle({'width': intercale_width+'px'});

    if (submenu.hasClassName('right')) {
      li.down('div.intercale').setStyle({'float': 'right'});
      li.down('div.intercale').setStyle({'margin': '0'});
    }
    submenu.show();
    AV911.Menu.hideSelect();
    AV911.Menu.menu_el = el;
    
    new PeriodicalExecuter(function () {
      this.stop();
      document.observe('mousemove', function(event){
      	var thisElem = Event.element(event);
        if (thisElem && (thisElem.hasClassName('sousmenu_box, lvl1') || thisElem.up('.sousmenu_box, .lvl1'))) {
        	 return true;
        } else {
        	document.stopObserving('mousemove');
        	AV911.Menu.hideSimpleMenu(AV911.Menu.menu_el);
      	}
      });
    }, 0.5);
    
  },
  hideSimpleMenu : function(el) {
    var li = $(el);
    if (!li) return;
    var submenu = li.down('div.sub-menu', 0);
    if (!submenu) return;
    li.removeClassName('isOpen');
    submenu.hide();
    AV911.Menu.showSelect();
  },

  hideSelect: function() {
    var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
    if (isIE6) {
      $$('select.true-select').each(function(elt) {
        elt.setStyle({display: 'none'});
      });
      $$('span.ie6-fake-select').each(function(elt) {
        elt.setStyle({display: 'inline'});
      });
    }
  },
  showSelect: function() {
    var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
    if (isIE6 ) {
      $$('select.true-select').each(function(elt) {
        elt.setStyle({display: 'inline'});
      });
      $$('span.ie6-fake-select').each(function(elt) {
        elt.setStyle({display: 'none'});
      });
    }
  },
  
  changePosition: function(position) {
    $('menu').setStyle({'position':position}); 
    $$('#menu li.lvl1').invoke('setStyle', {'position':position}); 
  }
  
};

AV911.Searcher = {
  current_elt: null,
  updateSearch : function(elt, offset) {
    if ($(elt).tagName.toUpperCase() == "FORM")  _form = $(elt);
    else {
      _form = $(elt).up('form');
      this.current_elt = elt;
    }
    offset = offset || 0;
    $('offset').value = offset;
    $('products-result').update('<img src="/app/av911/pix/ajax-loader.gif" />');
    //AV911.Searcher.resetSelects(elt);
    //Kwo.exec('/products.update', _form , {'callback': AV911.Searcher.callbackUpdateParams} );
    Kwo.exec(_form.action, _form , {'container': 'products-result'});
  },
  callbackUpdateParams : function (res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    var _selects = ['type-id','subtype-id'];
    _selects.each(function(el){
      if ($(AV911.Searcher.current_elt).id != el) {
        if (res['result']['select'][el]) {
          var _selected = $(el).value;
          $(el).update('');
          res['result']['select'][el].each(function(opt_values){
            var opt = new Element('option');
            opt.value   = opt_values.id;
            opt.innerHTML = opt_values.name;
            opt.select    = true;
            $(el).appendChild(opt);
          });
        }
      }
    });
  },
  resetSelects : function(elt) {
    if ($(elt).tagName.toUpperCase() == "FORM")  _form = $(elt);
    else _form = $(elt).up('form');
    _form.select('select').each(function(el){
      $(el).options[0].selected = true;
    });
    _form.select('input[type=checkbox]').each(function(el){
      $(el).checked = false;
    });
    AV911.Searcher.updateSearch(elt);
  },
  updatePrices : function (elt) {
    if (elt.min_value) $('price-min').value = elt.min_value;
    if (elt.max_value) $('price-max').value = elt.max_value;
    AV911.Searcher.updateSearch('products-search-form');
  }
};

AV911.Product = {
  default_image : '',
  quantity_max : 1,
  quantity_min : 1,
  step : 1,
  updateColors : function(item_key, target) {
    if (Object.isElement(item_key)) {
      var args = {"item_key": $(item_key).value};
      AV911.Product.updateKey(target, $(item_key).value);
    } else {
      var args = {"item_key": item_key};
    }
    Kwo.exec('/product.colors', args, {'callback': AV911.Product.callbackUpdateColors});
  },
  updatePrice : function(element) {
    element = element.down('option', element.selectedIndex);
    if (element.hasAttribute('data-src-old') && $('product-price').down('span.old-price') && element.readAttribute('data-src-new') != element.readAttribute('data-src-old')) {
      $('product-price').down('span.old-price').show();
      $('product-price').down('span.old-price').update('<strike>' + element.readAttribute('data-src-old') + '</strike>');
    } else {
      $('product-price').down('span.old-price').hide();
    }
    if (element.hasAttribute('data-src-promo') && element.readAttribute('data-src-promo') > 0 && $('product-price').down('span.promo-percent')) {
      $('product-price').down('span.promo-percent').show();
      $('product-price').down('span.promo-percent').update('-' + element.readAttribute('data-src-promo') + '<span class="small">%</span>');
    } else {
      $('product-price').down('span.promo-percent').hide();
    }
    $('product-price').down('span.price').update(element.readAttribute('data-src-new'));
  },
  callbackUpdateColors : function (res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    $('product-colors').update('');
    res['result']['colors'].each(function(el){
      var opt = new Element('option');
      opt.value     = el.item_key;
      opt.innerHTML = el.name;
      opt.writeAttribute('quantity_min', el.quantity_min);
      opt.writeAttribute('quantity_max', el.quantity_max);
      opt.writeAttribute('data-src-new', el.price);
      opt.writeAttribute('data-src-old', el.old);
      opt.writeAttribute('data-src-promo', el.promo);
      opt.writeAttribute('step', el.step);
      if (($('exchanger') && $('exchanger').readAttribute('data-size-key') == el.item_key) || el.selected) {
        opt.writeAttribute('selected', 'selected');
      }
      $('product-colors').appendChild(opt);
    });
    AV911.Product.updateKey('add-product', $('product-colors').value);
  },
  updateKey : function (elt, item_key) {
    $(elt).writeAttribute('data-item-key', item_key);
    var _option = $('product-colors').options[$('product-colors').selectedIndex];
    AV911.Product.quantity_min = (_option.readAttribute('quantity_min')? parseInt(_option.readAttribute('quantity_min')) : 1 );
    AV911.Product.quantity_max = (_option.readAttribute('quantity_max')? parseInt(_option.readAttribute('quantity_max')) : 1 );
    AV911.Product.step = (_option.readAttribute('step')? parseInt(_option.readAttribute('step')) : 1 );
    if ($('exchanger') && !$('exchanger').hasAttribute('qty-read')) {
      $('exchanger').writeAttribute('qty-read', true);
    } else {
      $('product-quantity').value = AV911.Product.quantity_min;
    }
    if (AV911.Product.quantity_max > AV911.Product.quantity_min) {
      $('product-quantity').next().removeClassName('disabled').enable();
    } else {
      if (!$('product-quantity').next().hasClassName('disabled')) {
        $('product-quantity').next().addClassName('disabled').disable();
      }
    }
  },
  switchImage : function (elt, defaultImg) {
    defaultImg = defaultImg || false;
    if (!defaultImg) {
      this.default_image = $('default-image').readAttribute('src');
      $('default-image').writeAttribute('src', $(elt).readAttribute('src_pdt'));
      $('default-image').writeAttribute('src_zoom', $(elt).readAttribute('src_zoom'));
      $('default-image').writeAttribute('alt', $(elt).readAttribute('alt'));
    }
    else {
      $('default-image').writeAttribute('src', this.default_image);
    }
  },
  incrementQuantity : function(elt, btn) {
    if ($(elt) && (parseInt($(elt).value) + AV911.Product.step ) <= AV911.Product.quantity_max) $(elt).value = parseInt($(elt).value) + AV911.Product.step;

    AV911.Utility.manageButtons($(btn), $(btn).previous('input.decrement-btn'),
                                AV911.Product.quantity_min, AV911.Product.quantity_max, $(elt).value);
  },
  decrementQuantity : function(elt, btn) {
    if ($(elt) && (parseInt($(elt).value) - AV911.Product.step ) >= AV911.Product.quantity_min)  $(elt).value = parseInt($(elt).value) - AV911.Product.step;

    AV911.Utility.manageButtons($(btn).next('input.increment-btn'), $(btn),
                                AV911.Product.quantity_min, AV911.Product.quantity_max, $(elt).value);
  },
  currencyChange : function(code, id) {
    Kwo.exec('/product.price', {'code':code, 'article_id':id} , {'container': 'product-price'});
  },
  currenciesListShow: function(elt) {
    $(elt).select('.currencies-list')[0].show();
    $(elt).removeClassName('closed');
    $(elt).addClassName('opened');
    new PeriodicalExecuter(function () {
      if ($('currencies').hasClassName('closed')) return;
      this.stop();
      document.observe('click', function(){
        document.stopObserving('click');
        $('currencies').select('.currencies-list')[0].hide();
        $('currencies').removeClassName('opened');
        $('currencies').addClassName('closed');
      });
    }, 0.1);
  },
  zoomImage : function (elt) {
    if ($(elt).readAttribute('src_zoom') == '') return;
    if (parseInt($(elt).readAttribute('src_zoom')) == $(elt).readAttribute('src_zoom')) {
      new Kwo.Dialog("/product.image", {"article": $(elt).readAttribute('src_zoom')},
                     {height:(700+40), className:"layout-hbox"});
      $$('.dialog-overlay').invoke('setStyle', {opacity: '0.8', filter :'alpha(opacity=80)'});
    } else {
      _image = new Image();
      _image.src = $(elt).readAttribute('src_zoom');
      new Kwo.Dialog("/product.image", {"image": $(elt).readAttribute('src_zoom')},
                     {height:(700+40), className:"layout-hbox"});
      $$('.dialog-overlay').invoke('setStyle', {opacity: '0.8', filter :'alpha(opacity=80)'});
    }
  }
};

AV911.Gift = {
  edit : function (elt) {
    new Kwo.Dialog("/gift.edit", {"item_key": $(elt).readAttribute("data-item-key")},
                   {width:500, height:200, className:"layout-hbox"});
  }
};

AV911.Cart = {
  addPurchase : function (elt) {
    if ($('product-quantity')) {
      var quantity = parseInt($('product-quantity').value);
      Kwo.Cart.addPurchase($(elt).readAttribute("data-item-key"), quantity);
    }
    else {
      Kwo.Cart.addPurchase($(elt).readAttribute("data-item-key"));
    }
    Kwo.Cart.updateWidget();
  },
  addGiftPurchase : function (args) {
    Kwo.exec("/gift.cart.add", args, {callback: function(res) {
      if (Kwo.hasError(res)) return Kwo.error(res);
      Kwo.Cart.view();
    }});
  },
  deletePurchase: function(elt) {
    elt = $(elt);
    var args = {item_key: elt.readAttribute("data-item-key")};
    Kwo.exec("/shop/purchase.delete", args, {confirm:elt});
  }
};


AV911.Coupon = {
  onCheck: function(args) {
    if (!Kwo.isAuth()) {
      var auth = new Kwo.Class.Auth();
      auth.onCallback = AV911.Coupon.onCheck;
      return ;
    }
    args = args || {'code': $('coupon-enter').down('input').value};
    Kwo.exec("/shop/coupon.check", args,
             {callback: AV911.Coupon.onCheckCallback});
  },

  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"]);
    $("coupon-enter").hide();
    $("coupon-valid").show();

    var args = $('cart-form');
    Kwo.exec("/shop/order.update", args,
             {callback: function (res) {
               if (Kwo.hasError(res)) return Kwo.error(res);
               Kwo.go("/shop/cart", null);
             }});

  },
  
  onRemove: function() {
    if (!Kwo.isAuth()) {
      var auth = new Kwo.Class.Auth();
      auth.onCallback = AV911.Coupon.onRemove;
      return ;
    }
    Kwo.exec("/account/av911/coupon.remove", null, {'callback': function(res) {
      if (Kwo.hasError(res)) return Kwo.error(res);
      Kwo.go("/shop/cart", null);
    }});
  }
};



AV911.SAV = {
  edit : function (user_id) {
    new Kwo.Dialog("/account/av911/sav.edit", {"user_id": user_id},
                   {width:500, height:310, className:"layout-hbox"});
  },
  consult : function (message_id) {
    new Kwo.Dialog("/account/av911/sav.consult", {"message_id": message_id},
                   {width:500, height:410, className:"layout-hbox"});
  },
  store : function (args) {
     Kwo.exec("/account/av911/sav.store", args, {callback:function(res){ Kwo.warn(res['result']['msg']); Kwo.reload();}});
  },
  show : function (order_id) {
    new Kwo.Dialog("/account/av911/sav", {"order_id": order_id},
                   {width:700, height:400, className:"layout-hbox"});
  }
};

AV911.Contact = {
  edit : function () {
    new Kwo.Dialog("/contact", null,
                   {width:500, height:560, className:"layout-hbox"});
  },
  send : function (args) {
     Kwo.exec("/contact.send", args, {callback:AV911.Contact.callbackContact});
  },
  callbackContact : function (res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.warn(res['result']['msg']);
    Kwo.getDialog().close();
  }
};

AV911.Advert = {
  showFirstConnexionAdvert: function () {
    new Kwo.Dialog("/advert.connexion", {}, {width:648, height:398, className:"layout-hbox-2"});
  }
};


AV911.Tabs = {
  initialize : function () {
    var tab_parent_num = 0;
    var tab_nav_num;
    $$('.tabs').each(function(el){
      tab_parent_num++;
      tab_nav_num = 0;
      el.select('.tabs-navs .tabs-nav').each(function(nav){
        tab_nav_num++;
        if (tab_nav_num == 1) nav.addClassName('selected');
        nav.writeAttribute('tabs-content', 'tabs-content-'+tab_parent_num+'-'+tab_nav_num);
        nav.observe('click',AV911.Tabs.showContent.bind(nav));
      });
      tab_nav_num = 0;
      el.select('.tabs-contents .tabs-content').each(function(nav){
        tab_nav_num++;
        if (tab_nav_num > 1) nav.hide();
        nav.writeAttribute('id', 'tabs-content-'+tab_parent_num+'-'+tab_nav_num);
      });
    });
  },
  showContent : function (elt) {
    this.up('.tabs').select('.tabs-content').invoke('hide');
    this.up('.tabs').select('.tabs-nav').invoke('removeClassName', 'selected');
    var content_container = this.readAttribute('tabs-content');
    if ($(content_container)) {
      $(content_container).show();
      $(content_container).fade({ duration: 0.2, from: 0, to: 1 });
    }
    this.addClassName('selected');
  }
};

AV911.Diaporama = Class.create({
  "executor": null,
  "auto": false,
  "boxMovable": null,
  "viewWidth": 0,
  "nbElements": 0,
  "deltaMove": 0,
  "nbElementsViewable": 0,
  "canMove": true,
  "initialize": function(params) {
    var boxMovable  = $(params.container).select('.container-movable')[0];
    this.boxMovable = boxMovable;
    this.viewWidth  = params.maxSlide * this.deltaMove;
    this.deltaMove  = params.deltaMove;
    this.nbElements = boxMovable.select('.slide').length;
    this.nbElementsViewable = params.maxSlide;
    this.auto = params.auto | false;
    $(params.container).select('.slide_arrow_left')[0].observe("click", this.moveRight.bind(this));
    $(params.container).select('.slide_arrow_right')[0].observe("click", this.moveLeft.bind(this));
    this.loadExecutor();
    //this.boxMovable.observe("click", this.moveRight.bind(this));
   },
  "moveLeft": function() {
    if(this.nbElements < this.nbElementsViewable || !this.canMove) return;
    var left = this.boxMovable.style.left;
    left = left.substring(0, left.indexOf('px'));
    if (Math.abs(left) % this.deltaMove != 0) return;
    if (left <= - this.boxMovable.getWidth() + this.viewWidth) return;
    this.canMove = false;
    new Effect.MoveBy(this.boxMovable, 0, -this.deltaMove, { duration:0.5, fps:25, from:0.0, to:1.0, afterFinish:this.effectCallback.bind(this).curry('left')});
  },
  "moveRight": function() {
    if(this.nbElements < this.nbElementsViewable  || !this.canMove) return;
    var left = this.boxMovable.style.left;
    left = left.substring(0, left.indexOf('px'));
    //if(Math.abs(left) % this.deltaMove != 0) return;
    //if(left >= 0) return;
    this.boxMovable.setStyle({'left':("-"+this.deltaMove+"px")});
    this.canMove = false;
    new Effect.MoveBy(this.boxMovable, 0, this.deltaMove, { duration:0.5, fps:25, from:0.0, to:1.0, beforeStart:this.effectCallback.bind(this).curry('right'),afterFinish : this.setCanMove.bind(this).curry(true)});
  },
  "effectCallback": function (direction) {
    this.loadExecutor();
    if (direction == 'left') {
      elt = this.boxMovable.down('.slide');
      for (i=0; i<this.nbElementsViewable; i++) {
        var next_elt = elt.next('.slide');
        this.boxMovable.appendChild(elt);
        elt = next_elt;
      }
      this.boxMovable.setStyle({'left':0});
      this.canMove = true;
    }
    else {
      top_elt = this.boxMovable.down('.slide');
      var last_elt = top_elt;
      while( last_elt.next('.slide')) {
        last_elt = last_elt.next('.slide') ;
      }
      elt = this.boxMovable.select('.slide')[12];
      for (i=0; i<this.nbElementsViewable; i++) {
        var previous_elt = last_elt.previous('.slide');
        new Insertion.Before(top_elt, last_elt);
        last_elt = previous_elt;
        top_elt = this.boxMovable.down('.slide');
      }
    }
  },
  "setCanMove": function (value) {
    this.canMove = value;
  },
  "loadExecutor": function() {
    if (!this.auto) return;
    if (this.executor != null) {
      this.executor.stop();
    }
    this.executor = new PeriodicalExecuter(this.moveLeft.bind(this), 6);
  }
});

AV911.SlideImage = Class.create({
  "current_position": 0,
  "max_position": 0,
  "left": 0,
  "elt":null,
  "time":10,
  "timer":null,
  "initialize": function (params) {
    if (!$(params.container)) {
      return;
    }
    this.elt = $(params.container);
    this.max_position = $(params.container).select('a').length;
    for (var i=1; i<= this.max_position ; i++ ) {
      var a = new Element('a', { 'class': (i==1? 'selected':''), href: 'javascript:void(0)' }).update(i);
      a.observe("click", this.moveSlide.bind(this).curry(null, i-1));
      this.elt.select('.slider-pagination')[0].insert(a);
    }
    this.timer = new PeriodicalExecuter(this.moveSlide.bind(this), this.time);
  },
  "moveSlide" : function (elt, index) {
    this.timer.stop();
    this.timer = new PeriodicalExecuter(this.moveSlide.bind(this), this.time);
    if (!Object.isNumber(index)) {
      this.current_position++;
      index = this.current_position;
    }
    else this.current_position = index;
    if (this.current_position >= this.max_position) this.current_position = index = 0;
    elt         = $(this.elt).select('.slider-images a')[index];
    var offset  = elt.positionedOffset();
    var parent  = elt.up('.slider-images');
    var _offset = parent.positionedOffset();
    this.left   = Math.abs(_offset[0])-offset[0];
    if (this.current_position == 0) {
      offset = parent.positionedOffset();
      this.left = Math.abs(offset[0]);
    }
    $(this.elt).select('.slider-pagination a').invoke('removeClassName', 'selected');
    $(this.elt).select('.slider-pagination a')[this.current_position].addClassName('selected');
    new Effect.Move(parent, { x: this.left ,  transition: Effect.Transitions.spring });
  }
});

AV911.Slidebar = Class.create({
  "elt": null,
  "larrow": null,
  "rarrow": null,
  "lhand": null,
  "rhand": null,
  "min_input": null,
  "max_input": null,
  "callback": Prototype.emptyFunction,
  "last_position": 0,
  "new_position": 0,
  "slide_width": 0,
  "margin_left": 0,
  "ratio": 1.25,
  "min_value": 0,
  "max_value": 0,
  "delta":70,
  "initialize": function (params) {
    if (!$(params.container)) {
      return;
    }
    if (typeof params.callback != "function" && params.callback != null) {
      return;
    }
    this.elt = $(params.container);
    this.larrow = $(this.elt).down('.left-arrow');
    this.rarrow = $(this.elt).down('.right-arrow');
    this.min_input = $(this.elt).down('input.min-value');
    this.max_input = $(this.elt).down('input.max-value');
    this.rarrow = $(this.elt).down('.right-arrow');
    this.lhand = this.larrow.down('.hand');
    this.rhand = this.rarrow;
    this.larrow.observe("mousedown", this.onLeftArrowClick.bind(this));
    this.rarrow.observe("mousedown", this.onRightArrowClick.bind(this));
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    this.chooseBetterPlace();
    this.updateLeftArrowInput();
    this.updateRightArrowInput();
    if (params.callback != null) {
      this.callback = params.callback;
    }
  },
  "onLeftArrowMove": function(e) {
    var delta = (this.last_position - e.clientX);
    this.last_position = e.clientX;
    if ((this.slide_width + delta) <= this.delta
        || (this.margin_left - delta) < 0) {
      return;
    }
    this.slide_width = this.slide_width + delta;
    this.margin_left = this.margin_left - delta;
    this.larrow.setStyle({'width': this.slide_width + 'px',
                          'marginLeft': this.margin_left + 'px'});
    document.body.focus();
  },
  "onRightArrowMove": function(e) {
    var delta = (this.last_position - e.clientX);
    this.last_position = e.clientX;
    if ((this.slide_width - delta) <= this.delta
        || (this.slide_width - delta + this.margin_left) >= 206) {
      return;
    }
    this.slide_width = this.slide_width - delta;
    this.larrow.setStyle({'width': this.slide_width + 'px'});
    document.body.focus();
  },
  "onLeftArrowClick": function(e) {
    if ($(e.target).match('.right-arrow')
        || !$(e.target).match('.hand')) {
      return;
    }
    this.last_position = e.clientX;
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    if (typeof this.onLeftArrowMoveBind != "function") {
      this.onLeftArrowMoveBind = this.onLeftArrowMove.bind(this);
    }
    if (typeof this.onLeftArrowReleaseBind != "function") {
      this.onLeftArrowReleaseBind = this.onLeftArrowRelease.bind(this);
    }
    document.observe('mousemove', this.onLeftArrowMoveBind);
    document.observe('mouseup', this.onLeftArrowReleaseBind);
    document.onselectstart = function () { return false; }
  },
  "onRightArrowClick": function(e) {
    this.last_position = e.clientX;
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    if (typeof this.onRightArrowMoveBind != "function") {
      this.onRightArrowMoveBind = this.onRightArrowMove.bind(this);
    }
    if (typeof this.onRightArrowReleaseBind != "function") {
      this.onRightArrowReleaseBind = this.onRightArrowRelease.bind(this);
    }
    document.observe('mousemove', this.onRightArrowMoveBind);
    document.observe('mouseup', this.onRightArrowReleaseBind);
    document.onselectstart = function () { return false; }
  },
  "onLeftArrowRelease": function() {
    document.stopObserving('mousemove', this.onLeftArrowMoveBind);
    document.stopObserving('mouseup', this.onLeftArrowReleaseBind);
    this.chooseBetterPlace();
    this.updateLeftArrowInput();
    document.onselectstart = Prototype.emptyFunction;
  },
  "onRightArrowRelease": function() {
    document.stopObserving('mousemove', this.onRightArrowMoveBind);
    document.stopObserving('mouseup', this.onRightArrowReleaseBind);
    this.chooseBetterPlace();
    this.updateRightArrowInput();
    document.onselectstart = Prototype.emptyFunction;
  },
  "chooseBetterPlace": function() {
    var step = 10;
    var delta = 0;
    if (this.margin_left%step != 0) {
      if ((this.margin_left%step) > step/2) {
        delta = (step - this.margin_left%step);
      } else {
        delta = - this.margin_left%step;
      }
      this.margin_left += delta;
      this.slide_width -= delta;
      this.larrow.setStyle({'marginLeft': this.margin_left + 'px',
                            'width': this.slide_width + 'px'});
    }
    if (this.slide_width%step != 0) {
      if ((this.slide_width%step) > step/2) {
        this.slide_width = this.slide_width + (step - this.slide_width%step);
      } else {
        this.slide_width = this.slide_width - this.slide_width%step;
      }
      if (this.slide_width <= this.delta) {
        this.slide_width = this.delta;
      }
      this.larrow.setStyle({'width': this.slide_width + 'px'});
    }
  },
  "updateRightArrowContent": function() {
    var value = this.max_value;
    if (this.max_value == 500) {
      value = '+ ' + value;
    }
    this.rhand.innerHTML = value + " &euro;";
  },
  "updateLeftArrowContent": function() {
    this.lhand.innerHTML = this.min_value + " &euro;";
  },
  "updateRightArrowInput": function () {
    this.max_value = parseInt((this.margin_left + this.slide_width) * this.ratio - this.delta);
    if (this.max_input.value != this.max_value) {
      this.max_input.value = this.max_value;
      this.callback({"max_value": this.max_value});
      this.updateRightArrowContent();
    }
  },
  "updateLeftArrowInput": function () {
    this.min_value = parseInt(this.margin_left * this.ratio + 0);
    if (this.min_input.value != this.min_value) {
      this.min_input.value = this.min_value;
      this.callback({"min_value": this.min_value});
      this.updateLeftArrowContent();
    }
  }

});

AV911.SlideShow = Class.create({
  "timeout": null,
  "mask": null,
  "nav": null,
  "count": 0,
  "pos": 0,
  "z": 1,
  "initialize": function (id, opts) {
    this.isIE = navigator.userAgent.toLowerCase().indexOf('msie') != -1;
    this.pos = 0;
    this.mask = $(id);
    this.width = this.mask.getWidth();
    this.count = this.mask.childElements().length;
    this.mask.childElements().invoke('setStyle',{left:'0px',top:'0px'}).invoke('hide');
    $('item'+this.pos).show();

    if (this.count > 1) {
      this.mask.observe("mouseout",this.play.bind(this));
      this.mask.observe("mouseover",this.pause.bind(this));
      if (opts.prev && $(opts.prev)) {
        $(opts.prev).observe('click', this.prev.curry(null).bind(this));
      }
      if (opts.next && $(opts.next)) {
        $(opts.next).observe('click', this.next.curry(null).bind(this));
      }
      if (opts.nav && $(opts.nav)) {
        this.nav = opts.nav;
        $(this.nav).childElements().each(function(s, index) {
          $(s).observe('click', this.view.curry(index).bind(this));
        }, this);
      }
      $(this.nav).down('span').addClassName('selected');
      this.play();
    }
  },
  "play": function () {
    this.pause();
    this.timeout = window.setTimeout(this.next.curry(null).bind(this), 8000);
  },
  "pause": function () {
    if (this.timeout) window.clearTimeout(this.timeout);
  },
  "view": function (pos) {
    this.pause();
    if (pos > this.pos) {
      this.next(pos);
    } else if (pos < this.pos) {
      this.prev(pos);
    }
    this.play();
  },
  "next": function (pos) {
    last_pos = this.pos;        
    if (Object.isNumber(pos) && pos >= 0) this.pos = pos;
    else this.pos++;
    if (this.pos > this.count - 1) this.pos = 0;
    if (this.pos < 0) this.pos = this.count - 1;
    $('item'+last_pos).fade({from: 1, to: 0, duration: 1 });
    $('item'+this.pos).appear({from: 0, to: 1, duration: 1 });    
    this.page();
    this.play();    
  },
  "prev": function (pos) {   
    last_pos = this.pos;        
    if (typeof pos == 'number' && pos >= 0) this.pos = pos;
    else this.pos--;
    if (this.pos > this.count - 1) this.pos = 0;
    if (this.pos < 0) this.pos = this.count - 1;
    $('item'+last_pos).fade({from: 1, to: 0, duration: 1 });
    $('item'+this.pos).appear({from: 0, to: 1, duration: 1 });    
    this.page();
    this.play();      
  },
  "page": function () {
    var list = $(this.nav).select('*');
    list.each(function(s) { s.removeClassName("selected"); });
    list[this.pos].addClassName("selected");
  }
});

AV911.Brand = {
  'display': function(element, selector) {
    $$('.brand_tab').each(function(elm) {
      if (elm.hasClassName('selected')) {
        elm.removeClassName('selected');
      }
    });
    element.addClassName('selected');
    $$('.brand_panel').each(function(elm) {
      elm.hide();
      if (elm.readAttribute('data-src') == selector) {
        elm.show();
      }
    });
  }
};

AV911.SoColissimo = {
  SHA1_Key: 891059084490,
  URL: 'http://ws.colissimo.fr/pudo-fo/storeCall.do',
  
  'callDialog': function(value) {
    new Kwo.Dialog("/account/av911/so.colissimo.iframe", {'addressee_id':value}, {'width':776, 'height':192});
  },
  'calcSignature': function(form) {
    var params = ['pudoFOId', 'ceName', 'dyPreparationTime', 'dyForwardingCharges', 'trClientNumber', 'trOrderNumber',
                  'orderId', 'numVersion', 'ceCivility', 'ceFirstName', 'ceCompanyName', 'ceAdress1', 'ceAdress2',
                  'ceAdress3', 'ceAdress4', 'ceZipCode', 'ceTown', 'ceEntryPhone', 'ceDeliveryInformation', 'ceEmail',
                  'cePhoneNumber', 'ceDoorCode1', 'ceDoorCode2', 'dyWeight', 'trFirstOrder', 'trParamPlus'];
    var str = '';
    var signature = '';
    
    params.each(function(param) {
      if (form.down('input[name=' + param + ']')) {
        str += form.down('input[name=' + param + ']').value;
      }
    });
    str += form.readAttribute('data-return');
    str += form.down('input[name=trReturnUrlOk]').value;
    str += AV911.SoColissimo.SHA1_Key;
    
    signature = AV911.SHA1.calc(str);
    form.down('input[name=signature]').value = signature;
  },
  'calcSignatureReturn': function(form) {
    var str = '';
    var signature = '';
    
    form.select('input').each(function(element) {
      if (element.name != 'signature') {
        str += element.value;
      }
    });
    str += AV911.SoColissimo.SHA1_Key;

    /*
    
    TO CHANGE : RETRIEVE SIGNATURE CONTROL
    
    
    
    signature = AV911.SHA1.calc(str);
    if (signature != form.down('input[name=signature]').value) {
      Kwo.go('/shop/order/-/scr-return/colissimo_error');
    } else {
      Kwo.exec('/account/av911/so.colissimo.store', form, {'callback': function(res) {
        Kwo.go('/shop/order/-/scr-confirm/colissimo');
      }});
    }*/
    Kwo.exec('/account/av911/so.colissimo.store', form, {'callback': function(res) {
      Kwo.go('/shop/order/-/scr-confirm/colissimo');
    }});
  },
  'request': function(form) {
    AV911.SoColissimo.calcSignature(form);
  },
  'return': function(form) {
    AV911.SoColissimo.calcSignatureReturn($(form));
  }
};

AV911.SHA1 = {
  'rotate_left': function(n, s) {
    var t4 = (n << s) | ( n >>> (32 - s));
    return t4;
  },
  'lsb_hex': function(val) {
    var str = '';
    var i;
    var vh;
    var v1;
    
    for (i = 0; i <= 6; i += 2) {
      vh = (val >>> (i * 4 + 4))&0x0F;
      v1 = (val >>> (i * 4))&0X0F;
      str += vh.toString(16) + v1.toString(16);
    }
    return str;
  },
  'cvt_hex': function(val) {
    var str = '';
    var i;
    var v;
    
    for (i = 7; i >= 0; i--) {
      v = (val >>> (i * 4))&0x0F;
      str += v.toString(16);
    }
    return str;
  },
  'calc': function(msg) {
    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;
    
    var msg_len = msg.length;
    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
      j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
      word_array.push(j);
    }
    
    switch(msg_len % 4) {
      case 0:
        i = 0x080000000;
        break;
      case 1:
        i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
        break;
      case 2:
        i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
        break;
      case 3:
        i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
        break;
    }
    word_array.push(i);
    
    while((word_array.length % 16) != 14) {
      word_array.push(0);
    }
    
    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3)&0x0FFFFFFFF);
    
    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
      for(i = 0; i < 16; i++) {
        W[i] = word_array[blockstart + i];
      }
      for(i = 16; i <= 79; i++) {
        W[i] = AV911.SHA1.rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
      }
      
      A = H0;
      B = H1;
      C = H2;
      D = H3;
      E = H4;
      
      for(i = 0; i <= 19; i++) {
        temp = (AV911.SHA1.rotate_left(A, 5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0FFFFFFFF;
        E = D;
        D = C;
        C = AV911.SHA1.rotate_left(B, 30);
        B = A;
        A = temp;
      }
      
      for(i = 20; i <= 39; i++) {
        temp = (AV911.SHA1.rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0FFFFFFFF;
        E = D;
        D = C;
        C = AV911.SHA1.rotate_left(B, 30);
        B = A;
        A = temp;
      }
      
      for(i = 40; i <= 59; i++) {
        temp = (AV911.SHA1.rotate_left(A, 5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0FFFFFFFF;
        E = D;
        D = C;
        C = AV911.SHA1.rotate_left(B, 30);
        B = A;
        A = temp;
      }
      
      for(i = 60; i <= 79; i++) {
        temp = (AV911.SHA1.rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0FFFFFFFF;
        E = D;
        D = C;
        C = AV911.SHA1.rotate_left(B, 30);
        B = A;
        A = temp;
      }
      
      H0 = (H0 + A) & 0x0FFFFFFFF;
      H1 = (H1 + B) & 0x0FFFFFFFF;
      H2 = (H2 + C) & 0x0FFFFFFFF;
      H3 = (H3 + D) & 0x0FFFFFFFF;
      H4 = (H4 + E) & 0x0FFFFFFFF;
    }
    
    temp = AV911.SHA1.cvt_hex(H0) + AV911.SHA1.cvt_hex(H1) + AV911.SHA1.cvt_hex(H2) + AV911.SHA1.cvt_hex(H3) + AV911.SHA1.cvt_hex(H4);
    
    return temp.toLowerCase();
  }
};
