if (!Kwo) var Kwo = {};

var BT = {
  Class: {},
  _auth_callback: null,

  onExtranetSignIn: function(args) {
    Kwo.exec("/extranet.signin", args, {callback: BT.onAuthCallback});
    return false;
  },

  onExtranetSignOut: function(elt) {
    Kwo.exec("/extranet.signout", null,
             {callback: function(res) { Kwo.go('/extranet'); }});
  },

  onDashboardSignIn: function(args) {
    Kwo.exec("/dashboard.signin", args, {callback: BT.onAuthCallback});
    return false;
  },

  onDashboardSignOut: function(elt) {
    Kwo.exec("/dashboard.signout", null,
             {callback: function(res) { Kwo.go('/dashboard'); }});
  },

  onDeveloppeurSignIn: function(args) {
    Kwo.exec("/anbm.signin", args, {callback: BT.onAuthCallback});
    return false;
  },

  onDeveloppeurSignOut: function(elt) {
    Kwo.exec("/anbm.signout", null,
             {callback: function(res) { Kwo.go('/anbm'); }});
  },

  onAuthCallback: function(res) {
    if (Kwo.hasError(res)) {
      Kwo.warn(res["result"]["msg"]);
      return false;
    }
    Kwo.reload();
  },

  init: function() {
      BT.contentResize();
      window.onresize = function() {
        BT.contentResize();
      };
      if (Prototype.Browser.IE) {
        var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
        if (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7) {
          $$(".trans").each(BT.alphaBackgrounds);
        }
      }
  },

  contentResize : function () {
    if ($('footer-wrap')) {

      var minHeight = 0;

      if (Prototype.Browser.IE) {
          var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
          if (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7) {
              minHeight=0;
          }else {
              minHeight=10;
          }
        }

      minHeight += document.viewport.getHeight() - ( $('topnav').getHeight() + $('header').getHeight() + $('menu').getHeight() + $('content').getHeight() + $('footer-wrap').getHeight() + 10 );

      if (minHeight > 0) {
        $('scontent').writeAttribute('style', 'min-height:' + ($('content').getHeight() + minHeight) + 'px');
      }
    }
  },

  loadInRightPanel: function(url) {
    var container = $('content').select('.float-content');
    if (url && container.length > 0) {
       Kwo.exec(url, null, {container: container[0]});
    }
  },

  hideFields: function(elt, value, elt_class) {
    if ($(elt).value == value) {
      $(elt).up('form').select('.'+elt_class).each(function(elt){
        elt.up('.field').hide();
      });
    }
    else {
      $(elt).up('form').select('.'+elt_class).each(function(elt){
        elt.up('.field').show();
      });
    }
  },

  activateRollover: function() {
    if ($('content')) {
      $('content').select('input, select, textarea').each(function(el){
        el.observe('focus', BT.InputForm.addHover);
      });
    }
  },

  swapContentForLogger: function(display) {
    Kwo.exec('/community/signup', {'display':display}, {container:'content'});
  },

  explodeDate: function(elt) {
    datetime = this.selection.get().toString();
    this.hide();
    _inputs  = elt.up('div').select('input');
    _inputs[2].value = datetime.substring(0,4);
    _inputs[1].value = datetime.substring(4,6);
    _inputs[0].value = datetime.substring(6,8);
    $(elt).value = _inputs[2].value+'-'+_inputs[1].value+'-'+_inputs[0].value;
  },

  implodeDate: function(elt, target) {
    _inputs  = $(target).up('div').select('input');
    $(target).value = _inputs[2].value+'-'+_inputs[1].value+'-'+_inputs[0].value;
    if ( parseInt($(elt).readAttribute('maxlength')) == $(elt).value.length && $(elt).next('input')) {
      if($(elt) != $('annee_input')){
        $(elt).next('input').focus();
      }
    }
  },

  getDialog: function(code, _width, _height) {
    new Kwo.Dialog("/cms/page/",
                   {"code": code},
                   {width:_width, height:_height, name:"service"});
  },
  "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"});
    }
  }
};

// ----------
BT.Class.Alert = Class.create(Kwo.Dialog, {
  initialize: function($super, content) {
    this.name = "alert";
    this.width = 500;
    this.height = 150;
    this.content = content;
    $super(this.onDisplay);
  },

  onDisplay: function() {
    Kwo.exec("/alert", {content: this.content}, {container: this.support});
  }
});

BT.Class.Confirm = Class.create(Kwo.Dialog, {
  initialize: function($super, args) {
    this.name = "confirm";
    this.width = 500;
    this.height = 200;
    this.content = args.content;
    this.ok = args.ok;
    this.ko = function() {this.close(); return false;};
    $super(this.onDisplay);
  },

  onDisplay: function() {
    Kwo.exec("/confirm", {content: this.content}, {container: this.support});
  }
});

//--------------------
BT.Extranet = {
  target_elt: null,

  onMenuOver: function(elt) {
    new Effect.Morph($(elt), {style: 'padding-right:25px;', duration: 0.2});
  },

  onMenuOut: function(elt) {
    new Effect.Morph($(elt), {style: 'padding-right:15px;', duration: 0.2});
  },

  getCity: function(elt, target) {
    $('autocompletion').hide();
    BT.Extranet.target_elt = target;
    if ($(elt).value.length == 5) {
      Kwo.exec("/pc.city", {'postal_code': (elt).value},
               {callback: BT.Extranet.getCityCallback});
    }
  },

  getCityCallback: function(res) {
    if (Kwo.hasError(res)) {
      BT.Extranet.target_elt.clear();
      return Kwo.error(res);
    } else if (!res.result.items){
      return ;
    } else {
      var dropdown = $('autocompletion-content');
      dropdown.update(res.result.items);
      dropdown.select('a').each(function(link) {
        link.observe('click', BT.Extranet.citySelect);
      });
      $('autocompletion').show();
      if(Object.isElement($('signup_country_form'))){
        $('signup_country_form').setStyle({'visibility':'hidden'});
        $('signup_email_form').setStyle({'visibility':'hidden'});
      }
    }
  },

  citySelect: function(e) {
    BT.Extranet.target_elt.value = e.target.readAttribute("data-city");
    $('autocompletion').hide();
    if(Object.isElement($('signup_country_form'))){
       $('signup_country_form').setStyle({'visibility':'visible'});
       $('signup_email_form').setStyle({'visibility':'visible'});
    }
  },

  getCalendar : function(){
	  var date_tmp = $('user-birth-date-year').value+"-"+$('user-birth-date-month').value+"-"+$('user-birth-date-day').value;
	  $('user-birth-date').value  = date_tmp;
  },

  onOrderCancelPrompt: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.order.cancel.prompt",
                   {id: elt.readAttribute('data-id')},
                   {width: 500, height: 250});
  },

  onOrderCancel: function(elt) {
    elt = $(elt);
    Kwo.exec("/extranet.order.cancel", elt, {callback: BT.Extranet.onOrderCancelCallback });
  },

  onOrderCancelCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.reload();
  }
};

//--------------------
BT.Dashboard = {
  stockEdit: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/dashboard.stock.edit",
                   {'id': elt.readAttribute("data-id")},
                   {width: 500, height: 300});
  },

  stockStore: function(elt) {
    elt = $(elt);
    Kwo.exec("/dashboard.stock.store", elt,
             {callback: BT.Dashboard.stockCallback});
  },

  stockCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  }
};

//--------------------
BT.Support = {
  onOpen: function(elt) {
    if (!isNaN(parseFloat(elt)) && isFinite(elt)) {
      var id = parseInt(elt);
    } else {
      elt = $(elt);
      id = elt.readAttribute("data-id");
    }
    Kwo.exec("/extranet.support.open",
             {'id': id},
             {callback: BT.Support.supportOpenedCallback});
  },

  onClose: function() {
    Kwo.exec("/extranet.support.close", null,
             {callback: BT.Support.supportClosedCallback});
  },

  supportOpenedCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.go('/extranet.client.detail');
    }
  },

  supportClosedCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.go('/extranet.clients');
    }
  },

  editNote: function() {
    new Kwo.Dialog("/extranet.note.edit", null, {width: 500, height: 400});
  },

  storeNote: function(args) {
    Kwo.exec("/extranet.note.store", args,
             {callback: BT.Support.storeNoteCallback});
  },

  storeNoteCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  },

  editMembre: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.membre.edit",
                   {'id': elt.readAttribute("data-id")},
                   {width: 500, height: 630});
  },

  storeMembre: function(elt) {
    Kwo.exec("/extranet.membre.store", elt,
             {callback: BT.Support.storeMembreCallback});
  },

  storeMembreCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      if (res.result.support > 0) {
        BT.Support.onOpen(res.result.user_id);
      } else {
        Kwo.reload();
      }
    }
  },

  getNoteMotives: function(elt, target) {
    Kwo.exec("/extranet.motifs", {'id': $(elt).value},
             {callback: BT.Support.updateNoteMotives.bind($(target))});
  },

  updateNoteMotives: function(res, target) {
    this.update('');
    for (var k in res['result']['motifs']) {
      var opt = new Element('option');
      opt.value     = k;
      opt.innerHTML = res['result']['motifs'][k];
      this.appendChild(opt);
    }
    if (this.readAttribute('onchange')) this.onchange();
  }
};

//--------------------
BT.Admin = {
  editTeleoperator: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.teleoperateur.edit",
                   {'id': elt.readAttribute("data-id")},
                   {width: 500, height: 540});
  },

  storeTeleoperator: function(elt) {
    Kwo.exec("/extranet.teleoperateur.store", elt,
             {callback: BT.Admin.storeTeleoperatorCallback});
  },

  storeTeleoperatorCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  },

  enableTeleoperator: function(elt) {
     Kwo.exec("/extranet.teleoperateur.enable",
              {'id': elt.readAttribute("data-id")},
             {callback: BT.Admin.storeTeleoperatorCallback});
  },

  disableTeleoperator: function(elt) {
     Kwo.exec("/extranet.teleoperateur.disable",
              {'id': elt.readAttribute("data-id")},
              {callback: BT.Admin.storeTeleoperatorCallback});
  },

  showTeleoperatorLogs: function(elt, offset, sort) {
    offset = offset || 0;
    sort = sort || "";
    sort = sort.split('.');
    var sortf = sort[0];
    var sortw = sort[1];

    if (Kwo.getDialog()) {
      if ($('teleoperateur-logs')) {
        Kwo.exec("/extranet.teleoperateur.logs",
                 {'id': elt ,'offset': offset, 'sortf': sortf, 'sortw': sortw},
                 {container: 'teleoperateur-logs'});
      }
    }
    else {
      elt = $(elt);
      new Kwo.Dialog("/extranet.teleoperateur.logs",
                     {'id': elt.readAttribute("data-id")},
                     {width: 1000, height: 620});
    }
  },
  showCommands : function(elt){
    elt = $(elt);
      new Kwo.Dialog("/extranet.command.details",
                     {'id': elt.readAttribute("data-id")},
                     {width: 620, height: 620});
  }

};

//--------------------
BT.Souscription = {
  editAddressee: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.addressee.edit",
                   {'id': elt.readAttribute("data-id")},
                   {width: 500, height: 500});
  },

  storeAddressee: function(elt) {
    elt = $(elt);
    Kwo.exec("/extranet.addressee.store", elt,
             {callback: BT.Souscription.addresseeCallback});
  },

  addresseeCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  },

  editBilling: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.billing.edit",
                   {'id': elt.readAttribute("data-id")},
                   {width: 500, height: 300});
  },

  storeBilling: function(elt) {
    elt = $(elt);
    Kwo.exec("/extranet.billing.store", elt,
             {callback: BT.Souscription.billingCallback});
  },

  billingCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  },

  editNotification: function(elt) {
    elt = $(elt);
    new Kwo.Dialog("/extranet.souscription.notify",
                   {'souscription_id': elt.readAttribute("data-id")},
                   {'width': 500, 'height': 300});
  },

  storeNotification: function(args) {
    args = $(args);
    Kwo.exec("/extranet.souscription.transfer", args,
             {callback: BT.Souscription.storeNotificationCallback});
  },

  storeNotificationCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  },

  onStatusChange: function(elt) {
    elt = $(elt);
    Kwo.exec("/extranet.souscription.status",
             {'id': elt.readAttribute("data-id"),
              'status': elt.readAttribute("data-status")},
             {callback: BT.Souscription.onStatusChangeCallback});
  },

  onStatusChangeCallback: function(res) {
    if (Kwo.hasError(res)) {
      return Kwo.error(res);
    } else {
      Kwo.reload();
    }
  }
};

//--------------------
BT.Offre = {
  item_key: null,

  onSubmit: function(args) {
    var link = $(args);
    if (!link.hasClassName('disabled')) {
      link.addClassName('disabled');

      if ($(args).tagName.toUpperCase() != "FORM") {
        args = $(args).up('form');
      }
      if ($('condition-checkbox') && !$('condition-checkbox').checked ) {
        Kwo.warn('Veuillez cocher les conditions');
        return;
      }
      var id = $F($(args).select("input[name=itemid]")[0]);
      if($(args).select("input[type=submit]")[0]){
    	  Kwo.Form.button = $(args).select("input[type=submit]")[0];
    	  Kwo.Form.button.disable();
      }

      if ($F("kwo-form-" + id + "-errors") >= 1) {
        $$("#kwo-form-" + id + " LABEL").invoke("removeClassName", "warn");
      }
      if ($('add-to-form') && $('add-to-form').select('input').length > 0) {
        $('extern-fields').insert($('add-to-form'));
      }
      if ($$('.add-to-form').length > 0) {
        $$('.add-to-form').each(function(elt){
          $('extern-fields').insert(elt);
        });
      }
      $(args).select('input[disabled=disabled]').invoke('addClassName', 'disabled');
      $(args).select('select[disabled=disabled]').invoke('addClassName', 'disabled');
      $(args).select('select').invoke('removeAttribute', 'disabled');
      $(args).select('input').each(function(elt) { elt.removeAttribute('disabled'); });
      if ($(args).select('input[name=next-step]').length > 0) {
        Kwo.exec("/offre.load.next", $(args),
                 {"callback": BT.Offre.onSubmitCallback.bind($(args))});
      }
      else {
        Kwo.exec("/offre.request", $(args),
                 {"callback": BT.Offre.onSubmitCallback.bind($(args))});
      }
    }
    else {
      return false;
    }
  },

  onSubmitCallback : function(res) {
    if (Kwo.hasError(res)) {
      this.select('.disabled').invoke('writeAttribute', 'disabled');
      return BT.MessageManager.show({message: res['result']['msg'], container: 'kwo-form-error'});
    }
    else {
      this.removeClassName('disabled');
      if (res['result']['msg']) {
        this.remove();
        if($('kwo-form-error')) $('kwo-form-error').hide();
        return BT.MessageManager.show({message: res['result']['msg'], container: 'kwo-form-success'});
      }
      else {
        if (!res['result']['redirect'].blank()) {
          Kwo.go(res['result']['redirect']);
        }
        else if (!res['result']['remote_url'].blank()) {
          var action = res['result']['remote_url'];
          var bt_sid = res['result']['bt_sid'];
          var bt_skey = res['result']['bt_skey'];
          var params = res['result']['params'];
          Kwo.exec('/post.redirect',
                   {'action':action, 'bt_sid':bt_sid, 'bt_skey':bt_skey, 'params':params},
                   {container:'post-redirection'})
        }
      }
    }
  },

  loadForm: function(item_key, flag) {
    BT.Offre.item_key = item_key;
    window.onAuthCallback = function (item_key) {
      BT.Offre.loadForm(BT.Offre.item_key);
    };
    if(flag==1){
      Kwo.exec("/offre.form", {item_key: item_key},
               {container: 'form', callback: BT.Offre.onloadCallbackForm});
    }
    else {
      Kwo.exec("/offre.form", {item_key: item_key},
               {container: 'form', callback: BT.activateRollover});
    }
  },

  loadFormAIES: function(item_key, country) {
    BT.Offre.item_key = item_key;
    window.onAuthCallback = function (item_key) {
      BT.Offre.loadForm(BT.Offre.item_key);
    };
    Kwo.exec("/offre.form", {item_key: item_key},
             {container: 'form', callback: BT.activateRollover});

    function tmp_refreshcountry() {
      if ($('kwo-form-24-labels-pays')) {
        var container = $('kwo-form-24-labels-pays');
        if (container.up('div').down('span', 1) && container.up('div').down('input')) {
          $('kwo-form-24-labels-pays').up('div').down('span', 1).update(country);
          $('kwo-form-24-labels-pays').up('div').down('input').value = country;
        }
      }
    }
    tmp_refreshcountry.delay(1);
  },

  onloadCallbackForm:function(){
    $('form').down('form').hide();
    if(Kwo.Auth.referer == 1){
      $('form').down('form').childElements('div')[3].down().childElements('input')[1].value=1;
    }
    BT.Offre.onSubmit($('form').down('form'));
  },

  loadFrame: function(item_key) {
    BT.Offre.item_key = item_key;
    window.onAuthCallback = function (item_key) {
      BT.Offre.loadFrame(BT.Offre.item_key);
    };
    Kwo.exec("/offre.frame", {item_key: item_key}, {container: 'frame'});
  },

  onBack: function(args) {
    Kwo.go('/offre/-/id/'+$('related_offre_id').getValue(),$$('form'));
  }
};

//--------------------
BT.Vente = {
  onNodeToggle: function(elt) {
    var tree = $('vente-arbo');
    var sub_ul = $(elt).next('ul');
    tree.select('ul.arbo-level-2').each(function(el) {
      if (sub_ul && sub_ul == el) {
        sub_ul.toggle();
      } else {
        el.hide();
      }
    });
  },

  onNodeDisplay: function(elt) {
    elt = $(elt);
    $('vente-privee').setStyle({'background':'none'});
    Kwo.exec('/vente.articles',
             {node_id: elt.readAttribute("data-id")},
             {container: 'vente-content'});
  },

  onProduitSelect: function(elt) {
    elt = $(elt);
    if (!$(elt)) return;
    if ($('art-cart-add')) {
      var item_key = elt.options[elt.selectedIndex].value;
      $('art-cart-add').writeAttribute("data-item-key", item_key);
      Kwo.exec('/article.availability', {'key':item_key} , {'callback': function(res){
        var availability = parseInt(res['result']['availability']);
        var threshold = parseInt(res['result']['threshold']);
        var weight = parseInt(res['result']['weight']);

        $('produit-weight').update(weight);

        if (availability < threshold)  threshold = availability;
        if (threshold > 0) {
          $('item-qty').update('');
          for (var i=1; i <= threshold; i++) {
            var opt = new Element('option');
            opt.value     = i;
            opt.innerHTML = i;
            $('item-qty').appendChild(opt);
          }
          $('art-cart-add').setStyle({'display':'block'});
          $('item-qty').show();
          $('alert-stock').hide();
        }
        else {
          $('art-cart-add').setStyle({'display':'none'});
          $('item-qty').hide();
          $('alert-stock').show();
        }
      }});
    }
  },

  onThumbnail: function(elt) {
    elt = $(elt);
    var thumbnail = elt.down('img');
    $('vente-article').select('td.image img').each(function(pix) {
      if (pix.readAttribute("data-n") == thumbnail.readAttribute("data-n")) {
        pix.show();
      } else {
        pix.hide();
      }
    });
  },

  onImageZoom: function(url) {
    image_1 = new Image();
    image_1.src = url;
    new Kwo.Dialog("/article.image", {"image": url}, {height:(800), width:(500), className:"layout-hbox"});
    $$('.dialog-overlay').invoke('setStyle', {opacity: '0.8', filter :'alpha(opacity=80)'});
  },

  onPlayVideo: function(url) {

  }
};

//--------------------
BT.OneShot = {
  elt:null,
  onFinalize: function(elt) {
    elt = $(elt);
    Kwo.exec("/oneshot.request",
             {offre_id: elt.readAttribute("data-id")},
             {container: $("psp-container")});
  },

  loadPurchase: function(elt) {
    BT.OneShot.elt = $(elt);
    window.onAuthCallback = function (item_key) {
      BT.OneShot.onFinalize(BT.OneShot.elt);
    };
    Kwo.exec("/oneshot.purchase",
             {id: elt.readAttribute("data-id")},
             {container: 'oneshot-purchase'});
  }
};

BT.AIESSearcher = {
  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;
    Kwo.exec(_form.action, _form , {'container': 'products-result'});
  },

  loadModeles : function(gamme_id, launch_search) {
    if(launch_search >0){
      launch_search = 1;
    }
    Kwo.exec('/aies.modeles', {'gamme_id':gamme_id} , {'callback': function(res){
      if (Kwo.hasError(res)) return Kwo.error(res);
      if (res['result']['modeles']) {
        $('modele-id').update('');
        for (var k in res['result']['modeles']) {
          var opt = new Element('option');
          opt.value     = k;
          opt.innerHTML = res['result']['modeles'][k].replace('+', '<br/>+');
          $('modele-id').appendChild(opt);
        }
      }
      if (launch_search == 1) BT.AIESSearcher.updateSearch($('modele-id').up('form'));
    }});
  },

  loadGammes : function(marque_id, launch_search) {
    if(launch_search >0){
      launch_search = 1;
    }
    Kwo.exec('/aies.gammes', {'marque_id':marque_id} , {'callback': function(res){
      if (Kwo.hasError(res)) return Kwo.error(res);
      if (res['result']['gammes']) {
        $('gamme-id').update('');
        for (var k in res['result']['gammes']) {
          var opt = new Element('option');
          opt.value     = k;
          opt.innerHTML = res['result']['gammes'][k];
          $('gamme-id').appendChild(opt);
        }
      }
      if (launch_search == 1) BT.AIESSearcher.updateSearch($('gamme-id').up('form'));
    }});
  },

  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;
    });
    _form.select('input[type=text]').each(function(el){
      $(el).value = '';
    });
    $('reset').value = 1;
    BT.AIESSearcher.loadGammes($('marque-id').value, 0);
    BT.AIESSearcher.loadModeles($('gamme-id').value,0);
    $('products-result').update('');
    $('reset').value = 0;
  },

  updatePrices : function (elt) {
    if (elt.min_value) $('price-min').value = elt.min_value;
    if (elt.max_value) $('price-max').value = elt.max_value;
    BT.Searcher.updateSearch('products-search-form');
  }
};
BT.initializeSlideShow = {
  currentSlideshow : null,
  initialize : function() {
    BT.currentSlideshow = new BT.SlideShow('slide_box');
  }
};
BT.SlideShow = Class.create({
  "mask": null,
  "link":null,
  "lock": 0,
  "periodical": null,
  "initialize": function (id) {
    this.visibleSlides = [];
    this.mask = $(id);
    this.cloneHref();
    this.autoRun();
  },
  "next": function () {
    if (this.lock === 1) { return; }
    this.lock = 1;
    this.cloneFirstVisibleChild();
 //   this.periodical.stop();
    this.mask.setStyle({'top' : '9px'});
    new Effect.Morph( this.mask , {
      style: 'top:-55px',
      duration: 0.5,
      afterFinish: (function(){
        this.removeFirstVisibleChild();
        this.mask.setStyle({'top' : '9px'});
        this.cloneHref();
        Kwo.exec("/promo", {'id': this.mask.firstDescendant().readAttribute("data-id")}, {container: 'home-promo-1'});
        this.lock = 0;
      }).bind(this)
    });
  },
  "prev": function () {
    if (this.lock === 1) { return; }
    this.lock = 1;
    this.periodical.stop();
    var elt = this.getLastVisibleChild();
    this.mask.insert({top : elt});
    this.mask.setStyle({'top' : '-55px'});
    new Effect.Morph( this.mask , {
      style: 'top:9px',
      duration: 0.5,
      afterFinish: (function(){
        this.cloneHref();
        Kwo.exec("/promo", {'id': this.mask.firstDescendant().readAttribute("data-id")}, {container: 'home-promo-1'});
        this.lock = 0;
      }).bind(this)
    });
  },
  "cloneFirstVisibleChild": function () {
    if(this.mask.firstDescendant().visible()){
      var elt = this.mask.firstDescendant().clone(true);
      this.mask.insert(elt);
    }
    else {
      this.mask.insert(this.mask.firstDescendant().remove());
      this.cloneFirstVisibleChild();
    }
  },
  "removeFirstVisibleChild": function () {
    if(this.mask.firstDescendant().visible()){
      this.mask.firstDescendant().remove();
    }
    else {
      this.mask.insert(this.mask.firstDescendant().remove());
      this.removeFirstVisibleChild();
    }
  },
  "getLastVisibleChild": function () {
    var last_descendant = $$('#' + this.mask.id + ' > *').last();
    if(last_descendant.visible()){
      return last_descendant.remove();
    }
    else {
      this.mask.insert({'top': last_descendant.remove()});
      return this.getLastVisibleChild();
    }
  },
  "cloneHref": function () {
    var elt = this.mask.firstDescendant();
    var link = $('active_link');
    if(elt.readAttribute("data-type") == 3){
      link.writeAttribute('onclick',
                          'new Kwo.Dialog("/btapie/video.prompt",{"id": "'+elt.readAttribute("data-id")+'"}, {"width": "'+elt.readAttribute("data-width")+'", "height": "'+elt.readAttribute("data-height")+'"})');
      link.href = 'javascript:void(0);';
    }else{
      if(link.hasAttribute('onclick')){
        link.removeAttribute('onclick');
      }
      link.href = elt.readAttribute("data-destination");
    }
  },
  "autoRun": function () {
  this.periodical = new PeriodicalExecuter((function(pe) {
      this.next();
    }).bind(this), 5);
  }
});
//--------------------
/*BT.Promo = {
  current_elt: null,
  y_scroll: 66,
  y_position: 0,
  position: 0,
  parent: null,
  timer: null,
  max: 0,
  onSwitch: function(position, stop) {
    stop = stop || false;
    if (stop) BT.Promo.timer.stop();
    elt = BT.Promo.parent.select('.block-ad-d1')[position];
    new_position = position * BT.Promo.y_scroll;
    Kwo.exec("/promo", {'id': elt.readAttribute("data-id")}, {container: 'home-promo-1'});
    new Effect.Move($('home-promo-1-menu').down('.arrow'), {
     x: 0, y: (new_position - BT.Promo.y_position), mode: 'relative',
     transition: Effect.Transitions.sinoidal, duration:0.3
    });
    BT.Promo.y_position = new_position;
  },

  autoSwitch: function() {
    BT.Promo.position++;
    if (BT.Promo.position ==  BT.Promo.max) BT.Promo.position = 0;
    BT.Promo.onSwitch(BT.Promo.position);
  },

  loadSwitcher: function(elt) {
    BT.Promo.parent = $(elt);
    BT.Promo.max    = $(elt).select('.block-ad-d1').length;
    BT.Promo.timer  = new PeriodicalExecuter(function(pe) { BT.Promo.autoSwitch();}, 5);
  }
};*/

BT.Categorie = {
  current_elt: null,
  y_scroll: 66,
  y_position: 0,
  position: 0,
  parent: null,
  timer: null,
  max: 0,

  onSwitch: function(position, stop) {
    stop = stop || false;
    if (stop) BT.Categorie.timer.stop();
    elt = BT.Categorie.parent.select('.block-ad-d1')[position];

    if (elt) {
      new_position = position * BT.Categorie.y_scroll;

      Kwo.exec("/categorie.carrousel", {'id': elt.readAttribute("data-id"), 'categorie_id': $F('categorie_id')}, {container: 'home-promo-1'});
      new Effect.Move($('home-promo-1-menu').down('.arrow'), {
       x: 0, y: (new_position - BT.Categorie.y_position), mode: 'relative',
       transition: Effect.Transitions.sinoidal, duration:0.3
      });
      BT.Categorie.y_position = new_position;
    }
  },

  autoSwitch: function() {
    BT.Categorie.position++;
    if (BT.Categorie.position ==  BT.Categorie.max) BT.Categorie.position = 0;
    BT.Categorie.onSwitch(BT.Promo.position);
  },

  loadSwitcher: function(elt) {
    BT.Categorie.parent = $(elt);
    BT.Categorie.max    = $(elt).select('.block-ad-d1').length;
    BT.Categorie.timer  = new PeriodicalExecuter(function(pe) { BT.Categorie.autoSwitch();}, 1000);
  }
};


BT.MessageManager = {
  show : function (args) {
    $$('.'+args.container).each(function(el){
      el.show().down('div').update(args.message);
    });
    Kwo.Form.button.enable();
  }
}

BT.InputForm = {
  addHover :function () {
    $('content').select('.onfocus').invoke('removeClassName', 'onfocus');
    var _parent = this.up('.sign-line');
    if (!_parent) _parent = this.up('.hover-line');
    if (!_parent) _parent = this.up('.field');
    if (_parent) _parent.addClassName('onfocus');
  }
}

BT.Menu = {
  addHover : function (elt) {
    var _parent = $(elt).up('li');
    _parent.addClassName('submenu-subcat-hover');
  },

  removeHover : function (elt) {
    var _parent = $(elt).up('li');
    _parent.removeClassName('submenu-subcat-hover');
  }
}

document.observe("dom:loaded", function() {
  setTimeout(BT.init, 100);
  new PeriodicalExecuter(function(pe) { Kwo.Cart.updateWidget(); }, 60);
  BT.activateRollover();
});

player = {
  onPlay: function() {

  },

  onStop: function() {
    return;
  }
};

BT.contact = {
  onSubmit : function(args) {
     if ($F('content_contact')=="" || $F('nom')=="" || $F('prenom')==""){
      if ($('kwo_error_signup_top')) {
        $('blabla_error_signup_top').update("Veuillez remplir tous les champs obligatoires");
        $('blabla_error_signup_bottom').update("Veuillez remplir tous les champs obligatoires");
        $('kwo_error_signup_top').show();
        $('kwo_error_signup_bottom').show();
      }
       return false;
     }
      if($('kwo_error_signup_top')) {
        $('kwo_error_signup_top').hide();
        $('kwo_error_signup_bottom').hide();
      }

     //var args = {"nom":$F('nom'),"prenom":$F('prenom'),"content":$F('content_contact'),"mail":$F('mail'),"tel":$F('tel')}
     Kwo.exec("/contact.mail", args, {"callback": BT.contact.onSubmitCallback()});
  },

  onSubmitCallback : function(h){
    if($('kwo_error_signup_top')) {
        $('blabla_success_signup_top').update("Votre demande de contact a été prise en compte");
        $('blabla_success_signup_bottom').update("Votre demande de contact a été prise en compte");
        $('kwo_success_signup_top').show();
        $('kwo_success_signup_bottom').show();
     }
     $('form_contact_submit').hide();
  },

  "Send" : function(args){
    Kwo.exec("/extranet.offre.contact.mail", args, {"callback": BT.contact.SendCallback()});
  },
  "SendCallback" : function(h){
     $('blabla_success_signup_top').update("Votre demande de contact a été prise en compte");
     $('kwo_success_signup_top').show();
     window.setTimeout(function(){$('mail_box_contact').update('');},1000);
  }
};

BT.cms = {
  "gereDiv" : function (nom) {
    $(nom).toggle();
  }
};

BT.anbm = {
  onSubmit : function(args) {
     Kwo.go("/anbm.testretour", args);
  },

  onSubmitCallback : function(h){
    return 0;
  },

  getDialogTest: function(action, args, _width, _height) {
  new Kwo.Dialog("/"+action,
                 {"date": args},
                 {width:_width, height:_height, name:"service"});
  }
};

BT.order = {
  "toggle" : function (elem) {
    var elem = $(elem);
    if(elem.match('h2.open')){
      elem.removeClassName('open');
    }else{
      elem.addClassName('open');
    }
    elem.next().toggle();
  }
};

BT.iframe = {
  resize : function(elt){
    var h=  elt.getHeight();
    elt.setStyle({"height":(h +20 )+"px"});
  }
}

BT.countdown = {

  init : function(elt,date_fin){
    new PeriodicalExecuter(function(pe) {
    	var result = BT.countdown.delai(date_fin);
    	if(result != -1){
		  if(elt.readAttribute('flag')=="p"){
		    elt.update("Fin dans "+ result);
		  }else{
		    elt.update("Début dans "+result);
		  }
    	}
    }, 1);
  },

  delai : function(date_fin){
    var date_jour=new Date();
	var tps=(date_fin.getTime()-date_jour.getTime())/1000;
	var j=Math.floor(tps/3600/24); // récupere le nb de jour
	tps=tps % (3600*24);
	var h=Math.floor(tps / 3600); // recupère le nb d'heure
	tps=tps % 3600;
	var m=Math.floor(tps/60); // récupère le nb minute
	tps=tps % 60
	var s=Math.floor(tps);

	if(j>=2) { return -1; }
	var txt = "";

	h = j * 24 + h;

	if(h>=10){
	  txt = h + ":";
	}else{
      if(h<=9 && h >=2){
	    txt = "0"+h + ":";
	  }else{
	    txt = "0"+h + ":";
	  }
	}
	if(j==0 && h==0) txt="";

	if(m>=10){
	  txt += m + ":";
	}else{
	  if(m<=9 && m >=2){
	    txt += "0"+m + ":";
	  }else{
	   txt += "0"+m + ":";
	  }
	}

    if(j==0 && h==0 && m==0) txt="";

	if(s>=10){
	  txt += s + "";
	}else{
	  if(s<=9 && s >=2){
	    txt += "0"+s + "";
	  }else{
	    txt += "0"+s + "";
	  }
	}

	if(s < 0 ){txt = "00";}

	return txt;
  }
}