/************************ VARIABLE PSEUDO-GLOBALE :)  *************************/
var BASE_HREF = $('base').attr('href'); // base href du site
var LANG = $('html').attr('lang'); // récupère la langue en cours
var FLVPLAYER_LOCATION = BASE_HREF+'assets/templates/bourbon/scripts/plugins/player/flvplayer.swf'; // emplacement du lecteur flv
var MP3PLAYER_LOCATION = BASE_HREF+'assets/templates/bourbon/scripts/plugins/player/mp3player.swf'; // emplacement du lecteur mp3
var CONSOLEPLAYER_LOCATION = BASE_HREF+'assets/templates/bourbon/scripts/plugins/player/consoleplayer.swf'; // emplacement du lecteur console

function _(string) { return translate[string][LANG]; } // function to translate

Shadowbox.init({
    language: LANG,
    players:  ["flv","img","html","swf","iframe","qt"], // ATTENTION, ne pas mettre "console" en prod tant que c'est pas OK.
    adapter:  "jquery",
    useSizzle:  false
});


/************************** SELECTEURS ADDITIONNELS ***************************/

// Extension CSS external: Olivier Gorzalka
// selecteur de lien externe
// utilisation $('a:external') ou tout simplement $(':external')
$.extend($.expr[':'],{
  external: function(a) {
    if (!a.href)
      return false;
    if (a.href.indexOf('javascript') == 0)
      return false;
    if ($(a).attr("rel") == 'external')
      return true;
    return false;
  }
});

// Extension CSS file: Sunny Ripert & Olivier Gorzalka
// selecteur de type de fichier (img et a)
// utilisation $('a:file(pdf)') > récupère tout les liens vers des fichiers pdf
// utilisation $(':file(jpg)') > récupère tout les images de type jpg
$.extend($.expr[':'],{
  file: function(a,i,m) {
    var type = m[3];
    var types = {
      image: '\\.(png|gif|jpe?g|bmp|tiff|psd|psp|svg|xcf|ico)$',
      music: '\\.(mp3|ogg|flac|wav|aif|aiff|aifc|cda|m3u|mid|mod|mp2|snd|voc|wma)$',
      archive: '\\.(zip|rar)$',
      video: '\\.(avi|wmv|qt|mkv|flv|mpg|ram)$',
      email: '^(mailto:)'
    } // types of file
    if (types[type])
      var match = new RegExp(types[type]); // if the type is in the array
    else
      var match = new RegExp('\\.'+type+'$'); // else herit of the filetype defined by the user

    if (a.href)
      return a.href.match(match);

    if (a.src)
      return a.src.match(match);

    return false;
  }
});

/*********************** FIN DES SELECTEURS ADDITIONNELS ***********************/
/**************************** FONCTIONS DIVERSES ******************************/
/**
 * Renvoie false ou bien la valeur d'un cookie
 *
 */
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return false;
}

/** Plante un cookie
 *
 */
function setCookie( name, value, expires, path, domain, secure )
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  if( expires ){
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

/************************** FIN DES FONCTIONS DIVERSES ************************/
/***************************** LISTE DES PLUGINS ******************************/


/**
 * Equal Heights Plugin
 * Equalize the heights of elements. Great for columns or any elements
 * that need to be the same size (floats, etc).
 *
 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
 * than 300 pixels tall. Elements with too much content will gain a scrollbar.
 *
 */

(function($) {
  $.fn.equalHeights = function(minHeight, maxHeight) {
    var tallest = (minHeight) ? minHeight : 0;
    function addSize(elem,baseHeight,operation) {
      var border_top = parseInt(elem.css('border-top-width'));
      var border_bottom = parseInt(elem.css('border-bottom-width'));
      var padding_top = parseInt(elem.css('padding-top'));
      var padding_bottom = parseInt(elem.css('padding-bottom'));
      if (operation == 'subtract') {
        if (!isNaN(padding_top)) baseHeight -= padding_top;
        if (!isNaN(padding_bottom)) baseHeight -= padding_bottom;
        if (!isNaN(border_top)) baseHeight -= border_top;
        if (!isNaN(border_bottom)) baseHeight -= border_bottom;
      } else {
        if (!isNaN(padding_top)) baseHeight += padding_top;
        if (!isNaN(padding_bottom)) baseHeight += padding_bottom;
        if (!isNaN(border_top)) baseHeight += border_top;
        if (!isNaN(border_bottom)) baseHeight += border_bottom;
      }
      return baseHeight;
    }
    this.each(function() {
      var height = $(this).height();
      height = addSize($(this),height);
      if (height > tallest) tallest = height;
    });
    if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
    return this.each(function() {
      tallest2 = addSize($(this),tallest,'subtract')
      $(this).height(tallest2);
    });
  }
})(jQuery);


/*
**  jquery.linkAnylizer.js -- jQuery plugin for anylising selected links
**  Olivier Gorzalka
**
**  Params :
**  @selectors: list of selector to retrieve (ex: selectors: ':external,:file(doc),:file(pdf)')
**  @ignore: selector of link to ignore separated by coma (ex: ignore: '.ignoreExternal, #linkId')
**  @new_window_txt: text to add in the title for external link (ex: new_window_txt: 'Open In A New Window')
**  LastChangedDate: 29 Dec 2008
*/

(function($) {
  $.fn.extend({
    linkAnylizer: function (options) {
      // Default options
      var settings = {
        selectors: null,
        ignore : '.ignoreExternal',
        new_window_txt : 'dans une nouvelle fenêtre'
      };
      if(options) $.extend(settings, options);

      var $link = $(this).find('a').not(settings.ignore);
      $link.each(function(i,item) {
        if( $(item).attr('href') == undefined ) return;
        if (settings.selectors != null) {
          var listSelectors = settings.selectors.split(','); // array of files to be tested
          var matchExp = new RegExp(/\:(file\()?(\w*)\)?$/);
          // file analysis
          $(listSelectors).each(function(i,selector){
            var classElem = selector.match(matchExp); // class to apply on the link
            if($(item).is(selector)) {
              if (selector == ':external') {
                var title;
                if( $(item).attr("title") == undefined )
                  title = $(item).attr("title");
                else
                  title = $(item).text();
                if( $(item).hasClass('iconAfter') ){
                  $(item).after('&nbsp;<span class="iconlink '+classElem[2]+'">&nbsp;</span>');
                }
                else{
                  $(item).attr({
                    'rel':'external',
                    'title': title +" ("+settings.new_window_txt+")"
                  }).addClass('iconlink '+classElem[2]); // give the class to the object
                  $(item).attr('target','blank');
                }
              } else {
                if( $(item).hasClass('iconAfter') ){
                  $(item).after('&nbsp;<span class="iconlink '+classElem[2]+'">&nbsp;</span>');
                }
                else
                  $(item).addClass('iconlink '+classElem[2]); // give the class to the object
              }
            }
          });
        }
      });
    }
  });
})(jQuery);


/*
**  Plugin jQuery attrAria
**  adapté de la petite fonction simple pour commencer à utiliser ARIA...
**  renseigne les roles des zones : http://www.w3.org/TR/xhtml-role/#s_role_module_attributes
**  via http://www.lesintegristes.net/2008/12/09/introduction-a-wai-aria-traduction/
**  Params :
**  @aria-param : without the aria- prefix (ex: channel: 'notify')
**  LastChangedDate: 28 Dec 2008
*/

(function($) {
  $.fn.extend({
    attrAria: function (options) {
      var aria_keys = 'valuemin,valuemax,valuenow,valuetext,labelledby,live,polite,assertive,rude,atomic,busy,channel,relevant,required,describedby,invalid'.split(',')
      for (key in options) {
        if ($.inArray(key, aria_keys) > 0) {
          options['aria-'+key] = options[key]
          delete options[key]
        }
      }
      $(this).attr(options);
    }
  });
})(jQuery);


/*
**  Plugin jQuery favorize
**  Params :
**  @error_fav: texte si le navigateur ne supporte par l'ajout de favoris
**  LastChangedDate: 6 Jan 2009
*/
(function($) {
  $.fn.extend({
    favorize: function (options) {
      // Default options
      var settings = {
        error_fav : 'Votre navigateur ne supporte pas l\'ajout de favoris.'
      };
      if(options) $.extend(settings, options);

      if(window.opera) {
        if ($(this).attr("rel") != ""){ // don't overwrite the rel attrib if already set
          $(this).attr("rel","sidebar");
        }
      }

      $(this).click(function(event){
        event.preventDefault(); // prevent the anchor tag from sending the user off to the link
        var url = window.location.href;
        var title = $('html title').text();

        if (window.sidebar) { // Mozilla Firefox Bookmark
          window.sidebar.addPanel(title, url,"");
        } else if( window.external ) { // IE Favorite
          window.external.AddFavorite( url, title);
        } else if(window.opera) { // Opera 7+
          return false; // do nothing - the rel="sidebar" should do the trick
        } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
          alert(settings.error_fav);
        }
      });
    }
  });
})(jQuery);


/*
**  Plugin jQuery mp3Player (nécésisite le plugin jQuery Flash)
**  Params :
**  @mp3_player: url vers le lecteur mp3 (swf)
**  @height_player: hauteur du player mp3,
**  @width_player: largeur du player mp3,
**  @version_flash: version flash requise pour afficher le lecteur mp3
**  LastChangedDate: 6 Jan 2009
*/

(function($) {
  $.fn.extend({
    mp3Player: function (options) {
      // Default options
      var settings = {
        mp3_player : null,
        height_player: 20,
        width_player: 50,
        version_flash: 7
      };
      if(options) $.extend(settings, options);

      if (!settings.mp3_player) {
        alert("Aucun lecteur média n'a été spécifié dans la configuration du plugin mp3Player.");
        return;
      }

      if (!$(this).length)
        return;
      else
        $(this).each(function(i,item) {
          $(item).flash({
            src: settings.mp3_player,
            height: settings.height_player+'px',
            width: settings.width_player+'px'
          },{ version: settings.version_flash },
          function(htmlOptions) {
            htmlOptions.flashvars.file = $(item).attr('href');
            $(item).after($.fn.flash.transform(htmlOptions));
          });
        });
    }
  });
})(jQuery);


/*
**  Plugin jQuery diaporama (nécessite le plugin jCycle)
**  Params :
**  @imgLoading: chemin vers l'image de chargement
**  @wrapper : classe conteneur du diaporama
**  @zoomImg : classe de l'image permettant de zoomer
**  @slideExpr: balise qui contient les différentes images à faire défiler
**  @controlsClass: classe du conteneur des boutons de controle
**  @fx: effet à appliquer (fade, slide etc...) > voir options jCycle
**  @speed: temps entre les effets de transitions
**  @timeout: délai entre chaque image
**  @next: classe du boutons de controle "suivant"
**  @prev: classe du bouton de controle "précédent"
**  @pause: classe du bouton de controle "pause"
**  @play: classe du bouton de controle "play"
**  LastChangedDate: 6 Jan 2009
*/

(function($) {
  $.fn.extend({
    diaporama: function (options) {
      // Default options
      var settings = {
        imgLoading: 'assets/templates/bourbon/img/diaporama/loading.gif',
        wrapper : '.wrapSlideshow',
        zoomImg : '.zoomImg',
        slideExpr: 'li',
        controlsClass: '.controls',
        fx:     'fade',
        speed:   400,
        timeout: 3000,
        next:   '.next',
        prev:   '.prev',
        pause:   '.pause',
        play:   '.play'
      };
      if(options) $.extend(settings, options);

      function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

      var $this = $(this);
      if (!$this.length) return;
      var heightSlideShow = $this.height()-30; // padding-top du cadre conteneur de l'image loading
      var imgLoading = '<div style="height:'+heightSlideShow+'px" class="loading-image"><img src="'+settings.imgLoading+'" alt="'+_('loading')+'" /></div>';
      var htmlControl = '<div class="'+c(settings.controlsClass)+'">';
      htmlControl += '<span><a href="#" class="'+c(settings.prev)+'">'+_('prev')+'</a></span>';
      htmlControl += '<span><a href="#" class="'+c(settings.play)+'">'+_('play')+'</a></span>';
      htmlControl += '<span><a href="#" class="'+c(settings.pause)+'">'+_('pause')+'</a></span>';
      htmlControl += '<span><a href="#" class="'+c(settings.next)+'">'+_('next')+'</a></span></div>';

      $this.css('display','none')
      $(imgLoading).insertBefore($this);
      $(window).load(function() {
        $('.loading-image').remove();
        $this.fadeIn("slow", function(elem) {
          var heights = [];
          $this.find(settings.slideExpr).each(function() { heights.push($(this).height()) });
          heights=heights.sort();
          var heightConteneur = heights[heights.length-1];
          $(settings.wrapper).css('height',heightConteneur+3);
        })
          .wrap('<div class="'+c(settings.wrapper)+'"></div>')
          .find(settings.zoomImg+':first').appendTo(settings.wrapper)

        $(htmlControl).insertAfter($this);
        window.slideshow = $this.cycle({
          slideExpr: settings.slideExpr,
          fx:        settings.fx,
          speed:     settings.speed,
          timeout:   settings.timeout,
          next:      settings.next,
          prev:      settings.prev
        });
        $(settings.controlsClass).show();
        $(settings.pause).click(function() { $this.cycle('pause'); return false; });
         $(settings.play).click(function() { $this.cycle('resume'); return false; });
      });
    }
  });
})(jQuery);


/*
**  Pseudo Plugin jQuery Organization (nécessite le plugin Shadowbox)
**  Params :
**  @navClass: class du conteneur de la navigation des items de l'organigramme
**  @prefixNavLink : Prefixes des liens menant à la description des items de l'organigramme
**  @moreInfoTxt : Texte "Read More..."
**  LastChangedDate: 7 Jan 2009
*/

(function($) {
  $.fn.extend({
    organization: function (options) {
      // Default options
      var settings = {
        navClass: '.navOrganisation',
        prefixNavLink :'nav_',
        moreInfoTxt : 'Read more',
        heightOverlayer: 370,
        widthOverlayer:630
      };
      if(options) $.extend(settings, options);
      function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
      function l(exp,id,title,i) { return '<a title="'+title+'" rel="shadowbox[organisation'+i+'];height='+settings.heightOverlayer+'px;width='+settings.widthOverlayer+'px" href="'+window.location.href.replace(/#.*$/, '')+'#'+id+'">'+exp+'</a>'; }
      if (!$(this).length) { return; }
      $('<ul class="'+c(settings.navClass)+'"></ul>').insertBefore(this)
      $(this).find('li').each(function(i,item) {
        var targetId = $(item).attr('id');
        var idLi = settings.prefixNavLink+targetId;
        var title = $(item).find('h4').text();
        var subTitle = $(item).find('h5').text();
        var imgSrc = $(item).find('img:first').attr('src');

        var htmlGenerated = '<li id="'+idLi+'">';
        htmlGenerated += '<p>'+l('<img src='+imgSrc+' alt="'+title+'" />',targetId,title,1)+'</p>';
        htmlGenerated += '<h4>'+l(title,targetId,title,2)+'</a></h4>';
        htmlGenerated += '<h5>'+l(subTitle,targetId,title,3)+'</h5>';
        htmlGenerated += '<p class="readMore">'+l(settings.moreInfoTxt,targetId,title,4)+'</p>';
        htmlGenerated += '</li>';

        $(htmlGenerated).appendTo(settings.navClass);

      });

      $(this).hide();
    }
  });
})(jQuery);


/*
**  Plugin hack js des propriétés de taille maxi et mini
**  non supportées par IE min-height / max-height / etc...
** indiquer simplement la balise conteneur ou doivent être recherchées ces propriétés
*/

(function($) {
  $.fn.extend({
    ieCSS: function (options) {
      var settings = { selector:'img' };
      if(options) $.extend(settings, options);

      var $this = $(this);

      var old_ie = /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
        if (!old_ie) return;

      function compare(elem) {
        var widthElem = parseInt(elem.width());
        var heightElem = parseInt(elem.height());
        var attrLength = {}
        var ratioHeight = false;
        var ratioWidth = false;
        // si la min-width est renseignée
        if (elem.css('min-width') != 'undefined') {
          // si la largeur de l'élement est plus grand que la min-width
            if (widthElem < parseInt(elem.css('min-width'))) {
              attrLength['width'] = parseInt(elem.css('min-width')); // on applique la min-width
          }
        }
        // si la max-width est renseignée
          if (elem.css('max-width') != 'undefined') {
          // si la largeur de l'élement est plus grand que la max-width
            if (widthElem > parseInt(elem.css('max-width'))) {
              attrLength['width'] = parseInt(elem.css('max-width')); // on applique la max-width
            }
        }
        // si la min-height est renseignée
        if (elem.css('min-height') != 'undefined') {
          // si la largeur de l'élement est plus grand que la min-height
            if (heightElem < parseInt(elem.css('min-height'))) {
              attrLength['height'] = parseInt(elem.css('min-height')); // on applique la min-height
          }
        }
        // si la max-height est renseignée
          if (elem.css('max-height') != 'undefined') {
          // si la largeur de l'élement est plus grand que la max-height
            if (heightElem > parseInt(elem.css('max-height'))) {
              attrLength['height'] = parseInt(elem.css('max-height')); // on applique la max-height
          }
          }
        // si l'élement est une image (on ajuste les proportion)
        if (elem.is('img')) {
            if (attrLength['width']) {
              attrLength['height'] = Math.round(heightElem/(widthElem/parseInt(attrLength['width'])));
          }
            if (attrLength['height']) {
              attrLength['width'] = Math.round(widthElem/(heightElem/parseInt(attrLength['height'])));
          }
            styles = { width: attrLength['width'],height: attrLength['height'] }
            elem.attr(styles)
          } else {

            elem.attr(attrLength)
          }
        }
        $this.find(settings.selector).each(function() { compare($(this)); });
    }

  });
})(jQuery);


/*
**  Plugin formManager
**  Params :
**  @action: action à appliquer sur l'élement du formulaire ou sur le formulaire lui-même (tempSearchText,secureForm)
             on peut appliquer plusieurs actions en les ajoutant de cette maniere : action:'tempSearchText&secureForm)
**  @classError : pour l'action secureForm, ajoute une classe sur le champs de formulaire sécurisé en cas d'erreur
**  LastChangedDate: 8 Jan 2009
*/

(function($) {
  $.fn.extend({
    formManager: function (options) {
      // Default options
      var settings = {
        action: null,
        classError:'.error',
        alertTxt:null
      };
      if(options) $.extend(settings, options);
      function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

      function getAction(actionToTest,actionCalled) {
        return actionToTest.indexOf(actionCalled) >= 0;
      }
      function tempSearchText(elem) {
        if (!$(elem).is('input[type=text]')) return;
        var txtLabel = $(elem).prev('label').text(); // get the text of the previous label
        // if the label has a value
        if (!$(elem).attr('value').length)
          // Insertion of the label text inside the input value
          $(elem).attr('value',txtLabel);

          // Action on click
          $(elem).click(function() {
            // only if the text inside the input[value] = the label text description
            if ($(elem).attr('value') == txtLabel)
              $(elem).attr('value','');
          });
      }

      function secureForm(elem) {
        var $requiredFields = $(elem).find('.required');
        $(elem).submit(function(){
          if (
              !$requiredFields.attr('value').length ||
              $requiredFields.attr('value') == $requiredFields.prev('label').text()
          ) {
            $requiredFields.addClass(c(settings.classError));
            if (settings.alertTxt)
              alert(settings.alertTxt)
            return false;
          }
        })
        $requiredFields.focus(function() {
          $(this).removeClass(c(settings.classError))
        })
      }

      if (getAction(settings.action,'tempSearchText'))
        tempSearchText($(this));

      if (getAction(settings.action,'secureForm'))
        return secureForm($(this))
    }
  });
})(jQuery);

/******************************* FIN DES PLUGINS ******************************/


/* Generate Zebra Table */
/* function used to control the different form
  params :
  @table_name > the table to target
  @class_name > class to apply
*/

function stripeTable(table_name, class_name) {
  var target;
  if(table_name && class_name) {
    target = table_name + " tr:even";
    $(target).addClass(class_name);
  }
  else {
    target = "table tbody tr:even";
    $(target).addClass("even");
  } // cool :)
}

/*
IE Improvment
*/
/* Hack JS pour ajouter une pseudo-classe :hover à IE */
var old_ie = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);

/* elem > can be multiple element (like #mainContent, .menuItem) */
function ieImprovments(type,elem) {
  // variable regroupant les navigateurs IE antérieur à la version 7
  if (type == 'hoverHack') {
    jQuery.fn.hoverClass = function(c) {
      return this.each(function(){
        jQuery(this).hover(
          function() {
            jQuery(this).addClass(c);
            if( jQuery(this).attr("id") == "joinBourbon" )
              jQuery(this).css("background-color", "#EAE9DF");
            else if( jQuery(this).attr("id") == "postulateBlock")
              jQuery(this).fadeTo("fast", 0.5);

          },
          function() {
            jQuery(this).removeClass(c);
            if( jQuery(this).attr("id") == "joinBourbon" )
              jQuery(this).css("background-color", "#fff");
            else if( jQuery(this).attr("id") == "postulateBlock")
              jQuery(this).fadeTo("fast", 1);
          }
        );
      });
    };
    $(elem).each(function(i,item) { $(item).hoverClass('hover'); });
  }
}


// Load ShadowBox
function loadShadowbox(elem) {
  var title;
  if (!$(elem).is('a')) {
    $elem = $(elem).find('a').eq(0)
  } else {
    $elem = $(elem)
  }
  var rel = $elem.attr('rel');
  var deb = rel.indexOf('options{')+8;
  var fin = rel.indexOf('}', deb);
  var width = "100%";
  var height = "100%";

    if( rel.indexOf('console') >= 0 ){
        var width = "600";
      var height = "580";
        var optionsShadowBox = {
          language: LANG,
        player: 'console',
        title: $elem.attr('title'),
        width: width,
        height: height,
        file: BASE_HREF+$elem.attr('href'),
        content:BASE_HREF+$elem.attr('href')
      };

      var deb = 0;
      var fin = rel.length;

      var options = rel.substring( deb, fin ).split(';');
      $(options).each(function(i,item){
        optionsShadowBox[item.split('=')[0]] = item.split('=')[1];
      });


    } else {

      // On a filé une width ou une height ?
      var tmp = rel.indexOf('width=')+6;
      if( tmp > 6 )
        width = parseInt(rel.substring(tmp));
          tmp = rel.indexOf('height=')+7;
      if( tmp > 7 )
        height = parseInt(rel.substring(tmp));


    var optionsShadowBox = {
          language: LANG,
        player: 'iframe',
        title: '',
        width: width,
        height: height,
        content:BASE_HREF+$elem.attr('href')

      };

      var options = rel.substring( deb, fin ).split(';');
      $(options).each(function(i,item){
        optionsShadowBox[item.split(':')[0]] = item.split(':')[1];
      });

    }

  // C'est pas une iframe, mais du contenu à récupérer en GET et à afficher en HTML ?
  if( rel.indexOf('iframehtml') >= 0 ){
    $.get(BASE_HREF+$elem.attr('href'), function(data){
      Shadowbox.open({
        options: {animate:false, animateFade:false},
        player: 'html',
        content: data,
        language: LANG
      });
    });

    return false;
  }

  Shadowbox.open(optionsShadowBox);
  return false;
}

// Fonctions servant à stopper toutes les animations, clignotements
// Accessibility...
function insereStopAnim() {
  if ($('#footer').length<=0) return;
  if ($('.slideshow').length<=0) return;
  var htmlStopAnim = '<li><a id="stopAnim" href="'+window.location.href+'#" title="'+_('stopAnimation_desc')+'">'+_('stopAnimation')+'</a></li>';
  $('#footer').append(htmlStopAnim);
  $('#stopAnim').click(function() {
    if (".slideshow") slideshow.cycle('stop');
    return false;
  })
}

// Bubbling :)
function bubble(bubbleEvent,selector,callback,wrapper) {
  if (wrapper == 'undefined') { var wrapper = document.body }
  $(wrapper).bind(bubbleEvent, function(e) {
    var $target = $(e.target);
    if ($target.is(selector)) {
      $targetLink = $target;
    } else if ($target.parents().is(selector)) {
      $targetLink = $target.parents(selector)[0]
    } else { return; }
    return callback($targetLink);
  });
}

function rssFeedSubscribe() {
  htmlLinkFeed = '<p><a title="'+_('subscribeFeed_desc')+'" href="' + window.document.location + '#subscribe">'+_('subscribeFeed')+'</a></p>';
  $(htmlLinkFeed).insertBefore('.feedWrapper');
  $('.subscribeFeedWrapper').addClass('jsApplied');
  $('.feedWrapper').hide();
  $('.subscribeFeedWrapper p a').mouseover(function() {
    $('.feedWrapper:visible').hide();
    $(this).parent('p').next('.feedWrapper').show()
      .click(function() { $(this).hide(); });
    return false;
  });
}

// Gère le grisé des étapes lors du choix des rss auxquels s'inscrire
function rssEtapes(){
  if( !$("#rss_form").length )
    return;

  var etapes = [ true, false, false ];

  if( $("input[name^=feeds]:checked").val() && $("input[name^=feeds]:checked").val().length )
    etapes[1] = true;

  if( $("input[name=reader]:checked").val() && $("input[name=reader]:checked").val().length && etapes[1] )
    etapes[2] = true;

  var color = $("#rss_form li").eq(0).css("background-color");

  for (var i = 1; i < 3; i++){
    if( !etapes[i]  )
      $("#rss_form li").eq(i).css("background-color","#bab595");
    else
      $("#rss_form li").eq(i).css("background-color",color);
  }

}

function loadSendToAFriend() {
  // permet d'appliquer un style propre à l'overlayer d'envoi de la page
  var hrefSendToAFriend = $('#da_serviceSendToAFriend a').attr('href')+'&detectjs=true';
  var hrefSendToAFriend2 = $('#serviceSendToAFriend a').attr('href')+'&detectjs=true';
  var actionSendToAFriend = $('#SendToFriend').attr('action')+'&detectjs=true';
  if ($('#da_serviceSendToAFriend a').length) {
    $('#da_serviceSendToAFriend a').attr('href',hrefSendToAFriend);
  }
  if ($('#serviceSendToAFriend a').length) {
    $('#serviceSendToAFriend a').attr('href',hrefSendToAFriend2);
  }
  if ($('#SendToFriend').length) {
    $('#SendToFriend').attr('action',actionSendToAFriend);
  }
}




// add a class to the body if javascript is activated
function detectJs() {
  var classBody = document.getElementsByTagName('body')[0].className;
   document.getElementsByTagName('body')[0].className = classBody+' jsready';
}

// Add ARIA roles to the document
function setupARIA() {
  $('#content').attrAria({ role: 'main' });
  $('#mainMenu').attrAria({ role: 'navigation' });
  $('#websiteSearch').attrAria({ role: 'search' });
  $('#header').attrAria({ role: 'banner' });
  $('#footer').attrAria({
    role: 'navigation',
    title:_('navTitle')
  });
}


// Fade in/out des "autres sites" sur les homes
var fadeTo_offset = 1
function fadeToBanner(){
  if( fadeTo_offset >= $('#accessMenu li').length)
    fadeTo_offset = 0;

  var $tofadeout = $('#accessMenu li.active');
  var $tofadein = $('#accessMenu li').eq(fadeTo_offset);

  $tofadein.css("z-index","1").show();
  $tofadeout.css("z-index","3");
  $tofadeout.fadeOut(2000);
  $tofadeout.removeClass("active")
  $tofadein.addClass("active");

  fadeTo_offset++;
}

// Fade in/out des offres sur les pages RH
var fadeToJob_offset = 1;
function fadeToJob(){
  if( fadeToJob_offset >= $('#jobTicker li').length)
    fadeToJob_offset = 0;

  var $tofadeout = $('#jobTicker li.active');
  var $tofadein = $('#jobTicker li').eq(fadeToJob_offset);

  $tofadeout.fadeOut().removeClass("active");
  $tofadein.fadeIn().addClass("active");

  fadeToJob_offset++;
}

// Coupe le menu en nb cols ul
$.fn.split_menu = function(cols, klass) {
  var menu = this,
      items = $(this).find('li'),
      nb_items = items.length,
      rows = nb_items / cols,
      col = elem = 0,
      tab_menus = [],
      container = $('<div />')

  $.each(items, function(i, v) {
    tab_menus[col] || (tab_menus[col] = [])
    tab_menus[col][elem++] = v

    if (elem >= rows) {
      if (col++ <= cols)
        rows = (nb_items - i - 1) / --cols
      elem = 0
    }
  })

  $.each(tab_menus, function(col, items) {
    var sub_menu = $('<ul class="'+klass+' col'+col+'" />')
    container.append(sub_menu.append(items))
  })

  menu.find('.'+klass).remove()
  menu.append(container)
}

/******************* FONCTION LANCÉES AU CHARGEMENT DU DOM ********************/

$(document).ready(function () {

  // organigramme de la direction de bourbon
  $('.directionOrganization').organization({
    moreInfoTxt:_('readBio'),
    heightOverlayer: 400,
    widthOverlayer:630
  });

  // Gestion des target(s) _blank
  $('a[rel=external]').attr('target','_blank')
  $('#footer li a.external').attr('target','_blank')
  $('.mediaListText a[href^=http://]').attr('target','_blank')
  $('a[href^=http://webcast.bourbon-online.com]').attr('target','_blank')
  $(':file(pdf)').attr('target','blank');

  // Lien à tracker sous googleAnalytics
  $('a[rel^=hash]').addClass('tracked')
  $('a[rel*=shadowbox]').addClass('tracked')
  $(':file(pdf)').addClass('tracked')
  $('a.tracked').click(function(){
    var href = $(this).attr('href'),
        link_tracked = href.replace('http://'+location.host+'/', '').replace('http://', '')
    _gaq.push(['_trackEvent', 'Link', 'Click', link_tracked])
  })

  ieImprovments('hoverHack','.menuItem,.info_importante,.listeInfos li');


  /*
    Gestion de la carte interactive de la flotte

    Utilise delegate parce que parfois cette carte n'existe pas au dom ready
   */
  // Sort de la carte
  $('body').delegate('#bourbonmap', 'mouseleave', function() {
    $(this).children().removeClass('hover');
  // Passe au dessus d'un bateau
  }).delegate('#bourbonmap div', 'hover', function(){
    $(this).siblings().removeClass('hover');
    $(this).addClass('hover');
  // Clic sur un bateau
  }).delegate('#bourbonmap div', 'click', function() {
    // On rajoute un slash devant pour donner une url à partir de la racine
    // sinon IE ajoute un /fr à cause du <base href>
    window.location = '/'+$(this).attr('data-href')
  })


  // bouton d'action pour rejoindre bourbon ou pour postuler
  $('#joinBourbon, #postulateBlock').hover(function(){
    $(this).stop().animate({opacity:0.5})
  }, function(){
    $(this).stop().animate({opacity:1})
  }).css('cursor','pointer');

  $('#postulateBlock').bind('click',function() {
    loadShadowbox(this);
    return false;
  });

  $('#mainContent').ieCSS({
    selector:'img:not([class=nostyle])'
  });

  var ie7 = document.all && !window.opera && window.XMLHttpRequest
  // correction largeur tableau assistance sauvetage. -8px pour IE7
  if(ie7)
    $('.pageassistance-et-sauvetage table, .pageassistance-and-salvage table').width($('ul.navigationTab').width() - 8)
  else
    $('.pageassistance-et-sauvetage table, .pageassistance-and-salvage table').width($('ul.navigationTab').width())

  // analyse des différents type de liens de fichiers
  $('#sidebarMenu, #mainContent, #toolsSidebar > div:not(.photosList), #toolsSidebar > ul:not(.photosList)').linkAnylizer({
    selectors: ':external,:file(doc),:file(pdf),:file(ppt),:file(image),:file(music),:file(archive),:file(video),:file(email)', // list of selector to retrieve
    new_window_txt: _('newWindow'), // "Open in a new window" text for external link
    ignore: '.subscribeFeed, .ignoreIcon' // selector of link to ignore separated by coma (ex: ignore: '.ignoreExternal, #linkId')
  });

  $('#websiteSearch').formManager({
    action:'secureForm',
    alertTxt:_('errorRequiredField')
  })

  $('#rch').formManager({
    action:'tempSearchText'
  })

  loadSendToAFriend(); // fonction d'envoi à un ami
  rssFeedSubscribe(); // Inscription au flux rss

  // Gestion des étapes de la page RSS
  rssEtapes();
  $("input[name^=feeds]").click(function(){ rssEtapes(); });
  $("input[name=reader]").click(function(){ rssEtapes(); });

  $('a.serviceFavorites').favorize({ error_fav:_('errorFav') }); // Ajout de favoris
  $('.slideshow').diaporama(); // Gestion des diaporama

  bubble('click',"[rel^='shadowbox:iframe']",loadShadowbox); // load shadowbox on the element with a specific attribute
  bubble('click',"[rel^='shadowbox:console']",loadShadowbox); // load shadowbox on the element with a specific attribute

  // player mp3
  $('a[href$=mp3]').each(function(item,i){
    // On veut pas de player ou de shadowbox
    if( $(this).hasClass('ignoreJs') ){
      return;
    }
    // On veut pas de player, mais shadowbox OK
    if( $(this).hasClass('ignorePlayer') ){
      $(this).click(function(){
        Shadowbox.open({
          language: LANG,
          player:     'flv',
          title:      $(this).attr("title"),
          content:    $(this).attr("href"),
          options: {animate:false, animateFade:false},
          height:     0.1,
          width:      450
        })
        return false;
      });

      return;
    }
    var mp3_height = 20;
    var mp3_width = 50;
    var paires = $(this).attr("rel").split(",");
    for( var z = 0; z < paires.length; z++ ){
      var paire = paires[z].split(":");
      if( paire[0] == "width" && paire[1]){
        mp3_width = parseInt(paire[1])
      }
      else if( paire[0] == "height" && paire[1]){
        mp3_height = parseInt(paire[1])
      }
    }
    $(this).mp3Player({
      mp3_player : MP3PLAYER_LOCATION,
      height_player: mp3_height,
      width_player: mp3_width,
      version_flash: 7
    })
  });


  stripeTable(); // stripes sans stars dans les tableaux
  insereStopAnim(); // lien d'arrêt des animations dans le footer

  // Setup the tab Generator :)
  if (typeof $.fn.tabGenerator != 'undefined') {
    $('.specificities,.navByHashPanel').find('ul:first').addClass('navigationTab');
    $('.specificities').tabGenerator({
      separator: 'h4',
      navigation: '.navigationTab'
    });
    $('.navByHashPanel').tabGenerator({
      separator: 'h4:not(.notSeparator)',
      navigation: '.navigationTab',
      tabClassName: '.hashApplied',
      anchorActivate: true
    });
  }

  // Tree Control (sitemap)
  if ($('#navigation').length) {
    var controlTree = '<div id="treecontrol">';
    controlTree += '<a class="collapseAll" title="'+_('contract')+'" href="#">'+_('contract')+'</a>';
    controlTree += '<a class="expandAll" title="'+_('expand')+'" href="#">'+_('expand')+'</a>';
    controlTree += '</div>';
    $(controlTree).insertBefore("#navigation");
    $("#navigation").treeview({
      control: "#treecontrol",
      persist: "location",
      collapsed: true
    });
  }


  // Simple tree Control
  if ($('.toggle').length) {
    $(".toggle").treeview({
      persist: "location",
      collapsed: true
    });
  }

  setupARIA(); // chouilla d'ARIA


  // Recherche Opportunités : formulaire dynamique

  $('#parents').change(function(i,item) {
    var nomRub = $(this).find(':selected').text();
      $('optgroup :selected').removeAttr('selected');
      $('optgroup').not('[label='+nomRub+']').hide().insertBefore($(this));
      $('optgroup[label='+nomRub+']').appendTo('#function').show();
      $('#function').find('option:first').attr('selected','selected');
      /* si on a le premier elt du select #parents selectionne alors on affiche tous les optgroup */
      if ($(this).find(':selected').attr('value') == $(this).find(':first').attr('value')) $('optgroup').appendTo('#function').show();
  });


  /* AJustement graphique */
  $('#toolsSidebar')
    .children(':parent:last')
    .addClass('last')
  $('#toolsSidebar blockquote').each(function() {
    $(this).children('p:first').addClass('last')
  });

  // Lors du click sur le lien d'ajout du panier d'impression, envoie une requete asynchrone.

  $("#da_addPrints a, .da_addPrints a").click(function(){
    // Quelle est l'url à attaquer ?
    var url = $(this).attr("href");

    // On attaque l'url !
    $.get(url);

    if( LANG == 'fr' ){
      var added_txt = 'Page ajoutée au panier d\'impression.';
      var close_txt = 'Fermer cette fenêtre';
      var info_link = '<a href="'+BASE_HREF+'fr/outils/panier-dimpression">Voir le panier d\'impression</a>';
    }
    else{
      var added_txt = 'Page added to the print basket.';
      var close_txt = 'Close this window';
      var info_link = '<a href="'+BASE_HREF+'en/tools/print-basket">Check the print basket</a>';
    }

    // On fait apparaître l'overlayer :)
    var optionsShadowBox = {
      player : 'html',
      height: 150,
      width: 400,
      content : ' \
        <style> #sb-content.html { padding:50px 0 0 0; text-align:center; background: #fff url('+BASE_HREF+'/assets/templates/bourbon/img/illustr/shadowboxillustr.jpg) no-repeat bottom left; } \
          #sb-content.html p {float: none; padding: 0; width: auto;}\
        </style> \
        <p>'+added_txt+'</p><br/><br/> \
        <p>'+info_link+'</p><br/><br/> \
        <p><a href="#" onclick="javascript:window.parent.Shadowbox.close(); return false;">'+close_txt+'</a></p>',
      options : {animate:false,animateFade:false}
    }
    Shadowbox.open(optionsShadowBox);
    return false;
  });

  // On fait apparaître l'overlayer :)
  // jQuery(window).load(function() {
  //   if (PLAY_INTRO && PLAY_INTRO != undefined && PLAY_INTRO == 1) {
  //     if( LANG == 'fr' ){
  //       var contenu_shadowbox = '<p style="text-align: left; padding: 50px 20px 0 20px; font-size: 14px;">\
  //         BOURBON a cédé son activité d’opérateur de transport de Vrac en 2010 et est aujourd’hui un pure player des services maritimes à l’offshore pétrolier.<br/><br/>\
  //         Toutes les informations sur BOURBON : <a href="http://www.bourbon-online.com/fr" title="Se rendre sur le site de BOURBON online">www.bourbon-online.com</a></p>';
  //     } else {
  //       var contenu_shadowbox = '<p style="text-align: left; padding: 50px 20px 0 20px; font-size: 14px;">BOURBON sold its Bulk Freight Operator activity in 2010 and is now an offshore oil & gas services pure player.<br/><br/>\
  //       All information about BOURBON : <a href="http://www.bourbon-online.com/en" title="Visit the BOURBON online website">www.bourbon-online.com</a></p>';
  //     }
  //
  //     Shadowbox.open({
  //       player:     'html',
  //       title:      '',
  //       content:    contenu_shadowbox,
  //       height:     150,
  //       width:      500,
  //       options: {beforeClose: function(){return false}} // Désactivation de la fermeture de page
  //     });
  //     jQuery("#sb-nav-close").css("visibility","hidden");
  //   }
  // })

  // Postuler : affichage dynamique du champ "autre job"
  if( $("select#poste").length ){
    if( $("#field_autre").length ){
      $("#field_autre").hide();
    }
    $("select#poste").change(function(){
      if( $("select#poste").val() < 0 ){
        if( $("#field_autre").length ){
          $("#field_autre").show();
        }
      }
      else{
        if( $("#field_autre").length ){
          $("#field_autre").hide();
        }
      }
    });
  }

  // 01/03/09 : lancement du site : ajout vidéo de présentation en overlayer
  // Si param présent dans url
  /*
  if( (PLAY_INTRO && PLAY_INTRO != undefined && PLAY_INTRO == 1) || window.location.href.indexOf('play_intro') > 0){
    var play_intro = readCookie("PLAY_INTRO");
    if( !play_intro || window.location.href.indexOf('play_intro') > 0){
      Shadowbox.open({
        player:     'flv',
        title:      '',
        content:    BASE_HREF+'medias/videos/welcome.flv',
        height:     400,
        width:      600
      });
      setCookie( 'PLAY_INTRO', '1' );
    }
  }
  */

  // Cartographie : on ajoute le paramètre au lien vers l'overlayer
  if ($('#cartographie_metiers li a').length) {
    $('#cartographie_metiers li a').each(function(i,item) {
        var hrefitem = $(item).attr('href')+'&detectjs=true';
        $(item).attr('href',hrefitem);
    }
  );
  }

  // Overlayer cartographie : on ajoute le paramètre au lien postuler
  var hrefinsiderPopup = $('.insiderPopup').attr('href')+'&detectjs=true';
  if ($('.insiderPopup').length) {
    /* $('.insiderPopup').attr('href',hrefinsiderPopup); */

    $(".insiderPopup").click(function () {
      window.open( BASE_HREF + $(this).attr("href"),"_blank");
      return false;
      });

  }


  if ($('.overlayerQuote').length) {

    var txtLink = '<p class="readMore"><a href="#">'+_('readMore')+'</a></p>';
    $(txtLink).insertAfter('.overlayerQuote blockquote');
    var $pCible = $('.overlayerQuote blockquote p:first');
    $('.overlayerQuote').addClass('jsApplied')
    var txtBlockquote = $('.overlayerQuote .illustr').html();
    txtBlockquote += '<h4>'+$('.overlayerQuote cite').text()+'</h4>';
    txtBlockquote += '<p class="specialtext">'+$pCible.html()+'</p>';

    $('<div id="temoignage_js">'+txtBlockquote+'</div>').insertAfter($('.overlayerQuote')).hide();

    $('.overlayerQuote .readMore a').click(function(){
      $(this).parent().toggle();
      $('.completetext').toggle('slow');
      return false;
    });
  }

  // Rotation des liens vers les sites en home
  if( $("#accessMenu .active").length){
    setInterval(fadeToBanner,5000);
  }
  if( $("#jobTicker").length){
    setInterval(fadeToJob,3000);
  }

  // Bloc qui cycle à travers des images à liens (HR)
  var offers = $('#offersBlock')
  if (offers.length)
    offers.cycle()
  $('#offersBlock,#postulateButton,#youngSpace').css({clear:'left'})

  // Bloc qui cycle à travers des témoignages
  var temoignages = $('.listTemoignagesSmall');
  if (temoignages.length) {
    temoignages
      .before('<div class="prev">&nbsp;</div>')
      .after('<div class="next">&nbsp;</div>')
      .cycle({ prev: '.prev', next: '.next', pause:5*1000 })
  }

  // Gestion des filiales bourbon pour iBidules
  $('#filiales-bourbon').click(function(){
    if($(this).css('height') == 'auto')
      $(this).css('height', '39px')
    else
    $(this).css('height', 'auto')
  })
  $('#toolsAccess .menuItem').click(function(){
    $(this).find('.servicesMenu').toggle()
  })

  // Gestion du Menu
  var menu_active = $('#mainMenu li.active'),
      menu_submenu = $('#mainMenu li:not(#mainMenu li .submenu li)')


  // Réadaptation du menu
  menu_submenu.each(function() {
    if ($(this).find('.submenu').length > 0)
      $(this).split_menu(3, 'submenu')
  })

  // Gestion du Hover
  $('#mainMenu li:not(#mainMenu li ul li)').hover(
    function() {
      $('#mainMenu li.active').removeClass('active')
      $(this).addClass('active').children('div').show()
      $('#mainMenu ul.submenu').show();
    },
    function() {
      $(this).removeClass('active').children('div').stop(true, true).fadeOut('fast')
      if ($('#mainMenu li.active').length == 0)
        menu_active.addClass('active')
    }
  )

 // Envoi d'une page à un ami
 $('#da_serviceSendToAFriend a').click(function(){

   Shadowbox.open({
        content:    BASE_HREF + $(this).attr('href'),
        player:     'iframe',
        title:      $(this).attr('title'),
        height:     480,
        width:      450
    });
    return false;
  });

  // Gestion du cachage du 4e niveau du menu de gauche
  $('#sidebarMenu ul li ul li:not(.active) ul').hide();

  // Gestion des blocs cliquables de la homepage

  $('.pagehome #film-corporate').click(function(){

   Shadowbox.open({
        content:    $(this).find('.moreAbout a').attr('href'),
        player:     'flv',
        title:      $(this).find('.moreAbout a').attr('title'),
        height:     450,
        width:      600
    });
  });


  $('.pagehome #strategie-bourbon-2015').click(function(){
    window.location = $(this).find('.moreAbout a').attr('href');
  });




});

$(window).load(function() {

  $('.navOrganisation').each(function() {
    if(location.hash)
      $(this).find('a[href$='+location.hash+']').click()
  })

  $('#visuelhp img:first').fadeIn(2000, function(){
     $(this).delay(1500).fadeOut(2000).next().delay(3500).fadeIn(2000, function() {
       $(this).delay(1500).fadeOut(2000).prev().delay(3500).fadeIn(2000, function() {
         $(this).delay(1500).fadeOut(2000).next().delay(3500).fadeIn(2000)
       })
     })
   })


  // Application de PIE au window.load() pour IE
  if (window.PIE) {
    $('#visuelhp img').each(function() {
      PIE.attach(this)
    })
  }

  // Egaliseur de colonnes
  $(".cols").equalHeights();
  $(".cols2").equalHeights();
  $(".cols3").equalHeights();

})



