if (!Kernix) var Kernix = {};

var count = 0;

var gallery = [];

Kernix.init = function() {
  $$('.kwo-galleryBox').each(function(elt){ gallery.push(new Gallery(elt)); });

  $$('a.kwo-modal-box').each(function(elt){ Kernix.display.convertLink(elt); });

  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(Kernix.display.alphaBackgrounds);
    }
  }

  if (Prototype.Browser.IE && rslt != null && Number(rslt[1]) < 7) {
    elt = $$('#footer .plan_site div.contact_box .kernix_picto div.logo a')[0];
    elt.alt = 'Site développé par KerniX';
    elt.title = 'Site développé par KerniX';
    elt.down('img').alt = 'Site développé par KerniX';
  } else {
    elt = $$('#footer .plan_site div.contact_box .kernix_picto div.logo a img')[0];
    elt.observe('mouseover', Kernix.display.footerLogoAppear);
    elt.observe('mousemove', Kernix.display.footerLogoAppear);
    elt.observe('mouseout', Kernix.display.footerLogoDisappear);
  }

};

var Gallery = Class.create({
  initialize: function(eltBox) {
    this.firstLabel = "debut";
    this.prevLabel  = "précédente";
    this.nextLabel  = "suivante";
    this.lastLabel  = "fin";
    this.currentIndex = 0;
    this.imagePlaced = 0;
    this.isPlaced  = false;
    this.width     = 0;
    this.isRunning = false;
    this.isRolling = false;
    this.timerRoll = null;
    this.argMove = {'x': 0,
    'y': 0,
    'fps':30,
    'duration': 0.75,
    'transition': Effect.Transitions.sinoidal,//spring
    'beforeStart' : this.lock.bind(this),
    'afterFinish' : this.unlock.bind(this)};
    this.imageCollection = [];

    this.el = $(eltBox);

    var container_id  = "galleryBox" + count++;

    this.el.insert({'before' : '<div id="' + container_id + '" class="kwo-galleryBox"></div>'});

    this.container = $(container_id);
    //    this.container = new Element('div', {id : container_id} ).addClassName('kwo-galleryBox').hide();
    this.container.insert({top:new Element('div').addClassName('overlay')});
    this.container.insert({bottom:new Element('div').addClassName('images')});

    var eltsLi = this.el.select('li');
    for( k in eltsLi) {
      var eltLi = eltsLi[k];
      if (typeof(eltLi) != "object") continue;
      var eltA = $(eltLi).down('a');

      var imageObj = new Image();
      imageObj.onload = this.addImageToBox.bind(this).curry(imageObj);
      imageObj.onerror = this.desactiveGallery.bind(this);
      imageObj.src = eltA.href;
      this.imageCollection.push(imageObj);

    }
    this.el.remove();

    if (this.imageCollection.length > 1){
      var action = ['first', 'prev', 'next', 'last'];
      for (k in action) {
        var str = action[k];
        if (typeof(str) != "string") continue;
        var attr = {'title' : this[str+'Label'] };
        var button = new Element('A', attr).update(str);
        button.addClassName(str+'Button');
        button.addClassName('btnNavigation');
        button.observe('click', this[str].bind(this));
        this.container.insert({'bottom' : button});
      }
      this.roll();
    }
  },
  activeGallery : function () {
    this.roll();
    this.container.down('.overlay').hide();
    this.container.select('.btnNavigation').invoke('show');
  },
  desactiveGallery : function () {
    this.stopRoll();
    this.container.down('.overlay').show();
    this.container.select('.btnNavigation').invoke('hide');
  },
  addImageToBox : function(imageObj) {
    this.container.down('.images').insert({'bottom':imageObj});
    this.imagePlaced++;
    if (!this.isPlaced) this.place();
    if (this.imagePlaced == this.imageCollection.length) {
      this.activeGallery();
    }
  },
  lock : function(){
    this.isRunning = true;
  },
  unlock : function(){
    this.isRunning = false;
  },
  roll: function(interval){
    clearInterval(this.timerRoll);
    this.timerRoll = setInterval(this.next.bind(this), 5000);
  },
  stopRoll: function(interval){
    clearInterval(this.timerRoll);
  },
  first: function() {
    if (this.isRunning || this.currentIndex==0) return false;

    var arg = this.argMove;
    if (this.imageCollection.length > 2)
    arg.transition =  Effect.Transitions.spring;
    else
    arg.transition =  Effect.Transitions.sinoidal;
    arg.x   =  (this.width * (this.currentIndex + this.imageCollection.length - 1)) - (this.width * (this.imageCollection.length - 1));
    arg.duration = 2;
    new Effect.Move(this.container.down('.images'), arg);
    this.currentIndex = 0;
    this.roll();
  },
  prev: function() {
    if (this.isRunning) return false;
    if (this.currentIndex <= 0) return this.last();

    var arg = this.argMove;
    arg.transition =  Effect.Transitions.sinoidal;
    arg.x   = this.width;
    arg.duration = 0.75;

    new Effect.Move(this.container.down('.images'), arg);
    this.currentIndex--;
    this.roll();
  },
  next: function() {
    if (this.isRunning) return false;
    if (this.currentIndex >= this.imageCollection.length-1) return this.first();

    var arg = this.argMove;
    arg.transition =  Effect.Transitions.sinoidal;
    arg.x   = -this.width;
    arg.duration = 0.75;
    new Effect.Move(this.container.down('.images'), arg);
    this.currentIndex++;
    this.roll();
  },
  last: function() {
    if (this.currentIndex >= this.imageCollection.length-1 || this.isRunning) return false;

    var arg = this.argMove;
    if (this.imageCollection.length > 2)
    arg.transition =  Effect.Transitions.spring;
    else
    arg.transition =  Effect.Transitions.sinoidal;
    arg.x   = -this.width * (this.imageCollection.length - 1) + this.width * this.currentIndex;
    arg.duration = 2;
    new Effect.Move(this.container.down('.images'), arg);
    this.currentIndex = this.imageCollection.length-1;
    this.roll();
  },
  place : function() {
    var dim = $(this.imageCollection[this.currentIndex]).getDimensions();
    if (dim.width < 1) {
      return;
    }
    this.width = dim.width;
    arg = {'width'    : dim.width+'px',
    'height'   : dim.height+'px',
    'display'  : 'block'
    };
    this.container.setStyle(arg).show();
    this.isPlaced = true;
  }
});


Kernix.display = {
  "footerLogoRunning":null,
  "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"});
    }
  },
  
  "showUrl" : function (url, args, opts){
    args = args || {};
    //    opts = opts || {};
    //    if (!(width in opts)) { opts.width = '600'; }
    if (!Kwo.getDialog()) {
      new Kwo.Dialog(url, args, {width:620, height:650});
    }
    return false;
  },
  
  "footerLogoAppear" : function() {
    if (Kernix.display.footerLogoRunning) return false;
  
    var elt = $$('#footer .plan_site div.contact_box .kernix_picto .tooltips')[0];
    args = { style: 'top:-30px; opacity:1;',
    duration: 0.2,
    beforeStart : function(){ elt.show(); },
    afterFinish : function(){ Kernix.display.footerLogoRunning=null; }
    }
    Kernix.display.footerLogoRunning = new Effect.Morph(elt, args);
  },
  
  "footerLogoDisappear" : function() {
    var elt = $$('#footer .plan_site div.contact_box .kernix_picto .tooltips')[0];
    args = { style: 'top:-10px; opacity:0;',
    duration: 0.2,
    afterFinish : function(){ elt.hide(); Kernix.display.footerLogoRunning=null; }
    }
    Kernix.display.footerLogoRunning = new Effect.Morph(elt, args);
  },
  
  "convertLink" : function(eltA){
    eltA.onclick = function() {
      if (eltA.href.match(/\.swf/i)) {
        var flashvars = {};
        var params = {scale : "showall"} ;
        var attributes = {} ;
        if (!Kwo.getDialog()) {
          var modalbox = new Kwo.Dialog(null, null, {width:900, height:640});
        } else {
          var modalbox = Kwo.getDialog();
        }
        $(modalbox.support).update('<div id="dialogSupportBox"></div>');
        swfobject.embedSWF(eltA.href, 'dialogSupportBox', 880, 620, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
      } else if (eltA.href.match(/\.(gif|png|jpg|jpeg)/i)) {
        eltImg = new Image();
        eltImg.onload = function() {
          if (!Kwo.getDialog()) {
            var modalbox = new Kwo.Dialog(null, null, {width:this.width+20, height:this.height+20} );
          } else {
            var modalbox = Kwo.getDialog();
          }
          $(modalbox.support).update(eltImg);
        };
        eltImg.src = eltA.href;
      }
      else Kernix.display.showUrl(eltA.href);
      return false;
    };
  }
};

Kernix.Newsletter = {

  onCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    this.select("div.inputs")[0].addClassName("confirmation").update(res["result"]["callback_msg"].ucfirst() + ".");
  },

  onSubmit: function(args) {
    Kwo.exec("/push/newsletter.subscribe", args,
    {disable:true, reset:true,
    callback: Kernix.Newsletter.onCallback.bind(args)});
  }

};

document.observe('dom:loaded', Kernix.init);
