/*
 *  @author       Rafaël <http://ixmedia.com>
 */

/* formulaires d’Inscription aux événements {{{ */

$(function() {

  $('form.inscription a.tip').each(function() {
    var $a = $(this), $tooltip = $(this.hash);
    
    $tooltip.css({
      position: 'absolute',
      display: 'none',
      top: this.offsetTop - $tooltip[0].offsetHeight,
      left: this.offsetLeft + this.offsetWidth + 5
    });
    
    $a.bind('click', function() {
      if ($tooltip.css('display') === 'block') {
        $tooltip.css('display', 'none');
      } else {
        $tooltip.css('display', 'block');
        $(document.body).one('click', function() {
          $tooltip.css('display', 'none');
        });
      }
      
      $tooltip.css({
        top: this.offsetTop - $tooltip[0].offsetHeight,
        left: this.offsetLeft + this.offsetWidth + 5
      });
      
      return false;
    });
    
  });

});

/* }}} */

/* Login {{{
******************************************************************************/

var CSS = {
  
  styleSheets: document.styleSheets,
  
  styleSheet: document.styleSheets[ document.styleSheets.length-1 ],
  
  insertRule: function(selector, properties) {
    var index;
    if (CSS.styleSheet.addRule)
      index = CSS.styleSheet.addRule(selector, properties);
    else
      index = CSS.styleSheet.insertRule(selector + ' {' + properties + '}', CSS.styleSheet.cssRules.length);
    return index;
  },
  
  deleteRule: function(index) {
    if (CSS.styleSheet.removeRule)
      index = CSS.styleSheet.removeRule(index);
    else
      index = CSS.styleSheet.deleteRule(index);
  }
};

// CSS.insertRule('#formulaire-connexion', 'display: none;');

/* }}} */

/* carrousel {{{ */

  function SimpleCarousel( args ) {
    if ( args === undefined || args.constructor !== Object ) {
      throw new Error('[function SimpleCarousel] No parameters specified. Expecting an Object of named parameters.');
      return;
    }
    this.initialize( args );
  }
  SimpleCarousel.prototype = {

    initialize: function( args ) {
      var this_ = this;

      if ( args.anchors === undefined ) {
        throw new Error('[function SimpleCarousel] Parameter "anchors" not specified.');
        return;
      }
      if ( args.blocks === undefined ) {
        throw new Error('[function SimpleCarousel] Parameter "blocks" not specified.');
        return;
      }

      this_.$anchors = $( args.anchors );
      this_.$blocks  = $( args.blocks );

      this_.changingBlock = false;

      this_.$anchors.click(function() {
        this_.changeBlock( this.hash.replace(/^#/, '') );
        return false;
      });

      // if the url’s hash on dom ready is one of our anchors
      if ( this_.$blocks.filter(window.location.hash).length ) {

        // hide all blocks but the with id of the hash
        this_.currentBlockId = window.location.hash.replace(/^#/, '');
        this_.$anchors.filter('[href="#'+ this_.currentBlockId +'"]').parent('li').addClass('actif');
        this_.$blocks.not('#'+ this_.currentBlockId).hide();

      } else {

        // hide all blocks but the first
        this_.currentBlockId = this_.$blocks.first()[0].id;
        this_.$anchors.filter(':first').parent('li').addClass('actif');
        this_.$blocks.not(':first').hide();
      }

      $(window).bind('hashchange', function() {
        if ( this_.$blocks.filter(window.location.hash).length ) {
          this_.changeBlock( window.location.hash.replace(/^#/, '') );
        }
      });
    },

    changeBlock: function( newBlockId ) {
      var this_ = this;

      if ( this_.changingBlock || newBlockId == this_.currentBlockId ) {

        return;

      } else {

        this_.changingBlock = true;

        if ( this_.currentBlockId ) {

          this_.$anchors.filter('[href="#'+ this_.currentBlockId +'"]').parent('li').removeClass('actif');
          this_.$anchors.filter('[href="#'+ newBlockId +'"]').parent('li').addClass('actif');
          this_.hideBlock(this_.currentBlockId, function() {
            this_.showBlock(newBlockId, function() {
              this_.changingBlock = false;
            });
          });

        } else {

          this_.$anchors.filter('[href="#'+ newBlockId +'"]').parent('li').addClass('actif');
          this_.showBlock(newBlockId, function() {
            this_.changingBlock = false;
          });
        }
      }

      this_.currentBlockId = newBlockId;
    },

    hideBlock: function( newBlockId /*, callback */ ) {
      var this_ = this;

      var callback  = ( arguments[1] === undefined ) ? function() {} : arguments[1];

      this_.$blocks.filter('#' + newBlockId).fadeOut(300, callback);
    },

    showBlock: function( newBlockId /*, callback */ ) {
      var this_ = this;

      var $newBlock = this_.$blocks.filter('#' + newBlockId),

        callback  = ( arguments[1] === undefined ) ? function() {} : arguments[1];

      $newBlock.fadeIn(300, callback);

      $newBlock[0].id = '';
      window.location.hash = newBlockId;
      $newBlock[0].id = newBlockId;
    }

  };

/* }}} */

(function($) {
$(function() {

/* Basic {{{
******************************************************************************/
  
  if ( $('#carrousel-dossiers').length ) {
    window.simpleCarousel = new SimpleCarousel({
      blocks:  '#carrousel-dossiers > .dossier',
      anchors: '#ancres-dossiers > li > a'
    });
  }
  
  if ( !('console' in window) ) {
    window.console = {
      log: function() {}
    };
  }
  
  window.domainWithoutSubdomain = function( domainWithSubdomain ) {
    var matches = domainWithSubdomain.match( DOMAIN_REGEX );
    return matches ? matches[0] : null;
  };
  
  var l = document.links.length, link;
  while (l--) {
    link = document.links[l];
    if ( !link.href.match(/^mailto:/) && (domainWithoutSubdomain(link.hostname) != domainWithoutSubdomain(location.hostname) || link.href.match( /\.(doc|docx|xls|xlsx|ppt|pptx|pdf|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)$/ )) ) {
      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' : '';
    }
  }
  
  $.fn.extend({

    focusinout: function( fonctionFocusIn, fonctionFocusOut ) {
      this.focusin(fonctionFocusIn);
      this.focusout(fonctionFocusOut);
    }

  });

  $('ul#meta-nav li').focusinout(function() {
    $(this).find('ul').addClass('focused');
  }, function() {
    $(this).find('ul').removeClass('focused');
  });
  
  // To detect native support for the HTML5 placeholder attribute
  var fakeInput = document.createElement('input'),
    placeHolderSupport = ('placeholder' in fakeInput);

  // Applies placeholder attribute behavior in web browsers that don't support it
  if (!placeHolderSupport) {

    $('[placeholder]').each(function() {

      var $this = $(this),
        originalText = $this.attr('placeholder');

      if ($this.val() == '') {
        $this.val(originalText);
        $this.addClass('placeholder');
      }

      $this.bind('focus', function () {
        $(this).removeClass('placeholder');
        if ($(this).val() == originalText) $(this).val('');
      });

      $this.bind('blur', function () {
        if ($(this).val().length === 0) {
          $(this).val(originalText);
          $(this).addClass('placeholder');
        }
      });

      // Empties the placeholder text at form submit if it hasn't changed
      $this.parents('form').submit(function () {
        if ($this.val() == originalText) $this.val('');
      });

      // Clear at window reload to avoid it stored in autocomplete
      $(window).bind('unload', function () {
        if ($this.val() == originalText) $this.val('');
      });

    });

  }
  

/* }}} */

/* Login {{{
******************************************************************************/

  $('label.in-field-label').each(function() {
    
    var $label = $(this),
      $span  = $label.children('span'),
      $input = $label.children('input');
    
    function checkEmptyInput() {
      if ($input.val() == '') {
        $span.show();
      } else {
        $span.hide();
      }
    }
    window.setTimeout(checkEmptyInput, 100);
    window.setTimeout(checkEmptyInput, 200);
    window.setTimeout(checkEmptyInput, 300);
    
    $label.bind('click', function () {
      $span.hide();
      $input.focus();
    });
    
    $input.bind('focus', function () {
      $span.hide();
    });
    
    $input.bind('blur', function () {
      if ($input.val().length === 0) {
        $span.show();
      }
    });
    
  });
  
  $('#lien-connexion').click(function() {
    $('#formulaire-connexion').toggleClass('ouvert');
    return false;
  });

/* }}} */

/* <select> {{{
******************************************************************************/

  $('body:not(.section-recherche-plantes, .section-formulaire-inscription) select').each(function() {
    var $this = $(this);
    
    if ($.browser.webkit)
      $this.width($this.width() + 60);
    
    var select = new classy.SelectInput($this, {});
  });

/* }}} */

/* Contactez-nous {{{
******************************************************************************/

  if ( $('.section-contactez-nous').length ) {
    
    var mapDiv = $('#map');
    
    mapDiv[0].innerHTML = '';
    
    var mapOptions = {
      center: (new google.maps.LatLng(45.624, -72.962)),
      zoom: 14,
      disableDefaultUI: true,
      navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    window.markersArray = [];
    window.infoWindow = new google.maps.InfoWindow();
    window.map = new google.maps.Map( $('#map')[0], mapOptions );
    
    window.addMarker = function( opts ) {
      var marker = new google.maps.Marker({
        position: opts.location,
        map: map,
        title: opts.title
      });
      return window.markersArray.push( marker ) - 1;
    };
    
    window.showInfoWindow = function( markerId, content ) {
      infoWindow.setContent( content );
      infoWindow.open( map, window.markersArray[ markerId ] );
    };
    
    var markerId = addMarker({
      location: (new google.maps.LatLng(45.621091, -72.961879)),
      title: 'Bureaux de la FIHOQ'
    });
    
    showInfoWindow( markerId, '<p style="margin-top: 0"><strong>Bureaux de la FIHOQ</strong></p><p style="margin-bottom: 0">3230 Rue Sicotte<br />Saint-Hyacinthe, QC J2S 7N1, Canada</p>' );
    
    $('#map').after('<p><a target="_blank" href="http://maps.google.com/maps?f=q&source=s_q&hl=fr&geocode=&q=3230,+rue+Sicotte+Saint-Hyacinthe+Qu%C3%A9bec+J2S+7B3&sll=46.791921,-71.263418&sspn=0.016483,0.038581&ie=UTF8&hq=&hnear=3230+Rue+Sicotte,+Saint-Hyacinthe,+Les+Maskoutains,+Qu%C3%A9bec+J2S+7N1,+Canada&ll=45.621091,-72.961879&spn=0.016838,0.038581&z=15&iwloc=A">Voir la carte en plus grand format.</a></p>')
    
  }

/* }}} */

/* Répertoire {{{
******************************************************************************/

  $('table.tableau-triable > thead > tr > th.sortable').click(function() {
    window.location.href = $(this).find('a').attr('href');
  });
  
  // $('.tri-recherche input[type="text"]').click(function() {
  //   if ( !$(this).hasClass('dont-select') ) {
  //     $(this).addClass('dont-select');
  //     this.select();
  //   }
  // }).blur(function() {
  //   $(this).removeClass('dont-select');
  // });

/* }}} */

/* Calendrier {{{
******************************************************************************/

  if ( $('.calendrier-wrap').length ) {
    
    if ( ($journeeSelectionnee = $('.journee-selectionnee')).length ) {
      $('.calendrier-wrap').not( $journeeSelectionnee.parents('.calendrier-wrap') ).hide();
    } else {
      $('.calendrier-wrap:not(.mois-courant)').hide();
    }
    
    var $calendriers = $('.calendrier-wrap');
    
    $calendriers.each(function(i) {
      var $this = $(this);
      
      if ( i == 0 ) {
        $this.find('.lien-precedent').addClass('desactive');;
      } else {
        $this.find('.lien-precedent').click(function() {
          $this.hide();
          $('.calendrier-wrap:eq('+ (i-1) +')').show();
        });
      }
    });
    
    $calendriers.each(function(i) {
      var $this = $(this);
      
      if ( i >= $calendriers.length - 1 ) {
        $this.find('.lien-suivant').addClass('desactive');
      } else {
        $this.find('.lien-suivant').click(function() {
          $this.hide();
          $('.calendrier-wrap:eq('+ (i+1) +')').show();
        });
      }
    });
  }

/* }}} */

})
})(jQuery);

/* jQuery plugins {{{ */

  /*
   *  Returns an array of jQuery objects, groupe by specified number of elements.
   *  
   *    Say you have 17 <frameset> tags on your page...
   *  
   *    $('frameset').inGroupsOf(7); // => [ jQuery[0..6], jQuery[7..13], jQuery[14..16] ]
   *
   */
  $.fn.inGroupsOf = function( countPerGroup ) {

    var groups = [], offset = 0, $group;

    while ( ($group = this.slice( offset, (countPerGroup + offset) )).length ) {
      groups.push( $group );
      offset += countPerGroup;
    }

    return groups;
  };

  /*
   *  Donne la même hauteur à tous les éléments d’un groupe en ajoutant du padding-top aux éléments moins hauts.
   */
  $.fn.equalHeights = function( selector, howManyPerGroup ) {

    this.each(function() {

      var liCount, highestHeight, $liColonneGrouped = $(selector, this).inGroupsOf(howManyPerGroup), liHeight, li, row, paddingTop;

      row = $liColonneGrouped.length;
      while (row--) {
        highestHeight = 0;

        li = $liColonneGrouped[row].length;
        while (li--) {
          if ( (liHeight = $liColonneGrouped[row].eq(li).height()) > highestHeight ) {
            highestHeight = liHeight;
          }
        }

        li = $liColonneGrouped[row].length;
        while (li--) {
          paddingTop = Math.round( (highestHeight - $liColonneGrouped[row].eq(li).height()) / 2 );
          $liColonneGrouped[row].eq(li).css({
            'padding-top': paddingTop,
            'height': highestHeight - paddingTop
          });
        }
      }

    });

    return this;
  };

/* }}} */

/* vertical align {{{ */

  // VERTICALLY ALIGN FUNCTION
  $.fn.vAlign = function( offset ) {
    this.each(function() {
      var $this = $(this),
        ah = $this.height();
        ph = $this.parent().height();
        mh = ((ph - ah) / 2) + (offset || 0);

      $this.css('margin-top', mh);
    });
    return this;
  };

  $(window).load(function() {

    $window = $(window);
    $wrap = $('#wrap-1');
    $background = $('#background');

    function resizeBackground() {
      var newHeight = $window.height() > $wrap.height() ? $window.height() : $wrap.height();
      $background.css( 'height', newHeight );
    }
    $window.resize(resizeBackground);
    resizeBackground();

    if ( $.browser.msie && parseInt($.browser.version, 10) <= 6  ) {
      $('img').each(function() {
        var $this = $(this);
        if ( $this.closest('p, div').width() < $this.width() ) {
          $this.width( $this.parent().width() );
        }
      });
    }

    $('ul.liste-resultats div.description-resultat').vAlign(-10);
    $('ul.liste-resultats div.colonne-droite').vAlign(-10);

    var resizeBackgroundInterval = setInterval(resizeBackground, 1000);

    if ( $('.section-banque-photos').length ) {
      $('ul.colonnes-3').equalHeights('li.colonne', 4);
    }

    if ( $('.template-fiche-activite').length ) {
      $('ul.liste-commanditaires').equalHeights('li', 3);
    }

  });

/* }}} */

