jQuery(document).ready(function(){

//ACTIVE MENU TOTAL CONFORT
  if(typeof( easytoog_admin ) != 'undefined') {
    var id = location.pathname.split('/').pop();
    $('.menupage').find('a').each(function(i){
      if (id == this.href.split('/').pop())
      {
        $(this).parents('li').addClass('active');
      }
    });
  }
  else $('.menupage').find('a[href="'+ location.pathname +'"]').parents('li').addClass('active');

// QUIZZ TOTAL CONFORT
  $('.boxlittle_pink').hide();
  $('.checkquizz span').click(function(event) {
    $(this).parents('.quizz_answers').find('span').removeClass('active');
    $(this).parents('.quizz_answers').find('p').removeClass('active');
    $(this).addClass('active');
    $(this).parent().next().find('p').addClass('active');
  });
  $('.checkquizz p').click(function(event) {
    $(this).parents('.quizz_answers').find('span').removeClass('active');
    $(this).parents('.quizz_answers').find('p').removeClass('active');
    $(this).addClass('active');
    $(this).parent().prev().find('span').addClass('active');
  });

  $('.check_quizz').click(function(event){
    event.preventDefault();
    var nb_ok = 0;
    var nb_questions = 0;
    $('.quizz_answers').each(function(i) {
      nb_questions++;
      if ($(this).find('span.true.active').length == 1)
      {
        var answer = 'true';
        nb_ok++;
      }
      else
      {
        var answer = 'false';
      }
      $(this).find('p').removeClass('barre').removeClass('colorgreen');
      $(this).find('p.false.active').addClass('barre');
      $(this).find('p.true').addClass('colorgreen');

      $(this).parents('.quizz').find('.resultquizz_' + answer).show();

    });
    $('.boxlittle_pink').show();
    $('.fullresult').html(nb_ok + ' / ' + nb_questions);
  });



  //toogle FAQ
  jQuery(".toggle_faq").hide();
  jQuery("h2.triggerfaq").click(function(){
    jQuery(this).toggleClass('activefaq');
    jQuery(this).next(".toggle_faq").slideToggle("slow");
    return false;
  });

  //tooltip
  jQuery(".west").tipsy({gravity: 'w', 'fade':true});
  jQuery(".north").tipsy({gravity: 's', 'fade':true});
  jQuery(".south").tipsy({gravity: 'n', 'fade':true});
  jQuery(".east").tipsy({gravity: 'e', 'fade':true});

  //slide_panels
  jQuery('div.tabs ul.tabNavigation a').click(function () {
    jQuery(".toggle_container").slideUp('slow');
    if(jQuery('.active').length == 0) {
      jQuery(jQuery(this).addClass('active').attr('href')).slideDown('slow');
      return false;
    }
    if (jQuery(this).hasClass('active')) {
      jQuery(jQuery(this).removeClass('active').attr('href')).slideUp('slow');
      return false;
    }
    jQuery(jQuery('.active').removeClass('active').attr('href')).hide();
    jQuery(jQuery(this).addClass('active').attr('href')).show();
    return false;
  });

  jQuery('.toggle_container').hide();
  jQuery('span.trigger').click(function() {
    jQuery(this).toggleClass('active2');
    jQuery(this).next('.toggle_container').slideToggle('fast');
    return false;
  });

  //tabs_panel2
  jQuery(function () {
      var tabContainers = jQuery('#panel2_content_right > div');
      tabContainers.hide().filter(':first').show();
      jQuery('div.tabs_nav2 ul.tabNavigation_hover a').hover(function () {
        tabContainers.hide();
        tabContainers.filter($(this).attr('rel')).show();
        return false;
      });
    });

  //tabs_panel3
  jQuery(function () {
      var tabContainers = jQuery('#panel3_content_right > div');
      tabContainers.hide().filter(':first').show();

      jQuery('div.tabs_nav3 ul.tabNavigation_hover2 a').hover(function () {
        tabContainers.hide();
        tabContainers.filter($(this).attr('rel')).show();
        return false;
      });
    });

  handleSelectionEvents();

  if(typeof(toogloadconsole) == 'undefined')
  {
    $.post('/load-selection', function(data)
    {
      if(!data)
      {
        return;
      }

      var response = eval('(' + data + ')');

      jQuery.cookie('favoritePages', response.pages, {path: '/'});
      jQuery.cookie('favoriteDocuments', response.documents, {path: '/'});
    });
  }
  else
  {
    favorite_pages_build();
    favorite_docs_build();
  }

  $('#panel1 .panel_col1 .selection_select_all').click(function()
  {
    $('#pages_favorites input[type=checkbox]').attr('checked', 'checked');
    return false;
  });

  $('#panel1 .panel_col1 .selection_delete_checked').click(function()
  {
    var indexes = new Array();
    $('#pages_favorites input[type=checkbox]:checked').each(function()
    {
      indexes[indexes.length] = parseInt($(this).attr('id'));
      $(this).parent('li').remove();
    });

    favorite_pages_delete(indexes, false);

    if(typeof(toogloadconsole) == 'undefined')
    {
      $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
    }

    return false;
  });

  $('#panel1 .panel_col2 .selection_select_all').click(function()
  {
    $('#documents_favorites input[type=checkbox]').attr('checked', 'checked');
    return false;
  });

  $('#panel1 .panel_col2 .selection_delete_checked').click(function()
  {
    var indexes = new Array();
    $('#documents_favorites input[type=checkbox]:checked').each(function()
    {
      indexes[indexes.length] = parseInt($(this).attr('id'));
      $(this).parent('li').remove();
    });

    favorite_docs_delete(indexes, false);

    if(typeof(toogloadconsole) == 'undefined')
    {
      $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
    }

    return false;
  });

  jQuery('.toggle_container a.delete').click(function() {
    jQuery(this).closest('.panel_col').find('input.checkbox:checked').parent().fadeOut('500', function() {
      jQuery(this).remove();
    });
    jQuery(this).closest('.toggle_container').prev('span.trigger').click();
    return false;
  });

  jQuery('.nos-produits-panel-content').hide();
  //jQuery('#breadcrumb_produit').hide();
  //jQuery('#infos_produit').hide();

  if(jQuery.isFunction(jQuery.fn.prettyPhoto))
  {
    jQuery('a[href$=".flv"]').click(function()
    {
        var sitename = 'atlprochaudiere';
        var flashvars = '&amp;autoplay=1&amp;showvolume=1&amp;showfullscreen=1&amp;showplayer=always';
        var flv_path = jQuery(this).attr('href');

        if(flv_path.indexOf('/easylink/') !== -1)
        {
          //Admin
          flv_path = flv_path.replace(/\/([a-z0-9_]+\.php\/)?easylink\/video/i, '/mediasources/' + sitename + '/videos');
          jQuery(this).attr('href', '/sites/' + sitename + '/images/player_flv_maxi.swf?width=530&height=320&flashvars=flv=' + flv_path + flashvars);
        }
        else if(flv_path.indexOf('player_flv_maxi.swf') === -1) //test pour eviter de refaire le remplacement si on clique plusieurs fois
        {
          //Public
          jQuery(this).attr('href', '/images/player_flv_maxi.swf?width=530&height=320&flashvars=flv=' + flv_path + flashvars);
        }

        jQuery(this).attr('title', '');
      });

    if(jQuery('a[href$=".flv"]').size() > 0)
    {
      jQuery('a[href$=".flv"]').prettyPhoto({
        theme:      'facebook',
        showTitle:  false
      });
    }
  }

  jQuery('.show_club_label').click(function(e)
  {
    e.preventDefault();
    jQuery(this).next('.hidden_club').slideDown();

    var container = jQuery(this).closest('#espace_pro_toogle').length ? jQuery(this).closest('#espace_pro_toogle') : jQuery(this).closest('#espace_pro_toogle2');
    container.css({backgroundPosition: "left -10px"});
  });

  jQuery('.commande_cadeaux_link').click(function(e) {
    e.preventDefault();
    $('#breadcrumb')
      .nextUntil('#page-footer').remove().end()
      .empty().html('<iframe src="'+this.href+'" width="100%" height="5000px" border="none" style="border: none; margin-top: 10px; background: #fff;" />');
  });

  initializeSpecsTable();
  initializeProductTabs();
});

function handleSelectionEvents()
{
  jQuery('.add_page_to_favorites').unbind('click').click(function()
  {
    favorite_pages_add($(this).attr('href'), $(this).attr('tabindex'), $(this).find('strong').html());

    var unique_id = jQuery.gritter.add({
      // (string | mandatory) the heading of the notification
      title: 'Page ajouté à votre sélection !',
      // (string | mandatory) the text inside the notification
      text: 'Consulter et gérer vos pages favorites dans la barre des onglets en haut de cette page',
      // (string | optional) the image to display on the left
      image: jQuery(this).attr('rel'),
      // (bool | optional) if you want it to fade out on its own or just sit there
      sticky: false,
      // (int | optional) the time you want it to be alive for before fading out
      time: '4000'
      // (string | optional) the class name you want to apply to that specific message
      //class_name: 'my-sticky-class'
    });

    return false;
  });

  jQuery('.add_document_to_favorites').unbind('click').click(function()
  {
    var href = $(this).prev('a').attr('href');
    var titre = $(this).closest('div').find('.doc_description_titre').html();
    var format = $(this).closest('div').find('.file_format').html().split('/')[1];
    var taille = $(this).closest('div').find('.file_size').html();
    favorite_docs_add(href, $(this).attr('tabindex'), titre, format, taille);

    var unique_id = jQuery.gritter.add({
      // (string | mandatory) the heading of the notification
      title: 'Document ajouté à votre sélection !',
      // (string | mandatory) the text inside the notification
      text: 'Consulter, gérer et télécharger vos documents dans la barre des onglets en haut de cette page',
      // (string | optional) the image to display on the left
      image: jQuery(this).attr('rel'),
      // (bool | optional) if you want it to fade out on its own or just sit there
      sticky: false,
      // (int | optional) the time you want it to be alive for before fading out
      time: '4000'
      // (string | optional) the class name you want to apply to that specific message
      //class_name: 'my-sticky-class'
    });

    return false;
  });
}


//customlistscroll
function updateSlider1()
{
  jQuery('#content-slider').slider('destroy');
  jQuery('#content-slider').slider({
    slide: function(event, ui) {
      jQuery('#customlistscroll').scrollTo(jQuery('#customlistscroll ul li')[Math.ceil(-ui.value/2)]);
    },
    change: function(event, ui) {
      jQuery('#customlistscroll').scrollTo(jQuery('#customlistscroll ul li')[Math.ceil(-ui.value/2)]);
    },
    orientation: 'vertical',
    min: -((jQuery('#customlistscroll ul li').length - 5) * 2),
    max: 0
  });
  jQuery('#customlistscroll, #container-slider').unbind('mousewheel').mousewheel(function(event, delta){
    jQuery('#content-slider').slider('value', jQuery('#content-slider').slider('value') + delta)
    return false;
  });
}

//customlistscroll2
function updateSlider2()
{
  jQuery('#content-slider2').slider('destroy');
  jQuery('#content-slider2').slider({
    slide: function(event, ui) {
      jQuery('#customlistscroll2').scrollTo(jQuery('#customlistscroll2 ul li')[Math.ceil(-ui.value/2)]);
    },
    change: function(event, ui) {
      jQuery('#customlistscroll2').scrollTo(jQuery('#customlistscroll2 ul li')[Math.ceil(-ui.value/2)]);
    },
    orientation: 'vertical',
    min: -((jQuery('#customlistscroll2 ul li').length - 5) * 2),
    max: 0
  });
  jQuery('#customlistscroll2, #container-slider2').mousewheel(function(event, delta){
    jQuery('#content-slider2').slider('value', jQuery('#content-slider2').slider('value') + delta)
    return false;
  });
}


function initializeProductTabs()
{
  //Gallery images
  if(jQuery.isFunction(jQuery.fn.prettyPhoto))
  {
    if(jQuery("a[rel^='prettyPhoto']").size() > 0)
    {
      jQuery("a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});
    }
    if(jQuery("a[rel^='prettyInline']").size() > 0)
    {
      jQuery("a[rel^='prettyInline']").prettyPhoto({theme:'facebook', changepicturecallback: function () {if(typeof(toogloadconsole) != 'undefined') reloadEvents()}});
    }
    if(jQuery("a[rel^='prettySpecs']").size() > 0)
    {
      jQuery("a[rel^='prettySpecs']").prettyPhoto(
      {
        theme:'facebook',
    default_width: 980,
        changepicturecallback: function()
        {
          var count_variants = jQuery('.pp_content_container .FixedTables thead th').length - 2;
          jQuery('.pp_content_container .FixedTables').width(240 * count_variants + 100);
          jQuery('.pp_content_container .FixedTables td.unit, .pp_content_container .FixedTables th:eq(1)').width(80);
        }
      });

    jQuery('.specs_print').live('click', function(e){
        var windowPrint = window.open();
    windowPrint.document.write(
      '<head>'+
        '<style media="print">'+
        'table { font-size: 9px; text-align: center; } '+
        '.specname, .tab_subtitle { text-align: left; } '+
        '.odd { background-color: #f5f5f5; } '+
      '</style>'+
      '</head>'+
      '<body>'+
        '<table>'+
              $('#Open_Text_Arrays').html()+
      '</table>'+
      '</body>'
    );
        windowPrint.print();
        windowPrint.close();
    });
    }
  }

  if(jQuery('.gal').length > 0 && jQuery('.ressources_gallery').length > 0)
  {
    // Ca marche mais c'est tres sale, voir pour une autre solution?
    var nb_images = jQuery('.gal img').length;
    var nb_loaded_images;

    var interval = setInterval(function() {
      nb_loaded_images = 0;
      jQuery('.gal img').each(function() {
        if(jQuery(this).height() > 0)
        {
          nb_loaded_images++;
        }
      });

      if(nb_loaded_images >= nb_images)
      {
        jQuery('.gal').masonry({
          singleMode: true,
          itemSelector: '.ressources_gallery'
        });
        clearInterval(interval);
      }
    }, 100);
  }

  handleSelectionEvents();


  var tabContainers = jQuery('div.tabs_prod > div');
  tabContainers.hide().filter(':first').show();

  jQuery('div.tabs_prod ul.tabNavigation_prod a').click(function () {
    tabContainers.hide();
    tabContainers.filter(this.hash).show();
    jQuery('div.tabs_prod ul.tabNavigation_prod a').removeClass('selected2');
    jQuery(this).addClass('selected2');
    return false;
  }).filter(':first').click();
}

function initializeColumnsNavigation()
{
  //columnNavigation
  jQuery("#myTree").columnNavigation({
    containerPosition:"relative",
    containerWidth:"772px",
    containerHeight:"250px",
    columnWidth:257,
    columnFontSize:"11px",
    columnSeperatorStyle:"1px solid rgb(220,220,220)",
    containerBorder:"none",
    columnDeselectFontWeight:"normal",
    columnDeselectColor:"rgb(50,50,50)",
    columnSelectFontWeight:"normal",
    columnSelectBackgroundColor:"rgb(155,156,158)",
    columnSelectBackgroundImage:"url('/images/produit/nav_fleche_grise.png')",
    columnSelectBackgroundPosition:"233px -1px",
    leafDeselectColor:"#FFF",
    leafDeselectBackgroundColor:"#B71234",
    leafDeselectBackgroundPosition:"233px -1px",
    leafSelectBackgroundColor:"#B71234",
    leafSelectBackgroundImage:"url('/images/produit/nav_last_rouge.png')",
    leafSelectBackgroundPosition:"233px -1px",
    columnItemPadding:"0px 3px 0px 3px",
    columnScrollVelocity:200
  });

  jQuery("#myDocsTree").columnNavigation({
    containerPosition:"relative",
    containerWidth:"772px",
    containerHeight:"250px",
    columnWidth:257,
    columnFontSize:"11px",
    columnSeperatorStyle:"1px solid rgb(220,220,220)",
    containerBorder:"none",
    columnDeselectFontWeight:"normal",
    columnDeselectColor:"rgb(50,50,50)",
    columnSelectFontWeight:"normal",
    columnSelectBackgroundColor:"rgb(155,156,158)",
    columnSelectBackgroundImage:"url('/images/produit/nav_fleche_grise.png')",
    columnSelectBackgroundPosition:"233px -1px",
    leafDeselectColor:"#FFF",
    leafDeselectBackgroundColor:"#B71234",
    leafDeselectBackgroundPosition:"233px -1px",
    leafSelectBackgroundColor:"#B71234",
    leafSelectBackgroundImage:"url('/images/produit/nav_last_rouge.png')",
    leafSelectBackgroundPosition:"233px -1px",
    columnItemPadding:"0px 3px 0px 3px",
    columnScrollVelocity:200
  });
}

function initializeSpecsTable()
{
  /*//Tables des caractéristiques
  $(".tableDiv").each(function() {
      var Id = $(this).get(0).id;
      var maintbheight = 590;
      var maintbwidth = 737;
  $("#" + Id + " .FixedTables").fixedTable({
      width: maintbwidth,
      height: maintbheight,
      fixedColumns: 1,
      // header style
      classHeader: "fixedHead",
      // footer style
      //classFooter: "fixedFoot",
      // fixed column on the left
      classColumn: "fixedColumn",
      // the width of fixed column on the left
      fixedColumnWidth: 240,
      // table's parent div's id
      outerId: Id
      // tds' in content area default background color
      //Contentbackcolor: "#FFFFFF",
      // tds' in content area background color while hover.
      //Contenthovercolor: "#99CCFF",
      // tds' in fixed column default background color
      //fixedColumnbackcolor:"#187BAF",
      // tds' in fixed column background color while hover.
      // fixedColumnhovercolor:"#99CCFF"
    });
  });*/
  $(".fixedContainer tr").each(function(){
    $(this).children("td:even").css({backgroundColor:"#f2f3f4"})
      .mouseout(function(){
        $(this).css({backgroundColor:"#f2f3f4"});
      });
      $(this).children("td:odd").mouseout(function(){
        $(this).css({backgroundColor:"#fff"});
      })
  });
  $(".fixedContainer tr:first td").css({backgroundColor:"#666666"})
    .mouseout(function(){
      $(this).css({backgroundColor:"#666666"});
    });
  $(".fixedContainer .tab_subtitle").css({backgroundColor:"#bcc1c3"})
    .mouseout(function(){
      $(this).css({backgroundColor:"#bcc1c3"});
    });

  $(".fixedContainer .fixedTable td:not(.tab_subtitle)").mouseover(function(){
    $(this).css({backgroundColor:"#B8193B"});
  });

//  $('#espace_pro_toogle input, #espace_pro_toogle2 input, .espace_pro_widget input').keypress(function(e)
//  {
//    if(e.keyCode == 13)
//    {
//      $(this).closest('form').submit();
//    }
//  });

  $('.valid_login').click(function(e)
  {
    $(this).closest('form').submit();
    e.preventDefault();
  });
  
  var submitvalidlogin = function(e) {
    //e.preventDefault();
    
    var $form = $(this);
    
    // On vide la notice
    $form.find('.notice').empty();
    
    // Ne soumet pas le code club s'il n'a pas été affiché
    $form.find('.hidden_club:hidden').remove();
    
    // Si login
    if ($form.attr('action') === '/login') {
      $.ajax({
        url: $form.attr('action'),
        type: 'POST',
        dataType: 'json',
        data: $form.serialize(),
        success: function(data)
        {
          // Si logger, on le redirige sur la même page
          if (data.authenticated) {
            $.get('/sso/nocheck');
            var code_acces = $form.find('.hidden_club input').length ? $form.find('.hidden_club input').val() : null;
            document.location = '/sso/connect?frob=' + data.frob + '&redirect=' + location.pathname + '&code_acces=' + code_acces;
          // Notice si problème
          } else {
            $form.find('.notice').html('Identifiant ou mot de passe erroné');
          }
        }
      });
    // Si login-club
    } else {
      $.post($form.attr('action'), $form.serialize(), function(data) {
        if (data.hasClubs) {
          location.reload();
        // Notice si problème
        } else {
          $form.find('.notice').html('Code club erroné');
        }
      }, 'json');
    }
  };

  $('.valid_login').closest('form').submit(submitvalidlogin);
  $('.login_form').submit(submitvalidlogin);

  $('.fixedColumn').css({height:$('.fixedTable').height() + 'px'});
}



/*
 * Sélection de pages et de documents
 */

function cookie_split(name)
{
  var cookie_ary = Array();

  if (jQuery.cookie(name) != null)
  {
    var sep1 = new RegExp("[|]+", "g");
    var sep2 = new RegExp("[;]+", "g");

    var cookie_ary = jQuery.cookie(name).split(sep1);

    for (var i = 0; i < cookie_ary.length; i++)
    {
      cookie_ary[i] = cookie_ary[i].split(sep2);
    }
  }

  return cookie_ary;
}

function favorite_pages_split ()
{
  return cookie_split('favoritePages');
}

function favorite_docs_split ()
{
  return cookie_split('favoriteDocs');
}

function favorite_pages_build ()
{
  var cookie_ary = favorite_pages_split();
  var favorite_pages_content = '';

  for (var i = 0; i < cookie_ary.length; i++) {
    favorite_pages_content += '<li><a href="' + cookie_ary[i][2] + '" title="' + cookie_ary[i][1] + '"><strong>' + cookie_ary[i][1].replace(/\\'/g, "'") + '</strong></a>\n';
    favorite_pages_content += '<input class="checkbox" type="checkbox" id="' + i + '"/>\n';
    favorite_pages_content += '</li>\n';
  }

  $('#pages_favorites').empty().append(favorite_pages_content);
  updateSlider1();
}

function favorite_docs_build ()
{
  var cookie_ary = favorite_docs_split();
  var favorite_docs_content = '';

  for (var i = 0; i < cookie_ary.length; i++) {
    favorite_docs_content += '<li><img src="/images/content/icon_pdf.png" alt="" width="20" height="20" /><a href="' + cookie_ary[i][2] + '" title="' + cookie_ary[i][1] + '"><strong>' + cookie_ary[i][1].replace(/\\'/g, "'") + '</strong><span>' + cookie_ary[i][3] + ' | ' + cookie_ary[i][4] + '</span></a>\n';
    favorite_docs_content += '<input class="checkbox" type="checkbox" id="' + i + '"/>\n';
    favorite_docs_content += '</li>\n';
  }

  $('#documents_favorites').empty().append(favorite_docs_content);
  updateSlider2();
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
}

function favorite_pages_add (favorite_pages_url, favorite_pages_type, favorite_pages_text)
{
  var cookie_value = '';
  var cookie_ary = favorite_pages_split();
  var favorite_pages_elt_exist = false;

  if (cookie_ary.length > 0) {
    for (var i = 0; i < cookie_ary.length; i++) {
      if (cookie_ary[i][0] == favorite_pages_type && cookie_ary[i][1] == favorite_pages_text && cookie_ary[i][2] == favorite_pages_url) {
        alert('Déjà enregistré dans ma sélection');
        favorite_pages_elt_exist = true;
        break;
      }
    }

    cookie_value = jQuery.cookie('favoritePages') + '|'
  }

  if (!favorite_pages_elt_exist) {
    cookie_value += favorite_pages_type + ';' + favorite_pages_text + ';' + favorite_pages_url;
    jQuery.cookie('favoritePages', cookie_value, {path: '/'});

    $('#pages_favorites').append($(document.createElement('li')).append('<a href="' + favorite_pages_url + '" title=""><strong>' + favorite_pages_text + '</strong></a><input class="checkbox" type="checkbox" id="' + $('#pages_favorites li').length + '"/>'));
    updateSlider1();
  }

  if(typeof(toogloadconsole) == 'undefined')
  {
    $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
  }

  return false;
}

function favorite_pages_delete (indexes, save)
{
  indexes.sort();
  var cookie_ary = favorite_pages_split();
  var cookie_value = null;
  var tmp_ary = Array();
  var i;

  for(i = indexes.length - 1; i >= 0; i--)
  {
    cookie_ary.remove(i);
  }

  if (cookie_ary.length) {
    for (var i = 0; i < cookie_ary.length; i++) {
      tmp_ary[i] = cookie_ary[i].join(";");
    }
    cookie_value = tmp_ary.join("|");
  }

  jQuery.cookie('favoritePages', cookie_value, {path: '/'});

  if(save && typeof(toogloadconsole) == 'undefined')
  {
    $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
  }
}

function favorite_docs_add (favorite_docs_url, favorite_docs_type, favorite_docs_text, format, taille)
{
  var cookie_value = '';
  var cookie_ary = favorite_docs_split();
  var favorite_docs_elt_exist = false;

  if (cookie_ary.length > 0) {
    for (var i = 0; i < cookie_ary.length; i++) {
      if (cookie_ary[i][0] == favorite_docs_type && cookie_ary[i][1] == favorite_docs_text && cookie_ary[i][2] == favorite_docs_url) {
        alert('Déjà enregistré dans ma sélection');
        favorite_docs_elt_exist = true;
        break;
      }
    }

    cookie_value = jQuery.cookie('favoriteDocs') + '|'
  }

  if (!favorite_docs_elt_exist) {
    cookie_value += favorite_docs_type + ';' + favorite_docs_text + ';' + favorite_docs_url + ';' + format + ';' + taille;
    jQuery.cookie('favoriteDocs', cookie_value, {path: '/'});

    $('#documents_favorites').append($(document.createElement('li')).append('<img width="20" height="20" alt="" src="/images/content/icon_pdf.png"/><a href="' + favorite_docs_url + '" title="' + (favorite_docs_text ? favorite_docs_text : 'Document sans titre') + '"><strong>' + (favorite_docs_text ? favorite_docs_text : 'Document sans titre') + '</strong><span>' + format + ' | ' + taille + '</a><input class="checkbox" type="checkbox" id="' + $('#documents_favorites li').length + '"/>'));
    updateSlider2();
  }

  if(typeof(toogloadconsole) == 'undefined')
  {
    $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
  }

  return false;
}

function favorite_docs_delete (indexes, save) {
  var cookie_ary = favorite_docs_split();
  var cookie_value = null;
  var tmp_ary = Array();

  for(i = indexes.length - 1; i >= 0; i--)
  {
    cookie_ary.remove(i);
  }

  if (cookie_ary.length) {
    for (var i = 0; i < cookie_ary.length; i++) {
      tmp_ary[i] = cookie_ary[i].join(";");
    }
    cookie_value = tmp_ary.join("|");
  }

  jQuery.cookie('favoriteDocs', cookie_value, {path: '/'});

  if(save && typeof(toogloadconsole) == 'undefined')
  {
    $.post('/save-selection', {'pages': jQuery.cookie('favoritePages'), 'documents': jQuery.cookie('favoriteDocs')});
  }
}



/**
 * @name EstSiretValide
 *
 * @param Le code SIRET dont on veut vérifier la validité.
 *
 * @return Un booléen qui vaut 'true' si le code SIRET passé en
 * paramètre est valide, false sinon.
 */
function valideSiret(siret)
{
  var estValide;
  if ( (siret.length != 14) || (isNaN(siret)) )
    estValide = false;
  else {
    // Donc le SIRET est un numérique à 14 chiffres
    // Les 9 premiers chiffres sont ceux du SIREN (ou RCS), les 4 suivants
    // correspondent au numéro d'établissement
    // et enfin le dernier chiffre est une clef de LUHN.
    var somme = 0;
    var tmp;
    for (var cpt = 0; cpt<siret.length; cpt++) {
      if ((cpt % 2) == 0) { // Les positions impaires : 1er, 3è, 5è, etc...
        tmp = siret.charAt(cpt) * 2; // On le multiplie par 2
        if (tmp > 9)
          tmp -= 9; // Si le résultat est supérieur à 9, on lui soustrait 9
      }
      else
        tmp = siret.charAt(cpt);
      somme += parseInt(tmp);
    }
    if ((somme % 10) == 0)
      estValide = true; // Si la somme est un multiple de 10 alors le SIRET est valide
    else
      estValide = false;
  }
  return estValide;
}

/**
 * Modifications prettyphoto liensswf POPUP
 */
jQuery(document).ready(function()
{
  if(jQuery.isFunction(jQuery.fn.prettyPhoto)) {
    jQuery("a[href$='.swf']").each(function() {
      jQuery(this).attr('rel', 'prettyPhoto').attr('title', '').attr('target', '');
       jQuery(this).attr('href', jQuery(this).attr('href') + '?width=1024&height=768');
       jQuery(this).addClass('prettyFlash');
     });
    jQuery("a.prettyFlash").prettyPhoto({theme: 'facebook', allowresize: false});

    jQuery("a[href$='.iframe']").each(function() {
      jQuery(this).attr('rel', 'prettyPhoto[iframes]').attr('title', '').attr('target', '');
      jQuery(this).attr('href', jQuery(this).attr('href').replace('.iframe', '.html') + '?iframe=true&width=1024&height=768');
    });

    jQuery("a[href$='.popin']").each(function() {
      var href = jQuery(this).attr('href');
      jQuery(this).attr('rel', 'prettyPhoto[iframes]').attr('title', '').attr('target', '');
      jQuery(this).attr('href', href.substr(0, href.length - '.popin'.length) + '?iframe=true&width=960&height=600');
    });

    jQuery("a[rel^='prettyPhoto[iframes]']").prettyPhoto({theme: 'facebook', allowresize: false});
  }
});

/**
 * Gestion des abonnement de documents
 */
AbonnementDocument = function ()
{
  /**
   * Lance un appel ajax pour enregistrer la souscription ou la désinscription à l'abonnement document
   * @param checkbox
   * @return boolean
   */
  this.set = function (checkbox)
  {
    $.post('/set-abonnement', {active: jQuery(checkbox).attr('checked')} , function(data)
        {
          return true;
        });
  }
}
abonnementDocument = new AbonnementDocument();
