// 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;
  }
});


$(document).ready(function() {

  /* - Ajout de la class PDF aux PDFs - */
  $('a:file(pdf)').addClass('pdf');

  /*
   * Gestion du décalage du menu rouge
   */

   if ($('#nav1 ul ul').length) $('body').addClass('avec-sous-menu')

  /*
   * Cycle des offres colonne droite
   */
  var $lis = $("#offres-teaser li");
  if( $lis.length ){
    $lis.first().parent().height($lis.first().height())
    $lis.css({position:"absolute",zIndex:1}).first().css("z-index","2").addClass("visible");

    setInterval(function(){
      var $current = $lis.filter(".visible");
      var $next = $current.next().length == 1 ? $current.next() : $lis.first();
      $current.fadeOut(1000,function(){
        $current.css("z-index","1").show().removeClass("visible");
        $next.css("z-index","2").addClass("visible");
      });
    },5000);
  }
  /*
   * Gestion des témoignages déroulants
   */
   if (!window.location.hash)
   {
     $('ul.testimonial li .content:gt(0)').hide();
   }
   else
   {
     $('ul.testimonial li .content').hide();
     $(window.location.hash).next('.content').show();
   }
  $('ul.testimonial li .title').click(function(){

    // si on clique sur un témoignage déjà ouvert, il ne se passe rien
    if($(this).next('.content').is(':visible'))
      return false;
    var testimonialid = '#' + $(this).attr('id')
    $.changeHashWithoutScrolling(testimonialid);
    $('ul.testimonial .content').slideUp('slow');
    $(this).next('.content').slideToggle('slow', function(){
        $('html, body').animate({ scrollTop: $(testimonialid).offset().top }, 'slow');
    });

    return false;
  });


  /*
   * Gestion du menu déroulant "autres sites"
   */
  $("footer .last").hover(
    function(){
      $(this).addClass("ouvert");
    },
    function(){
      $(this).removeClass("ouvert");
    }
  );


  /*
   * Gestion des labels ajoutés dans les inputs
   */
  $("label.in-input").each(function(i,label){
    var id = $(label).attr("for");

    $("#"+id).val($(label).text()).live("focus",function(){
      if($(this).val() == $(label).text()){
        $(this).val("");
      }
    }).live("blur",function(){
      if( $(this).val() == "" )
        $(this).val($(label).text());
    });
    $(label).hide();
  });

  /*
   * Menu gauche déroulant
   */
   /*
  $("#nav2>ul>li:not(.active)").live("click",function(){
    console.log($(this));
    return false;
  });

  */
  $('#item-35>a').click(function(){
    return false;
  });
  $("#nav2>ul>li:not(#item-102,#item-28,.active) ul").hide();
  $("#nav2>ul>li:not(#item-102,#item-28)>a").live("click",function(){
    if( $(this).parent().find("ul").is(':visible') )
      $(this).parent().find("ul").slideUp("slow",function(){$(this).parent().toggleClass("active")});
    else
      $(this).parent().toggleClass("active").find("ul").slideDown("slow");
    return false;
  });

  /*
   * Gestion Overlayer image under the flag
   */
   $(".illustr a").colorbox();
   $("a.cboxElement").colorbox();

  /*
   * Gestion de la carte interactive BOURBONMAP
   */
  $('body').delegate('#bourbonmap', 'mouseleave', function() {
    $(this).children().removeClass('hover');
  }).delegate('#bourbonmap div', 'hover', function(){
    $(this).siblings().removeClass('hover');
    $(this).addClass('hover');
  });

  $('#bourbonmap').mouseleave(function() {
    $(this).children().addClass('hover');
  });

  /*
   * Gestion du player vidéo
   */

  // Renvoie true ou false, si canPlayFormat(obj VideoJS, str ext)
  function canPlayFormat( videojs , format){
    var type = "";

    if ( format=='mp4' )
      type = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
    else if ( format=='webm' )
      type = 'video/webm; codecs="vp8, vorbis"';
    else if ( format=='ogv' )
      type = 'video/ogg; codecs="theora, vorbis"';

    if (videojs.video.canPlayType(type) == "probably" || videojs.video.canPlayType(type) == "maybe" )
      return true;

    return false
  }

  // Renvoie l'extension jouable par le player html5, sans le "."
  function getPlayableExt(videojs){
    if ( canPlayFormat(videojs,"mp4") )
      return "mp4";
    if ( canPlayFormat(videojs,"ogv") )
      return "ogv";
    if ( canPlayFormat(videojs,"webm") )
      return "webm";
  }


  // Création d'un object VideoJS
  if ( $("#example_video_1").length ){

    // Navigateurs HTML 5

    var myPlayer = VideoJS.setup("example_video_1", {
      controlsBelow: false, // Display control bar below video instead of in front of
      controlsHiding: true, // Hide controls when mouse is not over the video
      defaultVolume: 0.85, // Will be overridden by user's last volume if available
      flashVersion: 9, // Required flash version for fallback
      linksHiding: true, // Hide download links when video is supported
//      playerFallbackOrder: ["flash", "html5", "links"]
      playerFallbackOrder: ["html5", "flash", "links"]
    });
    // Changement de source de la vidéo au click sur les vignettes

    var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

    if ($('#example_video_1').is(':visible') && !isIE6) { /* si on utilise le player html5 */

      $(".video-link a").live("click",function(){

        var link = $(this).attr("data-video");
        var path = dirname(link);
        var base =  basename(link,".flv");

        $('div.videoplayer figcaption span.job').text($(this).parent().find('a.job').html());
        $('div.videoplayer figcaption span.name').text($(this).parent().find('a.name').html());
        $('div.videoplayer figcaption span.job').attr('class', $(this).parent().find('a.job').attr('class'));

        // $('html, body') ne fonctionne pas sur Mobile Safari
        $('html').animate({scrollTop : 0},1500);
        $('body').animate({scrollTop : 0},1500);

        myPlayer.pause();
        myPlayer.video.src = path + '/' + base + "." + getPlayableExt(myPlayer);
        myPlayer.video.load();
        myPlayer.video.play();
    //    console.log("Nouvelle source : " + myPlayer.video.src );

        return false;
      });
    }
    else{

      $(".video-link a").live("click",function(){

        var link = $(this).attr("data-video");
        var thumb = $(this).parent().find('img.thumb').attr('src');

        $('div.videoplayer figcaption span.job').text($(this).parent().find('a.job').html());
        $('div.videoplayer figcaption span.name').text($(this).parent().find('a.name').html());
        $('div.videoplayer figcaption span.job').attr('class', $(this).parent().find('a.job').attr('class'));

        $('html').animate({scrollTop : 0},1500);
        $('body').animate({scrollTop : 0},1500);
        $(window).animate({scrollTop : 0},1500);
        $(document).animate({scrollTop : 0},1500);



        $('.video-js-box').html('<object id="flash_fallback_1" class="vjs-flash-fallback" width="400" height="300" type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"><param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /><param name="allowfullscreen" value="true" /><param name="flashvars" value=\'config={"playlist":["' + thumb + '", {"url": "' + link + '","autoPlay":true,"scaling":"fit","autoBuffering":true}]}\' /><img src="' + thumb + '" width="400" height="300" alt="Poster Image" title="No video playback capabilities." /></object>');


        //var replaceclip = {'url':link, 'autoplay':true};
        //VideoJS.flashPlayers.htmlObject.api(replaceclip);


        if(!isIE6)
        return false;
      });
    }
  }


  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 < 4; i++) {
      if (!etapes[i]) $("#rss_form li").eq(i).css("background-color", "#6A6E71");
      else $("#rss_form li").eq(i).css("background-color", color);
    }
  }

  rssEtapes();
  $("input[name^=feeds]").click(function () {
    rssEtapes();
  });
  $("input[name=reader]").click(function () {
    rssEtapes();
  });

  $('#rss_form li#rsssubmit a').click(function(){
            if($('body').hasClass('ajax')) return false;
      $('body').addClass('ajax');

      $('li#rssresults div p').slideUp('slow');

      $.post( $('form#rss_form').attr('action'), $('form#rss_form').serialize(),
        function( data ) {
          $('li#rssresults div p').slideUp(function(){
            $(this).html(data);
            $("#rss_form li").eq(3).css("background-color", "#2A3874");
            $(this).slideDown('slow');
          });
          $('body').removeClass('ajax');
        }
      );

      return false;

  });


});


/*
 * Fonctions diverses
 */

function basename (path, suffix) {
  var b = path.replace(/^.*[\/\\]/g, '');
  if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix) {
    b = b.substr(0, b.length - suffix.length);
  }
  return b;
}
function dirname (path) {
    return path.replace(/\\/g, '/').replace(/\/[^\/]*\/?$/, '');
}


// Change the window location #hash
// But makes sure it doesn't scroll by renaming the id temporarily
$.changeHashWithoutScrolling = function(hash) {
  var elem = $(hash),
      id = elem.attr('id')
  elem.attr('id', id+'-tmp')
  window.location.hash = hash
  elem.attr('id', id)
}

// opens rel="external" links in new windows. is standards compliant.

function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for (var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; } } window.onload = externalLinks;

