/*
 * @author        Louis-Philippe Dumas @louisdumas / lpdumas@ixmedia.com
 * @company       iXmédia <http://www.ixmedia.com>
 */
 
 
/* @section App {{{
 ******************************************************************************/
   if (!window.console) {
     (function() {
       var f = function() {};
       window.console = {log: f, info: f, dir: f, warn: f, error: f, trace: f, group: f, groupCollapsed: f, groupEnd: f, time: f, timeEnd: f, profile: f, profileEnd: f, count: f};
     })();
   }
   

   
   var App = (function() {

     var bodyClasses = $('body').attr('class');

     return {

       isSection: function(section) {
         return (bodyClasses.indexOf("section-" + section) != -1);
       },
       isTemplate: function(section) {
         return (bodyClasses.indexOf("template-" + section) != -1);
       },
       insertCSSRules: function(selector, properties) {
         var ss = document.styleSheets,
           s = ss[ss.length-1],
           i;
         if (s.addRule) {
           i = s.addRule(selector, properties);
         } else {
           i = s.insertRule(selector + ' {' + properties + '}', s.cssRules.length);
         }
         return i;
       },
       deleteCSSRules: function(rule) {
         var ss = document.styleSheets,
           s = ss[ss.length-1];
         if(s.addRule) {
           s.removeRule(rule);
         } else {
           s.deleteRule(rule);
         }
       },
       //Jquery animation fallback if CSS animations are not supported
       handleAnimations : function(target, options, speed){
         //modernizr.js is required here!!!!!
         if(Modernizr.csstransitions){

           target.css(options);
         } else {

           speed = speed || 150;
           target.animate(options, speed);
         }
       }
       
     };

   })();

   App.Accordion = function(accordionName, opts){
     var accordions = $(accordionName),
         opts       = opts || {},
         isOpen     = (typeof opts.isOpen != 'undefined') ? opts.isOpen : 1 ;
     
     accordions.each(function(){
       var myAccordion = $(this),
       firstChild            = myAccordion.find('li:first'),
       firsChildDesireHeight = firstChild.find('div.faq-content').height();
     
       firstChild.find('div.faq-wrapper').css({'height' : firsChildDesireHeight});
       firstChild.addClass('active');
     
       myAccordion.find('li').click(function(e) {
         var desireHeight = $(this).find('div.faq-content').height();
         myAccordion.find('li').removeClass('active');
         myAccordion.find('div.faq-wrapper').css({'height' : 0});
       
         if(!$(this).hasClass('active')) {
           $(this).addClass('active');
           $(this).find('div.faq-wrapper').css({'height' : desireHeight});
         }
       });
     
     })
   }
   
   App.sidebarSlider = function(sliderName) {
     var _this          = this; 
     this.slider        = $(sliderName + ' ul.slides');
     this.slides        = this.slider.find('li');
     this.navPrev       = $(sliderName + ' .prev')
     this.navNext       = $(sliderName + ' .next')
     this.sliderCaption = $('<p class="slider-caption"><span></span></p>');
     this.slideWidth    = 160;
     this.currentSlide  = 0;

     $(sliderName).append(this.sliderCaption);

     this.slider.css({'width' : (this.slides.length * this.slideWidth) });

     this.handleCaption();
     this.prepareAnimation();

     $(sliderName + ' a.nav').click(function(e) {
       e.preventDefault();
     })
     this.navPrev.click(_this.animeSlider.bind(_this,'prev'));
     this.navNext.click(_this.animeSlider.bind(_this,'next'));
   }

   App.sidebarSlider.prototype = {
     prepareAnimation : function() {  
       this.prevSlide = (this.currentSlide > 0) ? this.currentSlide - 1  : this.slides.length-1;
       this.nextSlide = (this.currentSlide < (this.slides.length-1)) ? this.currentSlide + 1  : 0;
     },

     animeSlider : function(where) {
       var targetSlide    = (where === 'prev') ? $(this.slides[this.prevSlide]) : $(this.slides[this.nextSlide]),
           targetPosition = (where === 'prev') ? this.prevSlide : this.nextSlide,
           newPosition    = targetSlide.position()['left'];

       //Jquery animation fallback if CSS animations are not supported
       App.handleAnimations(this.slider, {'left' : -newPosition}, 300)

       this.currentSlide = targetPosition;
       this.handleCaption();
       this.prepareAnimation();
     },

     handleCaption : function() {
       var newCaption       = $(this.slides[this.currentSlide]).find('.caption').html(),
           captionContainer = this.sliderCaption.find('span'),
           _this            = this;

       captionContainer.fadeOut('fast',function(){
         if(newCaption) {
           captionContainer.html(newCaption);
           captionContainer.fadeIn('fast');
         }
       });

     }
   }
/*}}} */

$(function() {

/* @section Basic {{{
******************************************************************************/
  Modernizr.load;

  window.domainWithoutSubdomain = function(domainWithSubdomain) {
    var matches = domainWithSubdomain.match(DOMAIN_REGEX);
    return matches ? matches[0] : null;
  };
  
  var links = document.getElementsByTagName('a'),
    l = links.length;
    
  while (l--) {
    link = links[l];

    if (!link.className.match(/fancybox/) && !link.href.match(/^(javascript:|mailto:)/) && (link.hostname != location.hostname || link.href.match(/\.(docx?|xlsx?|pptx?|pdf|eps|zip|vsd|vxd|rar|wma|mov|avi|wmv|mp3|mp4|mpg|mpeg|mpeg4|m4a|m4v|f4v|flv|csv|xml|ogg|oga|ogv|webm|jpg|jpeg|png|gif|webp|svg|ico|txt|css|js)$/))) {
      link.target = '_blank';
      link.title += link.title ? ' – S’ouvre dans une nouvelle fenêtre.' : 'S’ouvre dans une nouvelle fenêtre.';
      link.className += link.className.indexOf('externe') == -1 ? ' externe' : '';
    }
  }

  /* }}} */
  if($('.accordion').length){(function(){
    var accordion = new App.Accordion('.accordion');
  }())}

  
  /* Content switcher {{{
******************************************************/
  if(App.isTemplate('page-niveau-2') && $('#content-switcher-nav').length ){(function(){
    var minHeight = 400;

    // @Pierre-Luc Paquin
    $('.content-switcher .section:first-child').addClass('active');

    $('.content-switcher .section').not('.active').css({'display' : 'none'});
    
    $('#content-switcher-nav a').not('.realLink').click(function(e){
      // e.preventDefault();
      var target           = $(this).attr('href'),
          activeSectionId  = $('.section.active').attr('id'),
          targetHeight     = ($(target).height() < minHeight) ? minHeight : $(target).height();
      
      if(target !== '#' + activeSectionId) {
        
        var track = location.pathname + "/" + target.replace('#','');
        _gaq.push(['_trackPageview', track]);
        
        $('#content-switcher-nav li').removeClass('active')
        $(this).closest('li').addClass('active');
        $('.content-switcher .section.active').removeClass('active').fadeOut('fast', function(){
          
          App.handleAnimations($('.content-switcher'),{'height': targetHeight}, 150);
          
          $(target).addClass('active').fadeIn('fast');
        })
      }
      
    })
    
    
    if(location.hash) {
      
      $('#content-switcher-nav a').each(function(){
        if($(this).attr('href') === location.hash) {
          
          $(this).trigger('click');
        }
      });
    } else {
      if(!$('#content-switcher-nav li.active').length) {
        $('#content-switcher-nav li:first').addClass('active');
      }
    }
    
  }());}
/* }}} */
  
  /***VIDEO SLIDER INSTANTIATION {{{
  ******************************************************/
  if($('#videos-slider').length){(function(){
    var vidSlider = new App.sidebarSlider('#videos-slider');
    vidSlider.slider.find('a').click(function(e){
      e.preventDefault();
      var href = $(this).attr('href');

      $('#player iframe').attr('src', href);
    })
  }());}
  /*}}}*/
  
  /*** Handleling «Séance d’information» form{{{
  ******************************************************/  
  if($('form#info-form').length) {(function(){
    var infoForm             = $('form#info-form'),
        infoFormSelect       = infoForm.find('select'),
        infoFormHidden       = infoForm.find('div.hidden'),
        infoFormEar          = infoForm.find('#form_infoSource'),
        infoFormOther        = infoForm.find('#otherInfoSource'),
        infoFormButton       = infoForm.find('button');
    
    infoFormHidden.hide();
    infoFormOther.hide();
    
    infoFormSelect.change(function(){
      if($(this).val() !== '') {
        infoFormHidden.show();
      } else {
        infoFormHidden.hide();
      }
    });
    
    infoFormEar.change(function(){
      if($(this).val() === '6') {
        infoFormOther.show();
      } else {
        infoFormOther.hide();
      }
    });
    
    //Google analytics stuff
    infoFormButton.click(function(e){
      // e.preventDefault();
      var currentDate = new Date(),
          day         = currentDate.getDate(),
          month       = currentDate.getMonth(),
          year        = currentDate.getFullYear(),
          hours       = currentDate.getHours(),
          minutes     = currentDate.getMinutes(),
          today       = day + "/" + month + "/" + year + ' - ' + hours + ':' + minutes;
      
      _gaq.push(['_trackEvent', 'Inscription', 'Envoyer', ]);
    })
    
  }());}
  /*}}}*/
  
  /*** Alert {{{*/
  if($(".close-alert").length){(function(){
    $(".close-alert").click(function(){
      $(this).closest("#alert-wrapper").hide();
    })
  }())}
  /*}}}*/
  
  /*** Sexy SELECT INPUT {{{
  ******************************************************/
  if(!$('html').hasClass('ie7') && $('select').length){(function(){
    $('select').each(function(){
      new Skii.SelectInput($(this));
    })
  }());}
  /*}}}*/
  /*** Sexy SELECT INPUT {{{
  ******************************************************/
  if($('a.history-back').length){(function(){
    $('a.history-back').click(function(e){
      e.preventDefault();
      history.back()
    })
  }());}
  /*}}}*/
});

