if(typeof(console) != 'object' || typeof(console.log) != 'function')
  console = {log: function() {}};

/* scroll liens vers ancres */
var scrolling = function(){
  var speed = 1000;
  $('a[href^="#"]').bind('click',function(){
    var id = $(this).attr('href');
    if(id == '#')
      goTo('body');
    else
      goTo(id);
    return(false);
  });
  function goTo(ancre){
    $('html,body').animate({
      scrollTop:$(ancre).offset().top
      },speed,'swing', function() {
      if(ancre != 'body')
        window.location.hash = ancre;
      else
        window.location.hash = '#';
      $(ancre).attr('tabindex','-1');
      $(ancre).focus();
      $(ancre).removeAttr('tabindex');
    });
  }
};
/*--------------------*/

/*
 * Fonctions pour splash screen
 */
 
function instantHideOvpi(target) {
  jQuery('#ovpi .inside').html('');
  jQuery('html').css('overflow','scroll'); /*pour ie6*/ 
  jQuery('#trame').hide(0);
  enableShowOvpi(target);
}
function hideOvpi(target) {
  target.animate({left: "-330"}, 500, 'linear', function(){
    target.addClass('closed');
    jQuery('#trame').fadeOut(50);
    jQuery('html').css('overflow','scroll'); /*pour ie6*/  
    jQuery('#ovpi .inside').html('');
    enableShowOvpi(target);
  });
}
function showOvpi(target) {
  jQuery('a.toggle').unbind('mouseover');
  jQuery('a.toggle').unbind('mouseout');
  target.animate({left: "50%"}, 500, 'linear', function(){
    target.removeClass('closed');
    enableHideOvpi(target);
    jQuery('#trame').fadeIn(50);
  });
  jQuery('#ovpi .inside').html('<iframe width="720" height="558" src="http://www.youtube.com/embed/VCjFabup6yQ?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>');
}
function enableHideOvpi(target) {
    jQuery('a.toggle').unbind('click');
    jQuery('a.toggle, #trame').click(function(){hideOvpi(target);});
}
function enableShowOvpi(target) {
    jQuery('a.toggle, #trame').unbind('click');
    jQuery('a.toggle').mouseover(function () {
      target.animate({left: "-320"}, 100);
    });
    jQuery('a.toggle').mouseout(function () {
      target.animate({left: "-330"}, 100);
    });
    jQuery('a.toggle').click(function(){showOvpi(target);});
}
 

/**
 * Actions
 */
$(document).ready(function(){

  /*------------------------------------------------------------------------------*/
  /* USUAL */
  /*------------------------------------------------------------------------------*/
  $("body").addClass('js-enabled');
  $(function(){
    scrolling();
  });
  
  /* gestion splash */
	if(document.getElementById('ovpi')){
		jQuery('#ovpi').addClass('js-enabled');
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		  jQuery("body","html").css({height: "100%", width: "98%"});
		  if (document.getElementById("HideSelect") === null) {//iframe to hide select elements in ie6
      jQuery("html").css("overflow","hidden");
			jQuery("body").append("<iframe id='HideSelect'></iframe><div id='trame'></div>");
		  }
		}else{//all others
		  if(document.getElementById("TB_overlay") === null){
			jQuery("body").append("<div id='trame'></div>");
		  }
		}
    jQuery('#ovpi').prepend('<p id="js-toggle-ovpi"><a href="#" class="toggle">Fermer</a></p>'); 
    if(jQuery('#ovpi').hasClass('closed')) {
      instantHideOvpi(jQuery('#ovpi'));
    } else {   
      jQuery('#ovpi .inside').html('<iframe width="720" height="558" src="http://www.youtube.com/embed/VCjFabup6yQ?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>');
      enableHideOvpi(jQuery('#ovpi'));
    }
	}
	/*--------------------------*/
  
  /* ajoute un target _blank au lien avec une classe external */
  $("a[rel='external'], a[rel='document'], a[href^='http://'], a[href^='mailto'], a[href$='.pdf'], a[href$='.doc'], a[href$='.xls'], a[href$='.txt']").each(function(){
    if($(this).attr('rel') != 'bookmark') {
      $(this).attr({
        title: ($(this).attr("title"))?$(this).attr("title"):$(this).attr("href")+" (nouvelle fenêtre)"
      });
      $(this).click(function() {
        window.open($(this).attr('href'));
        return false;
      });
    }
  });
  /*----------------------------------------------------------*/

  /* changement de curseur auto sur evenements click */
  $.event.special.click = {
    setup: function() {
      $(this).css('cursor','pointer');
      return false;
    },
    teardown: function() {
      $(this).css('cursor','');
      return false;
    }
  };
  /*----------------------------------------------------------*/
  
  /* gestion selecteur odd sur tableaux */
  $('#content .rich-text table tr:odd').addClass('odd');
  $('#content .rich-text table tbody td').hover(function(){
    $(this).parent().addClass('hover')
    },function(){
    $(this).parent().removeClass('hover')
    });
  /* -------------------------- */
  
  /* gestion changment de couleur sur titres h2 pages internes */
  $('body:not(#home) #content > h2').each(function(){
    var title = $(this).html();
    var first_space = title.indexOf(' ');
    if(first_space > 0) {
      var begin_title = title.substring(0,first_space);
      var end_title = title.substring(first_space, title.length);
    } else {
      var begin_title = title.substring(0,title.length/2);
      var end_title = title.substring(title.length/2, title.length);
    }
    $(this).html('<span>'+begin_title+'</span>'+end_title);
  })
  /* -------------------------- */
  
  /* gestion selecteur last-child sur breadcrumb pour ie */
  $('ul:not(.actions) li:last-child').addClass('last-child');
  /* -------------------------- */
  
  
  /* navigation accès directs */
  $('#direct-access').css('top','-21px');
  /*$('#direct-access').css('cursor','pointer');*/
  
  /* mouse events */
  $('.js-enabled #direct-access').hover(
    function(){
      $('#direct-access').animate({
        top: '0'
      }, {
        queue:false,
        duration :500
      });
    },
    function(){
      $('#direct-access').animate({
        top: '-21px'
      }, {
        queue:false,
        duration :500
      });
    }
    );
  $('.js-enabled #direct-access a').focus(function(){
    $('.js-enabled #direct-access').animate({
      top: '0'
    }, {
      queue:false,
      duration :500
    });
  });
  /* -------------------------- */

  /* accordeon blocs contenus seulement si plusieurs blocs présents */
  if($('.expand').length > 1) {
    $(".expand").prev().addClass('toggle');
    $(".expand:gt(0)").parent().addClass('closed');
    $(".expand:gt(0)").hide();
      
    $('.expand').prev().click(function() {
      $(this).next().slideToggle('fast')
      $(this).parent().toggleClass('closed')
    })
    if($(".expand")[0]!=undefined){
      $("#main > h2").after('<ul class="actions"><li class="toggle_all"><a href="#">Tout déplier</a></li></ul>');
      $(".toggle_all a").toggle(
        function(){
          $('.expand').slideDown('fast')
          $('#main .bloc-wrap').removeClass('closed')
          $('.toggle_all a').fadeOut('fast', function(){
            $(this).html('Tout replier');
            $(this).fadeIn('fast')
            });
        },
        function(){
          $('.expand').slideUp('fast')
          $('#main .bloc-wrap').addClass('closed')
          $('.toggle_all a').fadeOut('fast', function(){
            $(this).html('Tout déplier');
            $(this).fadeIn('fast')
            });
        })
    }
  }
  /* -------------------------------------------------------*/  
  /* Recherche */
  $("#quick-search p:not(.submit) input").each(function(){
    if(!$(this).val())
    {
      $(this).attr('value',$(this).prev().html());
    }
    $(this).prev().css('display','none');
    $(this).click(function() {
      if ($(this).val() == $(this).prev().html()){
        $(this).val('');
      }
    });
    $(this).blur(function() {
      if ($(this).val() == '')
      {
        $(this).val($(this).prev().html());
      }
    });
  });
  /*--------------------*/
  
  /* hauteur main */
  if(!document.getElementById('home')){
    if($('#sub').height() > $('#main').height()) {
      $('#main').height($('#sub').height());
    } 
  };
  /*----------------------------------------------------------*/
  /* ------------------------------------------ */
  
  /* animation flash header home sample*/
  /*  if ($('#home').length) {  
      var flashvars = {};
      var params = {};
      params.scale = "noscale";
      params.wmode = "transparent";
      var attributes = {};
      attributes.id = "target_element_id";
      swfobject.embedSWF("/flash/animation.swf", "swfanimation", "710", "500", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
    }*/
  /*--------------------------*/

  /*------------------------------------------------------------------------------*/
  /* FORMULAIRES */
  /*------------------------------------------------------------------------------*/
  /*gestion class "current" sur paragraphe ayant le focus*/
  $('#main form:not(.filter-form) p:not(.submit) *')
  .focus(function(){
    $(this).closest('p:not(.area)').toggleClass('current');
  })
  .blur(function(){
    $(this).closest('p:not(.area)').toggleClass('current');
  });
  /*--------------------*/
    
  /*Formulaire : gestion class "current" sur fieldset*/
  $('#main form:not(.filter-form) p:not(.submit) *')
  .focus(function(){
    $(this).closest('fieldset').toggleClass('current');
  })
  .blur(function(){
    $(this).closest('fieldset').toggleClass('current');
  });
  /*--------------------*/
  /*------------------------------------------------------------------------------*/
  

  /* ciblage lien 2s3i en pied de page */
  $('#footer-nav a[href=http://www.2s3i.com]').parent().attr('class', 'ss3i');
  $('#footer-nav .ss3i span').css('display', 'none');
  /*--------------------*/

 
  /* ciblage lien 2s3i en pied de page */
 

  var format_date = function(raw) {
    var parts = (/\w+ (\w+) (\d+) (\d+:\d+:\d+) [+-]\d+ (\d{4})/).exec(raw);
    var d = new Date(parts[1]+' '+parts[2]+', '+parts[4]+' '+parts[3]);
    return [
      d.getDate(),
      ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()],
      d.getFullYear(),
      [d.getHours(), 'h', (Math.floor(d.getMinutes() / 10) == 0 ? '0' : ''), d.getMinutes()].join('')
    ].join(' ');
  }

  var format_text = function(t) {
    if(typeof t == 'string')
      return t.replace(/http:\/\/([\w\d:#@%/;$()~_?\+\-=\\\.&]*)/, '<a href="http://$1">$1</a>');
    return t;
  }

  if($('#telex').length)
  {
    $.ajax({
      url: 'http://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=' + $('#telex').attr('class') + '&count=2',
      type: 'GET',
      dataType: 'jsonp',
      success: function(data) {
        console.log('success')
        $('#telex .telex-list > li').remove();
        if(data.length > 0)
        {
          $.each(data, function() {
            $('#telex .telex-list').append('<li>' + format_text(this.text) + '<span>' + format_date(this.created_at) + '</span></li>')
          });
        }
        else
          $('#telex .telex-list').append('<li class="empty">Aucun telex pour l\'instant</li>');
      }
    });
  }

  $("#main-nav .book a").fancybox();
  
  
  $(".rich-text p.left,  .rich-text p.right").each(function(i) 
	{
		if($(this).find('img').attr('alt') !=''){
      $(this).append("<div class='thecaption'>" + $(this).find('img').attr('alt') + "</div>");
      $(this).addClass('has-caption');
    }
	});
  
  /*--------------------*/
  
  /*------------------------------------------------------------------------------*/
  /* PLUGINS */
  /*------------------------------------------------------------------------------*/
  
  /* augmente la portée du survol d'un lien à son conteneur */
    if(typeof $(this).biggerlink == 'function') {  
      $('#references-widget li div.description').biggerlink({link: '.read-more a'});
    }
    /*--------------------*/
  
  if(typeof $(this).makeacolumnlists == 'function') {
    $('#nav-savoir-faire ul, #nav-prestations ul').removeClass('multiColumns');
    $('#nav-savoir-faire ul, #nav-prestations ul').makeacolumnlists({
      cols: 2,
      colWidth: 0,
      equalHeight: false,
      startN: 1
    });
    $('#contextual-menu ul').makeacolumnlists({
      cols: 2,
      colWidth: 0,
      equalHeight: false,
      startN: 1
    });
  }
  
  /* menu deroulant */
  if(typeof $(this).superfish == 'function') {   
    $('#main-nav > ul').superfish({
      autoArrows: false
    });
  }
  /* -------------------------- */

  
  /* fancy zoom (jquery.fancybox)*/
  if(typeof $(this).fancybox == 'function') { 
    $("a[href$='.JPG'], a[href$='.jpg'], a[href$='.gif'], a[href$='.png']").each(function(){
      if(!$(this).parent().parent().hasClass('thumbs')){
        $(this).fancybox({
          overlayShow: true,
          overlayOpacity: 0.8,
          overlayColor: '#000',
          centerOnScroll: true
        });
      }
    });
    $(".gallery a[href$='.JPG'],.gallery  a[href$='.jpg'],.gallery a[href$='.gif'],.gallery a[href$='.png']").each(function(){
      $(this).append('<p>'+$(this).find('img').attr('alt')+'</p>');
    });
    if($(".msg").length > 0)
      $.fancybox($(".msg"), {
        overlayOpacity: 0.8,
        overlayColor: '#000',
        padding: 0,
        extraClass: 'modal',
        onClosed: function(){
          $('.msg').hide()
          }
        });
}
/*--------------------*/ 
  
/* masked Input*/
if(typeof $(this).mask == 'function') {  
  if($("form .tel input").length > 0){
    $("form .tel input").mask("99-99-99-99-99");
  }
}
/*--------------------*/ 

  
/* slider agenda */
if(typeof $(this).cycle == 'function'){
  $('#push-list').after('<div id="push-nav"></div>').cycle({
    fx:     'scrollRight',
    speed:  1000,
    timeout: 8000,
    pager:  '#push-nav'
  });
    
  $('#references-widget').after('<ul id="references-nav"><li id="prev"><a href="#">précédent</a></li><li id="next"><a href="#">suivant</a></li></ul>').cycle({
    fx:     'scrollRight',
    speed:  'slow',
    next:   '#references-nav #next a',
    prev:   '#references-nav #prev a' ,
    speed:  1000,
    timeout: 4000
  });
  
  $('.visuels > img').wrap('<div id="viewport">') ;
  $('#viewport').append('<img width="510" height="285" alt="" src="" style="display:none;z-index:2;">') ;
  if($('.thumbs li:eq(1) img').attr('src') !=''){
    $('.thumbs li:eq(1)').addClass('current') ;
  } else {
    $('.thumbs li:eq(0)').addClass('current') ;
  }
  $('.thumbs li a').click(function(e){
    e.preventDefault();
    $(this).parent().parent().find('li').removeClass('current');
    $(this).parent().addClass('current');
    var newElement = $('#viewport').find('img:hidden');
    var oldElement = $('#viewport').find('img:visible');
    newElement.attr('src', $(this).attr('href'));
    oldElement.fadeOut('',function(){$(this).css('z-index:2;');newElement.css('z-index:1;');newElement.fadeIn();});
  }) ;
  
  
}
/*------------------------------------------------------------*/


      



  
/* Daterangepicker */
if(typeof $(this).daterangepicker == 'function'){
  if($('.daterange').length > 0)
  {
    $('.daterange input').daterangepicker({
      posX:0,
      posY:0,
      dateFormat: 'dd/mm/yy',
      appendTo: $('.daterange'),
      datepickerOptions: {
        dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
        monthNames: ['Janvier','Fevrier','Mars','Avril','Mars','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre']
      }
    });
  }
}
/*--------------------*/
  
/* tooltip sample (jquery.tooltip.min.js plugin)*/
if(typeof $(this).tooltip == 'function')
{
    
  /* tooltip sur liens avec attribut title */
  $('a').each(function(){
    if($(this).attr('title')){
      $(this).data('text', ($(this).attr('title'))?$(this).attr('title'):$(this).html());
      $(this).tooltip({
        track: true,
        showURL: false,
        bodyHandler: function() {
          return $(this).data('text');
        },
        delay: 15
      });
    }
  })
  /*--------------------*/
    
  /* tooltip pour messages erreur formulaires */
  if($('form .error').length > 0)
  {
    $('form p.error *')
    .each(function(){
      $(this).data('text', $(this).parent().find('span.error').html());
      $(this).parent().find('span.error').hide();
      $(this).tooltip({
        track: true,
        showURL: false,
        bodyHandler: function() {
          return $(this).data('text');
        },
        delay: 15
      });
    })
      
  }
  /*--------------------*/
    
  /* tooltip pour messages d'aide */
  if($('span.help').length > 0)
  {
    $('span.help')
    .each(function(){
      $(this).data('text', $(this).html());
    })
    .tooltip({
      track: true,
      showURL: false,
      bodyHandler: function() {
        return $(this).data('text');
      },
      delay: 15
    });
  }
/*--------------------*/
}
/* fin tooltip */
/*------------------------------------------------------------*/
  
  
  
});
