
jQuery(document).ready(function () {
  /* Déclarations des variables */
  var header = $(".header");
  var icon_menu = $(".icon_menu");
  var menu = $(".menu");
  var detail_menu = $(".detail_menu");
  var page_content = $(".page_content");
  var sidebar = $(".detail_content_sidebar");
  var last_post_anchor = $(".last_post_anchor");
  var btn = $(".menu_theme_button");
  var sous_menu = $(".sous_menu_theme");
  var closeBtn = $(".close_sous_menu_theme");
  var content_text = $(".content_text");
  var last_post_anchor_btn = $(".last_post_anchor_btn");
  var last_posts_detail_page = $(".last_posts_detail_page");
  var share = $(".share");
  var socials_block = $(".socials_block");
  var sidebarHeight = 0;
  var tags_wrapper = $('.detail_tags_block')[0];
  var more_tags = $('.detail_tags_wrapper .more_tags');
  var tags_wrapper_height = $('.detail_tags_block').height();
  var menu_theme_scrollbar = $('.sous_menu_theme_scroll');

  /* Clic sur le menu principal = ajout classe open = affichage du détail du menu */
  icon_menu.click(function () {
    if (detail_menu.is(".open")) {
      detail_menu.removeClass("open");
      menu.removeClass("open");
      detail_menu.fadeOut("fast");
    }
    else {
      detail_menu.addClass("open");
      menu.addClass("open");
      detail_menu.fadeIn("fast");
    }
    return false;
  });

  if (!$('section.pub').html()) {
    header.removeClass('hasPub');
  }

  /* On ajoute une classe "scrolled" lorsque la page est scrollée,
   on l'enlève sinon */
  $(window).scroll(function () {
    var windowpos = window.pageYOffset;

    if (windowpos > 50) {
      header.addClass("scrolled");
      header.removeClass("hasPub");
      page_content.addClass("scrolled");
    } else {
      if ($('section.pub').html()) {
        header.addClass("hasPub");
      }
      header.removeClass("scrolled");
      page_content.removeClass("scrolled");
    }
  });

  /* On regarde si l'utilisateur est en train de scroller vers le haut
   Si oui, on affiche l'encart des derniers articles publiés */
  var lastScrollTop = 0, delta = 2;

  $(window).scroll(function (event) {
    var st = window.pageYOffset;

    if (Math.abs(lastScrollTop - st) <= delta)
      return;

    if (st < sidebar.height()) {
      last_post_anchor.fadeOut("fast");
    } else {
      if (st > lastScrollTop) {
        // downscroll code
        if (last_post_anchor.is(':visible'))
          last_post_anchor.fadeOut("fast");
      } else {
        // upscroll code
        if (!last_post_anchor.is(':visible'))
          last_post_anchor.fadeIn("fast");
      }
    }

    lastScrollTop = st;
  });

  /* On permet de remonter en haut de page au clic sur la flèche en bas à droite */
  $(".scroll_top_btn").click(function () {
    last_post_anchor.css("visibility", "hidden");
    $("html, body").animate({scrollTop: 0}, "slow");
    return false;
  });

  /* On affiche/cache l'encart détaillé du "menu du thème", au clic sur le bouton "menu du thème */
  btn.click(function () {
    if (btn.is(".active")) {
      btn.removeClass("active");
      sidebar.removeClass("active");
      sous_menu.fadeOut("slow");
      sidebarHeight = 0;
    }
    else {
      btn.addClass("active");
      sidebar.addClass("active");
      sous_menu.fadeIn("slow");
      sidebarHeight = sidebar.height();
    }
    return false;
  });

  /* On cache le menu du thème au clic sur le bouton close du menu */
  closeBtn.click(function () {
    btn.removeClass("active");
    sous_menu.fadeOut("slow");
    return false;
  });

  /* Quand on clique sur l'ancre "Derniers articles publiés" */
  last_post_anchor_btn.click(function () {
    var position = last_posts_detail_page.position();
    var scrolly = position.top;
    window.scrollTo(0, scrolly);
  });

  /* Si on clique sur le bouton "Share", on ajoute une classe open pour faire afficher les réseaux sociaux en dessous */
  share.click(function () {
    if (socials_block.is(".open")) {
      socials_block.removeClass("open");
    }
    else {
      socials_block.addClass("open");
    }
    return false;
  });

  // Boutons de dissémination
  $('.detail_content_sidebar .socials .facebook').click(fbs_click);
  $('.detail_content_sidebar .socials .twitter').click(twitter_click);

  //Barre d'actus
  var barreActus = $("#barre-actus");
  if (barreActus.length > 0) {
    setInterval(function () {
      $("#barre-actus ul").animate({marginLeft: -990}, 1200, function () {
        $(this)
          .css({marginLeft: 0})
          .find("li:last")
          .after($(this).find("li:first"));
      });
    }, 8000);
  }

  // Menu responsive
  $(
    "#menuGeneral > ul > li > span, #menuRubriques > ul > li > span"
  ).click(function () {
    $("#menuGeneral > ul > li, #menuRubriques > ul > li")
      .not($(this).parent())
      .removeClass("actif");
    $(this).parent().toggleClass("actif");
  });

  // Fourchette de dates
  $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['fr']));

  if (typeof mes_presets !== 'undefined') {
    var conf = {
      initialText      : 'Sélectionnez une période',
      presetRanges     : mes_presets,
      dateFormat       : 'dd.mm.yy',
      applyButtonText  : 'Appliquer',
      clearButtonText  : 'Effacer',
      cancelButtonText : 'Annuler',
      datepickerOptions: {
        numberOfMonths: 2
      }
    };

    $("#duplo-filter-date").datepicker($.datepicker.regional["fr"]);
    $("#duplo-filter-date").daterangepicker(conf);
  }

  $("[data-fancybox].mailto").fancybox({
    iframe    : {
      css: {
        width: '430'
      }
    },
    beforeLoad: function () {
      this.src = insertParamInUrl($('.social-link.mailto').data('src'), 'tx_fluidrecommendation_pi1[title]', document.title.split('-')[0], 1);
    },
    afterShow : function (instance, slide) {
      slide.$slide.find('.pageTitle').html(slide.opts.$orig.data('title'));
    }
  });

  $('.detail_tags_wrapper .more_tags').click(function () {
    $(this).toggleClass('less');

    if ($(this).hasClass('less')) {
      tags_wrapper_height = $('.detail_tags_block').height();
      $(this).html('-');
      $('.detail_tags_block').animate({height: tags_wrapper.scrollHeight + 'px'}, 500).addClass('unfold');
    } else {
      $(this).html('+');
      $('.detail_tags_block').animate({height: tags_wrapper_height + 'px'}, 500, function(){
        $(this).height('auto');
        more_tags.show();
        $(this).removeClass('unfold');
      });
    }
  });

  $(window).load(function () {
    resizeSreen(content_text, sidebar, tags_wrapper, more_tags);

    /* Permet de faire disparaitre et réaparaitres des réseaux sociaux */
    $(window).scroll(function (event) {
      resizeSreen(content_text, sidebar, tags_wrapper, more_tags);
    });

    /* Responsive Iframe */

    // Find all iframes
    var $iframes = $(".detail_part iframe, .detail_part object");

    // Find &#x26; save the aspect ratio for all iframes
    $iframes.each(function () {
      var height = this.height ? this.height : $(this).css('height');
      var width = this.width ? this.width : $(this).css('width');

      if (width && height && width.slice(-1) !== '%') {
        $(this).attr("data-ratio", height / width)
               // Remove the hardcoded width &#x26; height attributes
               .removeAttr("width")
               .removeAttr("height")
               .css('max-width', width + 'px')
               .css('max-height', height + 'px');
      }
    });

    // Resize the iframes when the window is resized
    $(window).resize(function () {
      $iframes.each(function () {
        // Get the parent container&#x27;s width
        var width = $(this).parent().width();

        if ($(this).data("ratio")) {
          $(this).width(width)
                 .height(width * $(this).data("ratio"));
        }
      });
      // Resize to fix all iframes on page load.
    }).resize();

    if (menu_theme_scrollbar.html()) {
      menu_theme_scrollbar.scrollbar();
    }
  });

  /* Actions au resize de la page */
  $(window).resize(function () {
    resizeSreen(content_text, sidebar, tags_wrapper, more_tags);
  });
});

function resizeSreen(content_text, sidebar, tags_wrapper, more_tags) {
  if (sidebar.html()) {
    var h = content_text.height() - 100;

    var stBis = window.pageYOffset;
    var isVisibleSb = !sidebar.hasClass('hide');
    var isActiveSb = sidebar.hasClass('active');

    if (isActiveSb) {
      stBis -= sidebar.height();
    }

    if (stBis >= h && isVisibleSb) {
      sidebar.addClass('hide');
    } else if (stBis < h && !isVisibleSb) {
      sidebar.removeClass('hide');
    }
  }

  if (tags_wrapper) {

    /* Clic sur le bouton more pour les tags */
    if (tags_wrapper && tags_wrapper.scrollHeight > tags_wrapper.offsetHeight + 2) {
      more_tags.show();
    } else {
      if (!more_tags.hasClass('less')) {
        more_tags.hide();
      }
    }
  }
}

function fbs_click() {
  window.open(
    "https://www.facebook.com/sharer.php?u=" +
    encodeURIComponent(location.href) +
    "&t=" +
    encodeURIComponent(document.title),
    "sharer",
    "toolbar=0,status=0,width=626,height=436"
  );
  return false;
}

function twitter_click() {
  var u = location.href;
  window.open(
    "https://twitter.com/intent/tweet?related=touteleurope&via=touteleurope&original_referer=" +
    encodeURIComponent(u) +
    "&source=tweetbutton&text=" +
    encodeURIComponent(document.title) +
    ":&url=" +
    encodeURIComponent(u),
    "sharer",
    "toolbar=0,status=0,width=626,height=436"
  );
  return false;
}

function insertParamInUrl(url, key, value, position) {
  key = encodeURI(key);
  value = encodeURI(value);

  var kvp = url.split('&');

  var i = kvp.length;
  var x;
  while (i--) {
    x = kvp[i].split('=');

    if (x[0] == key) {
      x[1] = value;
      kvp[i] = x.join('=');
      break;
    }
  }

  if (i < 0) {
    kvp.splice(position, 0, [key, value].join('='));
  }

  //this will reload the page, it's likely better to store this until finished
  url = kvp.join('&');

  return url;
}
