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);
  }

  if ($('diaporama') && $('diaporama_position')) {
    new SlideShow('diaporama', {'nav':'diaporama_position'});
  }

};

SlideShow = Class.create({
  "timeout": null,
  "mask": null,
  "nav": null,
  "count": 0,
  "pos": 0,
  "z": 1,
  "initialize": function (id, opts) {
    this.pos = 0;
    this.mask = $(id);
    this.width = this.mask.getWidth();
    this.count = this.mask.childElements().length - 1;
    this.mask.select('div.diapo').invoke('setStyle',{left:'0px',top:'0px',zIndex:this.z++,opacity:0});
    $('item'+this.pos).setStyle({zIndex:this.z,opacity:1});
    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.play();
    }
  },
  "play": function () {
    this.pause();
    this.timeout = window.setTimeout(this.next.curry(null).bind(this), 5000);
    $(this.nav).childElements().invoke('removeClassName', 'selected');
    $('nav'+this.pos).addClassName('selected');
  },
  "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) {
    if ($('item'+this.pos) && ($('item'+this.pos).getStyle('opacity') == 0 || $('item'+this.pos).getStyle('opacity') == 1)) {
      $('item'+this.pos).setStyle({zIndex:this.z++,opacity:1});
      emile($('item'+this.pos), (Prototype.Browser.IE ? 'filter:alpha(opacity=0)' : 'opacity:0'), {duration: 500});
      if (Object.isNumber(pos) && pos >= 0) this.pos = pos;
      else { pos = this.pos; this.pos++; }
      if (this.pos > this.count - 1) this.pos = 0;
      if (this.pos < 0) this.pos = this.count - 1;
      if ($('item'+this.pos) && ($('item'+this.pos).getStyle('opacity') == 0 || $('item'+this.pos).getStyle('opacity') == 1)) {
        emile($('item'+this.pos).setStyle({zIndex:this.z++,opacity:0}), (Prototype.Browser.IE ? 'filter:alpha(opacity=100)' : 'opacity:1'), {duration: 500});
      }
    }
    this.play();
  },
  "prev": function (pos) {
    if ($('item'+this.pos) && ($('item'+this.pos).getStyle('opacity') == 0 || $('item'+this.pos).getStyle('opacity') == 1)) {
      emile($('item'+this.pos).setStyle({zIndex:this.z++,opacity:1}), (Prototype.Browser.IE ? 'filter:alpha(opacity=0)' : 'opacity:0'), {duration: 500});
      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;
      if ($('item'+this.pos) && ($('item'+this.pos).getStyle('opacity') == 0 || $('item'+this.pos).getStyle('opacity') == 1)) {
        emile($('item'+this.pos).setStyle({zIndex:this.z++,opacity:0}), (Prototype.Browser.IE ? 'filter:alpha(opacity=100)' : 'opacity:1'), {duration: 500});
      }
    }
    this.play();
  }
});

/*
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 = {} ;
        var swfWidth = eltA.hasAttribute("data-swf-width") ? Number(eltA.readAttribute("data-swf-width")) : 880;
        var swfHeight = eltA.hasAttribute("data-swf-height") ? Number(eltA.readAttribute("data-swf-height")) : 620;
        if (!Kwo.getDialog()) {
          var modalbox = new Kwo.Dialog(null, null, {width:swfWidth+20, height:swfHeight+20});
        } else {
          var modalbox = Kwo.getDialog();
        }
        $(modalbox.support).update('<div id="dialogSupportBox"></div>');
        swfobject.embedSWF(eltA.href, 'dialogSupportBox', swfWidth, swfHeight, "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)});
  }

};

Animated = {
  "sinoidal" : function(pos) {return (-Math.cos(pos*Math.PI)/2) + .5},
  "reverse"  : function(pos) {return 1-pos;},
  "flicker"  : function(pos) {var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;return pos > 1 ? 1 : pos;},
  "wobble"   : function(pos) {return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;},
  "pulse"    : function(pos, pulses) {return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;},
  "spring"   : function(pos) {return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));}
};

document.observe('dom:loaded', Kernix.init);

