jQuery(function(){
 clearInputs();
 initFisheye();
 initAccordion();
 initCustomForms();
 initGallery();
 initTabs();

 jQuery(".nyroModal").nyroModal();

 // PATCH pour le menu
 jQuery("#nav .drop-holder").mouseleave(function(e){
  jQuery(this).parent().css('padding','0');
  var self = this;
  setTimeout(function(){
   jQuery(self).parent().css('padding','0 0 9999px');
  },100);
 });

 $("body").mousedown(function(e){
    if (e.which == 3) {
      alert('Stop');
    }
 });
});

// init gallery
function initGallery(){
  jQuery('div.slideshow').slideshow();
  jQuery('div.gallery').scrollGallery();
}

// clear inputs
function clearInputs(){
  jQuery('input:text, input:password, textarea').each(function(){
    var _el = jQuery(this);
    var _val = _el.val();
    _el.bind('focus', function(){
      if(this.value == _val) this.value = '';
    }).bind('blur', function(){
      if(this.value == '') this.value = _val;
    });
  });
};

// init tabs
function initTabs() {
  jQuery('ul.tabset').each(function(){
    var _list = jQuery(this);
    var _links = _list.find('a.tab');
    _links.each(function() {
      var _link = jQuery(this);
      var _href = _link.attr('href');
      var _tab = jQuery(_href);
      if(_link.hasClass('active')) _tab.show();
      else _tab.hide();
      _link.click(function(){
        _links.filter('.active').each(function(){
          jQuery(jQuery(this).removeClass('active').attr('href')).hide();
        });
        _link.addClass('active');
        _tab.show();
        return false;
      });
    });
  });
}

// accordion function
function initAccordion() {
  jQuery('ul.menu').multiAccordion({activeClass:'current'});
  jQuery("ul.menu a.current.path").next().show();
  jQuery("ul.menu a.current.path").parent().parent().parent().show().prev().click().parent().parent().parent().show().prev().click();
}

// init fisheye
function initFisheye(){
  jQuery('#fisheye').Fisheye({
    maxWidth: 20,
    items: 'a',
    itemsText:'span',
    container: '.fisheyeContainter',
    itemWidth: 63, //82x73
    proximity: 50,
    halign : 'center'
  });
}

// multilevel accordion plugin
jQuery.fn.multiAccordion = function(_options){
  // default options
  var _options = jQuery.extend({
    activeClass:'active',
    opener:'>a',
    slider:'>div.slide',
    slideSpeed: 400,
    collapsible:true,
    event:'click'
  },_options);

  return this.each(function(){
    // options
    var _event = _options.event;
    var _accordion = jQuery(this);
    var _items = _accordion.find(':has('+_options.slider+')');

    _items.each(function(){
      var _holder = jQuery(this);
      var _opener = _holder.find(_options.opener);
      var _slider = _holder.find(_options.slider);
      _opener.bind(_event, function(){
        if(!_slider.is(':animated')) {
          if(_holder.hasClass(_options.activeClass)) {
            if(_options.collapsible) {
              _slider.slideUp(_options.slideSpeed, function(){
                _holder.removeClass(_options.activeClass);
              });
            }
          } else {
            var _levelItems = _holder.siblings('.'+_options.activeClass);
            _holder.addClass(_options.activeClass);
            _slider.slideDown(_options.slideSpeed);

            // collapse others
            _levelItems.find(_options.slider).slideUp(_options.slideSpeed, function(){
              _levelItems.removeClass(_options.activeClass);
            })
          }
        }
        return false;
      });
      if(_holder.hasClass(_options.activeClass)) _slider.show(); else _slider.hide();
    });
  });
}

//create jQuery plugin
jQuery.fn.slideshow = function(options){return new slideshow(this, options);}

//constructor
function slideshow(obj, options){this.init(obj,options)}

//prototype
slideshow.prototype = {
  init:function(obj, options) {
    this.options = jQuery.extend({
      slides:'div.holder > ul >li',
      nextBtn:'a.btn-next',
      prevBtn:'a.btn-prev',
      pagingHolder:'ul.switcher',
      pagingTag:'li',
      createPaging:false,
      autoPlay:6,
      dynamicLoad:false,
      imgAttr:'alt',
      effect:'slideX',//fade, slideX, slideY,
      startSlide:false,
      switchTime:3000,
      animSpeed:600,
      easing:'easeInOutExpo'
    },options);

    this.mainHolder = jQuery(obj);
    this.slides = jQuery(this.options.slides,this.mainHolder);
    this.nextBtn = jQuery(this.options.nextBtn,this.mainHolder);
    this.prevBtn = jQuery(this.options.prevBtn,this.mainHolder);
    this.dynamicLoad = this.options.dynamicLoad;
    this.imgAttr = this.options.imgAttr;
    this.animSpeed = this.options.animSpeed;
    this.switchTime = this.options.switchTime;
    this.effect = this.options.effect;
    this.autoPlay = this.options.autoPlay;
    this.previous = -1;
    this.loadingFrame = 1;
    this.busy = false;
    this.direction = 1;
    this.timer;
    this.pagingArray = new Array;
    this.loadArray = new Array;
    this.preloader = new Array;
    this.slidesParent = this.slides.eq(0).parent();
    this.slideW = this.slidesParent.width();
    this.slideH = this.slidesParent.height();
    this.easing = this.options.easing;

    (function(){
      if (this.options.startSlide) this.current = this.options.startSlide
      else {
        var active = -1;
        for(var i = 0; i< this.slides.length-1; i++) {
          if (this.slides.eq(i).hasClass('active')) {
            active = i;
            break;
          }
        }
        if (active != -1) this.current = active;
        else this.current = 0;
      }
    }).apply(this);

    this.initPaging();
    this.setStyles();
    this.bindEvents();
    this.showSlide();
  },

  initPaging:function(){
    var obj = this;
    this.pagingHolder = jQuery(this.options.pagingHolder,this.mainHolder);

    if (this.options.createPaging) {
      this.pagingHolder.each(function(i){
        var _this = jQuery(this);
        _this.empty();
        var list = jQuery('<ul>');
        for (var i = 0; i < obj.slides.length; i++) jQuery('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
        _this.append(list);
      });
    }

    this.paging = jQuery(this.options.pagingTag, this.pagingHolder);
    var ratio = Math.ceil(this.paging.length / this.slides.length);
    for (var i = 0; i < ratio; i++) {
      this.pagingArray.push(this.paging.slice(i*this.slides.length, (i*this.slides.length)+this.slides.length));
    }
  },

  setStyles:function(){
    //loader
    if (this.dynamicLoad) {
      this.loader = jQuery('<div class="loader">');
      this.loaderDiv = jQuery('<div>').appendTo(this.loader)
      this.loader.append(this.loaderDiv).appendTo(this.slidesParent);
    }

    //slides
    if (this.effect == 'fade') {
      this.slides.css({display:'none'});
      this.slides.eq(this.current).css({display:'block'});
    } else if (this.effect == 'slideX'){
      this.slides.css({display: 'none',left:-this.slideW});
      this.slides.eq(this.current).css({display:'block',left:0});
    } else if (this.effect == 'slideY'){
      this.slides.css({display:'none',top:-this.slideH});
      this.slides.eq(this.current).css({display:'block',top:0});
    }
  },

  bindEvents:function(){
    var obj = this;
    this.nextBtn.bind('click',function(){
      if (!obj.busy) obj.nextSlide();
      return false;
    });

    this.prevBtn.bind('click',function(){
      if (!obj.busy) obj.prevSlide();
      return false;
    });

    for (var i = 0; i < this.pagingArray.length; i++) {
      this.pagingArray[i].each(function(i){
        jQuery(this).bind('click',function(){
          if (i != obj.current && !obj.busy) {
            obj.previous = obj.current;
            obj.current = i;
            if (obj.previous > i) obj.direction = -1
            else obj.direction = 1;
            obj.showSlide();
          }
          return false;
        });
      });
    }

    if (this.dynamicLoad) this.loader.bind('click',function(){
      obj.abortLoading();
    });
  },

  nextSlide:function(){
    this.previous = this.current;
    if (this.current < this.slides.length-1) this.current++
    else this.current = 0;
    this.direction = 1;
    this.showSlide();
  },

  prevSlide:function(){
    this.previous = this.current;
    if (this.current > 0) this.current--
    else this.current = this.slides.length-1;
    this.direction = -1;
    this.showSlide();
  },

  showSlide:function(){
    var obj = this;
    var _current = this.current;
    this.busy = true;
    clearTimeout(this.timer);

    if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
      //slide already loaded
      this.switchSlide();

    } else {
      //slide not loaded
      this.showLoading();
      var images = jQuery(this.dynamicLoad,this.slides.eq(this.current));
      if (images.length) {
        var counter = 0;
        images.each(function(){
          var preloader = new Image;
          obj.preloader.push(preloader);
          var img = jQuery(this);
          preloader.onload = function(){
            counter++;
            checkImages();
          }
          preloader.onerror = function(){
            //ignore errors
            counter++;
            checkImages();
          }
          preloader.src = img.attr(obj.imgAttr);
        });

        function checkImages(){
          if (counter == images.length) {
            images.each(function(){
              var img = jQuery(this);
              img.attr('src',img.attr(obj.imgAttr));
            });
            successLoad();
          }
        }

      } else successLoad();
    }

    function successLoad(){
      obj.loadArray[_current] = 1;
      obj.hideLoading();
      obj.switchSlide();
    }
  },

  switchSlide:function(){
    var obj = this;

    if (this.previous != -1) {
      var nextSlide = this.slides.eq(this.current);
      var prevSlide = this.slides.eq(this.previous);

      if (this.effect == 'fade') {
        nextSlide.css({display:'block',opacity:0}).animate({opacity:1},this.animSpeed,function(){
          jQuery(this).css({opacity:'auto'});
        });
        prevSlide.animate({opacity:0},this.animSpeed,callback);
      } else if (this.effect == 'slideX'){
        nextSlide.css({display:'block',left:this.slideW*this.direction}).animate({left:0},this.animSpeed,this.easing);
        prevSlide.animate({left:-this.slideW*this.direction},this.animSpeed+10,this.easing,callback);
      } else if (this.effect == 'slideY'){
        nextSlide.css({display:'block',top:this.slideH*this.direction}).animate({top:0},this.animSpeed);
        prevSlide.animate({top:-this.slideH*this.direction},this.animSpeed+10,callback);
      }
    } else {
      if (this.autoPlay) this.startAutoPlay();
      this.busy = false;
    }

    this.refreshStatus();

    function callback(){
      prevSlide.css({display:'none'});
      if (obj.autoPlay) obj.startAutoPlay();
      obj.busy = false;
    }
  },

  refreshStatus:function(){
    for (var i = 0; i < this.pagingArray.length;i++) {
      this.pagingArray[i].eq(this.previous).removeClass('active');
      this.pagingArray[i].eq(this.current).addClass('active');
    }
    this.slides.eq(this.previous).removeClass('active');
    this.slides.eq(this.current).addClass('active');
  },

  showLoading:function(){
    var obj = this;
    this.loader.show();
    clearInterval(this.loadingTimer);
    obj.loadingTimer = setInterval(animateLoading, 66);

    function animateLoading(){
      obj.loaderDiv.css('top', obj.loadingFrame * -40);
      obj.loadingFrame = (obj.loadingFrame + 1) % 12;
    }
  },

  hideLoading:function(){
    this.loader.hide();
    clearInterval(this.loadingTimer);
  },

  abortLoading:function(){
    this.busy = false;
    this.hideLoading();
    this.current = this.previous;
    for (var i = 0; i < this.preloader.length; i++) {
      this.preloader[i].onload = null;
      this.preloader[i].onerror = null;
    }
    if (this.autoPlay) this.startAutoPlay();
  },

  startAutoPlay:function(){
    var obj = this;
    clearTimeout(obj.timer);
    obj.timer = setTimeout(function(){
      obj.nextSlide();
    },obj.switchTime);
  }
}

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
  var _options = jQuery.extend({
    sliderHolder: '>div.holder',
    slider:'>ul',
    slides: '>li',
    pagerLinks:'div.pager a',
    btnPrev:'a.btn-prev',
    btnNext:'a.btn-next',
    activeClass:'active',
    disabledClass:'disabled',
    generatePagination:'div.pg-holder',
    curNum:'span.cur-num',
    allNum:'span.all-num',
    circleSlide:true,
    pauseClass:'gallery-paused',
    pauseButton:'none',
    pauseOnHover:true,
    autoRotation:true,
    stopAfterClick:false,
    switchTime:5000,
    duration:650,
    easing:'easeInOutExpo',
    event:'click',
    afterInit:false,
    vertical:false,
    step:false
  },_options);

  return this.each(function(){
    // gallery options
    var _this = jQuery(this);
    var _sliderHolder = jQuery(_options.sliderHolder, _this);
    var _slider = jQuery(_options.slider, _sliderHolder);
    var _slides = jQuery(_options.slides, _slider);
    var _btnPrev = jQuery(_options.btnPrev, _this);
    var _btnNext = jQuery(_options.btnNext, _this);
    var _pagerLinks = jQuery(_options.pagerLinks, _this);
    var _generatePagination = jQuery(_options.generatePagination, _this);
    var _curNum = jQuery(_options.curNum, _this);
    var _allNum = jQuery(_options.allNum, _this);
    var _pauseButton = jQuery(_options.pauseButton, _this);
    var _pauseOnHover = _options.pauseOnHover;
    var _pauseClass = _options.pauseClass;
    var _autoRotation = _options.autoRotation;
    var _activeClass = _options.activeClass;
    var _disabledClass = _options.disabledClass;
    var _easing = _options.easing;
    var _duration = _options.duration;
    var _switchTime = _options.switchTime;
    var _controlEvent = _options.event;
    var _step = _options.step;
    var _vertical = _options.vertical;
    var _circleSlide = _options.circleSlide;
    var _stopAfterClick = _options.stopAfterClick;
    var _afterInit = _options.afterInit;

    // gallery init
    if(!_slides.length) return;
    var _currentStep = 0;
    var _sumWidth = 0;
    var _sumHeight = 0;
    var _hover = false;
    var _stepWidth;
    var _stepHeight;
    var _stepCount;
    var _offset;
    var _timer;

    _slides.each(function(){
      _sumWidth+=jQuery(this).outerWidth(true);
      _sumHeight+=jQuery(this).outerHeight(true);
    });

    // calculate gallery offset
    function recalcOffsets() {
      if(_vertical) {
        if(_step) {
          _stepHeight = _slides.eq(_currentStep).outerHeight(true);
          _stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
          _offset = -_stepHeight*_currentStep;
        } else {
          _stepHeight = _sliderHolder.height();
          _stepCount = Math.ceil(_sumHeight/_stepHeight);
          _offset = -_stepHeight*_currentStep;
          if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
        }
      } else {
        if(_step) {
          _stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
          _stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
          _offset = -_stepWidth*_currentStep;
          if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
        } else {
          _stepWidth = _sliderHolder.width();
          _stepCount = Math.ceil(_sumWidth/_stepWidth);
          _offset = -_stepWidth*_currentStep;
          if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
        }
      }
    }

    // gallery control
    if(_btnPrev.length) {
      _btnPrev.bind(_controlEvent,function(){
        if(_stopAfterClick) stopAutoSlide();
        prevSlide();
        return false;
      });
    }
    if(_btnNext.length) {
      _btnNext.bind(_controlEvent,function(){
        if(_stopAfterClick) stopAutoSlide();
        nextSlide();
        return false;
      });
    }
    if(_generatePagination.length) {
      _generatePagination.empty();
      recalcOffsets();
      var _list = jQuery('<ul />');
      for(var i=0; i<_stepCount; i++) jQuery('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
      _list.appendTo(_generatePagination);
      _pagerLinks = _list.children();
    }
    if(_pagerLinks.length) {
      _pagerLinks.each(function(_ind){
        jQuery(this).bind(_controlEvent,function(){
          if(_currentStep != _ind) {
            if(_stopAfterClick) stopAutoSlide();
            _currentStep = _ind;
            switchSlide();
          }
          return false;
        });
      });
    }

    // gallery animation
    function prevSlide() {
      recalcOffsets();
      if(_currentStep > 0) _currentStep--;
      else if(_circleSlide) _currentStep = _stepCount-1;
      switchSlide();
    }
    function nextSlide() {
      recalcOffsets();
      if(_currentStep < _stepCount-1) _currentStep++;
      else if(_circleSlide) _currentStep = 0;
      switchSlide();
    }
    function refreshStatus() {
      if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
      if(!_circleSlide) {
        _btnPrev.removeClass(_disabledClass);
        _btnNext.removeClass(_disabledClass);
        if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
        if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
      }
      if(_curNum.length) _curNum.text(_currentStep+1);
      if(_allNum.length) _allNum.text(_stepCount);
    }
    function switchSlide() {
      recalcOffsets();
      if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
      else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
      refreshStatus();
      autoSlide();
    }

    // autoslide function
    function stopAutoSlide() {
      if(_timer) clearTimeout(_timer);
      _autoRotation = false;
    }
    function autoSlide() {
      if(!_autoRotation || _hover) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime+_duration);
    }
    if(_pauseOnHover) {
      _this.hover(function(){
        _hover = true;
        if(_timer) clearTimeout(_timer);
      },function(){
        _hover = false;
        autoSlide();
      });
    }
    recalcOffsets();
    refreshStatus();
    autoSlide();

    // pause buttton
    if(_pauseButton.length) {
      _pauseButton.click(function(){
        if(_this.hasClass(_pauseClass)) {
          _this.removeClass(_pauseClass);
          _autoRotation = true;
          autoSlide();
        } else {
          _this.addClass(_pauseClass);
          stopAutoSlide();
        }
        return false;
      });
    }

    if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
  });
}

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright В© 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
  def: 'easeOutQuad',
  swing: function (x, t, b, c, d) {
    //alert(jQuery.easing.default);
    return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
  },
  easeInQuad: function (x, t, b, c, d) {
    return c*(t/=d)*t + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  },
  easeInOutQuad: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * ((--t)*(t-2) - 1) + b;
  },
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  },
  easeOutCubic: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t + 1) + b;
  },
  easeInOutCubic: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;
  },
  easeInQuart: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t + b;
  },
  easeOutQuart: function (x, t, b, c, d) {
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
  },
  easeInOutQuart: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
    return -c/2 * ((t-=2)*t*t*t - 2) + b;
  },
  easeInQuint: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t*t + b;
  },
  easeOutQuint: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t*t*t + 1) + b;
  },
  easeInOutQuint: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
    return c/2*((t-=2)*t*t*t*t + 2) + b;
  },
  easeInSine: function (x, t, b, c, d) {
    return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
  },
  easeOutSine: function (x, t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
  },
  easeInOutSine: function (x, t, b, c, d) {
    return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
  },
  easeInExpo: function (x, t, b, c, d) {
    return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
  },
  easeOutExpo: function (x, t, b, c, d) {
    return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  },
  easeInOutExpo: function (x, t, b, c, d) {
    if (t==0) return b;
    if (t==d) return b+c;
    if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
    return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
  },
  easeInCirc: function (x, t, b, c, d) {
    return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  },
  easeOutCirc: function (x, t, b, c, d) {
    return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
  },
  easeInOutCirc: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
    return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
  },
  easeInElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
  },
  easeOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
  },
  easeInOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
  },
  easeInBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*(t/=d)*t*((s+1)*t - s) + b;
  },
  easeOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
  },
  easeInOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
  },
  easeInBounce: function (x, t, b, c, d) {
    return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
  },
  easeOutBounce: function (x, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
      return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
      return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
      return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
      return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
  },
  easeInOutBounce: function (x, t, b, c, d) {
    if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
    return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
  }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright В© 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

// init custom forms
function initCustomForms() {
 jQuery('select').customSelect();
  //jQuery('input:radio').customRadio();
  //jQuery('input:checkbox').customCheckbox();
}
// custom forms plugin
(function(jQuery){
  // custom checkboxes module
  jQuery.fn.customCheckbox = function(_options){
    var _options = jQuery.extend({
      checkboxStructure: '<div></div>',
      checkboxDisabled: 'disabled',
      checkboxDefault: 'checkboxArea',
      checkboxChecked: 'checkboxAreaChecked'
    }, _options);
    return this.each(function(){
      var checkbox = jQuery(this);
      if(!checkbox.hasClass('outtaHere') && checkbox.is(':checkbox')){
        var replaced = jQuery(_options.checkboxStructure);
        this._replaced = replaced;
        if(checkbox.is(':disabled')) replaced.addClass(_options.checkboxDisabled);
        else if(checkbox.is(':checked')) replaced.addClass(_options.checkboxChecked);
        else replaced.addClass(_options.checkboxDefault);

        replaced.click(function(){
          if(checkbox.is(':checked')) checkbox.removeAttr('checked');
          else checkbox.attr('checked', 'checked');
          changeCheckbox(checkbox);
        });
        checkbox.click(function(){
          changeCheckbox(checkbox);
        });
        replaced.insertBefore(checkbox);
        checkbox.addClass('outtaHere');
      }
    });
    function changeCheckbox(_this){
      _this.change();
      if(_this.is(':checked')) _this.get(0)._replaced.removeClass().addClass(_options.checkboxChecked);
      else _this.get(0)._replaced.removeClass().addClass(_options.checkboxDefault);
    }
  }

  // custom radios module
  jQuery.fn.customRadio = function(_options){
    var _options = jQuery.extend({
      radioStructure: '<div></div>',
      radioDisabled: 'disabled',
      radioDefault: 'radioArea',
      radioChecked: 'radioAreaChecked'
    }, _options);
    return this.each(function(){
      var radio = jQuery(this);
      if(!radio.hasClass('outtaHere') && radio.is(':radio')){
        var replaced = jQuery(_options.radioStructure);
        this._replaced = replaced;
        if(radio.is(':disabled')) replaced.addClass(_options.radioDisabled);
        else if(radio.is(':checked')) replaced.addClass(_options.radioChecked);
        else replaced.addClass(_options.radioDefault);
        replaced.click(function(){
          if($(this).hasClass(_options.radioDefault)){
            radio.attr('checked', 'checked');
            changeRadio(radio.get(0));
          }
        });
        radio.click(function(){
          changeRadio(this);
        });
        replaced.insertBefore(radio);
        radio.addClass('outtaHere');
      }
    });
    function changeRadio(_this){
      $(_this).change();
      $('input:radio[name='+$(_this).attr("name")+']').not(_this).each(function(){
        if(this._replaced && !$(this).is(':disabled')) this._replaced.removeClass().addClass(_options.radioDefault);
      });
      _this._replaced.removeClass().addClass(_options.radioChecked);
    }
  }

  // custom selects module
  jQuery.fn.customSelect = function(_options) {
    var _options = jQuery.extend({
      selectStructure: '<div class="selectArea"><span class="left"></span><span class="center"></span><a href="#" class="selectButton"></a><div class="disabled"></div></div>',
      hideOnMouseOut: false,
      copyClass: true,
      selectText: '.center',
      selectBtn: '.selectButton',
      selectDisabled: '.disabled',
      optStructure: '<div class="optionsDivVisible"><div class="select-top"></div><div class="select-center"><ul></ul><div class="select-bottom"></div></div>',
      optList: 'ul'
    }, _options);
    return this.each(function() {
      var select = jQuery(this);
      if(!select.hasClass('outtaHere')) {

          // PATCH CAMILLE : pour styler les select caché au chargement de la page
          //if(select.is(':visible')) {
          var hiddenParent = null;
          if(!select.is(':visible')) {
            hiddenParent = select.parents(':hidden:last').show();
          }

          var hideOnMouseOut = _options.hideOnMouseOut;
          var copyClass = _options.copyClass;
          var replaced = jQuery(_options.selectStructure);
          var selectText = replaced.find(_options.selectText);
          var selectBtn = replaced.find(_options.selectBtn);
          var selectDisabled = replaced.find(_options.selectDisabled).hide();
          var optHolder = jQuery(_options.optStructure);
          var optList = optHolder.find(_options.optList);
          if(copyClass) optHolder.addClass('drop-'+select.attr('class'));

          if(select.attr('disabled')) selectDisabled.show();
          select.find('option').each(function(){
            var selOpt = $(this);
            var _opt = jQuery('<li><a href="#">' + selOpt.html() + '</a></li>');
            if(selOpt.attr('selected')) {
              selectText.html(selOpt.html());
              _opt.addClass('selected');
            }
            _opt.children('a').click(function() {
              optList.find('li').removeClass('selected');
              select.find('option').removeAttr('selected');
              $(this).parent().addClass('selected');
              selOpt.attr('selected', 'selected');
              selectText.html(selOpt.html());
              select.change();
              optHolder.hide();
              return false;
            });
            optList.append(_opt);
          });
          replaced.width(select.outerWidth());
          replaced.insertBefore(select);
          optHolder.css({
            width: select.outerWidth(),
            display: 'none',
            position: 'absolute'
          });
          jQuery(document.body).append(optHolder);

          var optTimer;
          replaced.hover(function() {
            if(optTimer) clearTimeout(optTimer);
          }, function() {
            if(hideOnMouseOut) {
              optTimer = setTimeout(function() {
                optHolder.hide();
              }, 200);
            }
          });
          optHolder.hover(function(){
            if(optTimer) clearTimeout(optTimer);
          }, function() {
            if(hideOnMouseOut) {
              optTimer = setTimeout(function() {
                optHolder.hide();
              }, 200);
            }
          });
          selectBtn.click(function() {
            if(optHolder.is(':visible')) {
              optHolder.hide();
            }
            else{
              if(_activeDrop) _activeDrop.hide();
              optHolder.children('ul').css({height:'auto', overflow:'hidden'});
              optHolder.css({
                top: replaced.offset().top + replaced.outerHeight(),
                left: replaced.offset().left,
                display: 'block'
              });
              if(optHolder.children('ul').height() > 200) optHolder.children('ul').css({height:200, overflow:'auto'});
              _activeDrop = optHolder;
            }
            return false;
          });
          replaced.addClass(select.attr('class'));
          select.addClass('outtaHere');

                                // PATCH CAMILLE : pour styler les select caché au chargement de la page
                                if(hiddenParent) {
                                  hiddenParent.hide();
                                }
        //}
      }
    });
  }

  // event handler on DOM ready
  var _activeDrop;
  jQuery(function(){
    jQuery('body').click(hideOptionsClick)
    jQuery(window).resize(hideOptions)
  });
  function hideOptions() {
    if(_activeDrop && _activeDrop.length) {
      _activeDrop.hide();
      _activeDrop = null;
    }
  }
  function hideOptionsClick(e) {
    if(_activeDrop && _activeDrop.length) {
      var f = false;
      $(e.target).parents().each(function(){
        if(this == _activeDrop) f=true;
      });
      if(!f) {
        _activeDrop.hide();
        _activeDrop = null;
      }
    }
  }
})(jQuery);
