/**
 * Created by damien on 10/02/2017.
 */
const util = require("./util.js")




$(document).ready(function() {


/* Fix A11Y suite audit AIX */

        setTimeout(function() {
            $('.autocomplete-suggestions').each(function() {
                $(this).attr('aria-hidden', 'true');
                $(this).attr('role', 'listbox');
            });
            $('.autocomplete-suggestions > div').each(function() {
                $(this).attr('role', 'option');
            });
        }, 300);

    $('#ancre-hautpage').attr('tabindex', '-1');

    $('#back-top').on('click', function() {
        $('#ancre-hautpage').focus();
    });


    $('header').attr('role', 'banner');
    $('.skip-links').attr('role', 'navigation');

    $('main').attr('role', 'main');
    $('main').attr('tabindex', '-1');
    $('.bs-docs-sidebar').attr('role', 'navigation');

    $('footer').attr('role', 'contentinfo');
    $('footer .sidebar ul.nav').attr('role', 'navigation');

    $('.navbar-toggler.toggle-left').attr('data-target', '#navbarsleft');
    $('.navbar-toggler.toggle-left').attr('aria-controls', 'navbarsleft');
    $('.navbar-toggler.toggle-left').attr('aria-expanded', 'false');

    $('.navbar-toggler.toggle-left').on('click', function() {
        $('.navbar-toggler.toggle-right').attr('aria-expanded', 'false');
        $(this).attr('aria-expanded', function (i, attr) {
            return attr == 'true' ? 'false' : 'true'
        });
    });

    $('.navbar-toggler.toggle-right').attr('data-target', '#navbarsright');
    $('.navbar-toggler.toggle-right').attr('aria-controls', 'navbarsright');
    $('.navbar-toggler.toggle-right').attr('aria-expanded', 'false');

    $('.navbar-toggler.toggle-right').on('click', function() {
        $('.navbar-toggler.toggle-left').attr('aria-expanded', 'false');
        $(this).attr('aria-expanded', function (i, attr) {
            return attr == 'true' ? 'false' : 'true'
        });
    });


    $('[data-module="diaporama"] .carousel-item a').addClass('stretched-link');

    $('i[class^="picto-"]').attr('aria-hidden', 'true');
    $('span[class^="picto-"]').each(function() {
      // Vérifier s'il n'y a pas de span enfants
      if ($(this).find('span').length === 0) {
        // Ajouter l'attribut aria-hidden
        $(this).attr('aria-hidden', 'true');
      }
    });
    $('details').each(function() {
      var summary = $(this).find('summary');
      var content = $(this).find(':not(summary)');

      summary.attr('aria-expanded', $(this).prop('open'));

      if (!$(this).prop('open')) {
        content.attr('aria-hidden', 'true');
      }


      summary.on('click', function() {
        var isOpen = $(this).parent().prop('open');

        $(this).attr('aria-expanded', !isOpen);
        content.attr('aria-hidden', isOpen);
      });
    });

      $('.mce-toc > ul').wrap( "<nav role='navigation' aria-label='Sommaire'></nav>" );

/* -- A TESTER SUR AIX -- */
/*
    $('.trigger-line').attr('aria-pressed', 'false');
    $('.trigger-line').on('click', function() {
        $(this).attr('aria-pressed', function (i, attr) {
            return attr == 'true' ? 'false' : 'true'
        });
    });*/
    $('#infos.infotrafic').attr('role', 'group');
    $('#infos.infotrafic').attr('aria-labelledby', 'Choisir une ligne');







/* menu slide left */

    util.updateTablesAttributes();
    $('.sidebar-nav .navbar-toggle.left-menu').on('click', function() {
        $navMenuCont = $($(this).data('target'));
        $navMenuCont.animate({
            'width': 'toggle'
        }, 350);
        $(".load").addClass("importantload");
        $("body").addClass("noscroll");
    });

    $(".load").click(function(event) {
        $(".sidebar-nav .navbar-toggle").trigger("click");
        $(".load").removeClass("importantload");
        $("body").removeClass("noscroll");
    });

    $(".removeUploadFileSelected").on("click", function(e) {
        var idInputFile = $(e.target).attr("data-filetargetId");
        $("#" + idInputFile).val("");
    })

    $('.dropdown-toggle').dropdown()
    $('.datepicker').datepicker({
        language: 'fr'
    });


    $(".head_menu").hover(
      function () {
        $(this).addClass('hover'),
        $(this).attr('aria-expanded', 'true');
      },
      function () {
        $(this).removeClass('hover'),
        $(this).attr('aria-expanded', 'false');
      }
      );

    $(".head_menu").focus(
      function () {
        $(this).addClass('focus'),
        $(this).attr('aria-expanded', 'true');
      },
      function () {
        $(this).removeClass('focus'),
        $(this).attr('aria-expanded', 'false');
      }
      );


    $(".sub-nav.accessible-megamenu-panel").removeAttr('aria-expanded');
    if($('.sub-nav.accessible-megamenu-panel').hasClass('open')){
            $(this).attr('title', $e.attr('data-original-title') || '');
        }



/* Gestion des tooltips */

    /*$('[data-toggle="tooltip"]').tooltip()

    $('[target="_blank"]').tooltip({
            container: 'body',
            placement:'top'

    });
*/




/* fix accessibilité title & data-original-title */

    function tooltiprgaa() { 
        if($('[data-original-title]').length >0){
            $('[data-original-title]').each(function(index, e){
                var $e = $(e)
                $e.attr('title', $e.attr('data-original-title') || '');
            });
        }
        if($('[title]').length >0){
            $('[title]').each(function(index, e){
                var $e = $(e)
                $e.attr('data-original-title', $e.attr('title') || '');
            });
        }
    }
tooltiprgaa();


/* fix accessibilité retrait title vide */

    function emptytitle() { 
            if($('a[title]')){
                $('a[title]').each(function(index, e){
                    var $e = $(e)
                    if($e.attr("title").length==0)
                        $e.removeAttr("title");
                        $e.removeAttr("data-original-title");
                });
            }
        }
    emptytitle();

/* fix accessibilité auto title _blank */


    function blanktitle() { 
            if($('[target="_blank"]:not([title])')){
                $('[target="_blank"]:not([title])').each(function(index, e){
                    var $e = $(e);
                    var $contenulink = $e.text(); 
                    var $newwindow = ' (nouvelle fenêtre)'
                    $e.attr('title',$contenulink + $newwindow);
                    $e.attr('data-original-title',$contenulink + $newwindow);
                });
            }
        }
    blanktitle();


    $('[data-toggle="tooltip"]').click(function() {
        $(this).tooltip('hide');
    });
    $('.fontAAA').click(function() {
        $('main').toggleClass('fontAAA');
        $('.fontAAA.augmente').toggleClass('block');
        $('.fontAAA.reduce').toggleClass('block');
        $(this).tooltip('hide');
    });
    $('.fontAAA.augmente').tooltip({
        title: "Augmenter la taille du texte",
        placement: "bottom"
    });
    $('.fontAAA.reduce').tooltip({
        title: "Réduire la taille du texte",
        placement: "bottom"
    });

    $('.fontAAA.augmente').on('click', function() {
        $('.fontAAA.reduce').focus();
    });
    $('.fontAAA.reduce').on('click', function() {
        $('.fontAAA.augmente').focus();
    });
    /* Fin de gestion des tooltips ---------------------- */


$('#contenu_page p').each(function(i){          // For each paragraph
    if ( ($(this).find('img[alt=""]').length) &&     // If there's an image
         (!$.trim($(this).text()).length))   // and there's no text
    {
        $(this).contents().unwrap(); // supprimer balise p If there's just one image
    }
});

    $('.btncontrast').click(function() {
        $('.warp').toggleClass('contrast');
    });
    $('.print').click(function() {
        window.print();
    });
    if($().accessibleMegaMenu != undefined){
        $("nav:first").accessibleMegaMenu({
            uuidPrefix: "accessible-megamenu",
            menuClass: 'accessible-megamenu',
            topNavItemClass: 'accessible-megamenu-top-nav-item',
            panelClass: 'accessible-megamenu-panel',
            panelGroupClass: 'accessible-megamenu-panel-group',
            hoverClass: 'hover',
            focusClass: 'focus',
            openClass: 'open'
        });
    }


    $('.js-accessible-megamenu > li:last-child > form').removeAttr('aria-hidden aria-expanded');


    if ($('#back-top').length == 1) {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 300) $('#back-top').addClass("visible");
            else $('#back-top').removeClass("visible");
        });
        $('#back-top').click(function() {
            $('#back-top').tooltip('hide')
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    }


$('img:not([alt])').attr('alt', '');
$('img[alt=""]').attr('aria-hidden', 'true');

$('table thead tr th').attr('role', 'columnheader')
$('table tbody tr th:first-child').attr('role', 'rowheader')

$('figure').each(function( index ) {
  if($(this).find("figcaption").length > 0){
    let txt = $(this).find("figcaption").text().trim()
    txt = txt.replace(/[\n\r]+/g, ' ');
    
    $(this).attr("aria-label", txt)
  }

});




    /* Gestion des liens sans cache */

function randnumber() {
  return Math.floor(Math.random()*2460)+10;
}
$("a.nocache").each(function() {
   var $this = $(this);
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '?rand='+randnumber());
});


    /* iframe responsive via tiny */

$('p:has(iframe[src*=youtube])').addClass('has_iframe');
$('p:has(iframe[src*=dailymotion])').addClass('has_iframe');
$('p:has(iframe[src*=vimeo])').addClass('has_iframe'); 

$('p:has(iframe[src*=calameo])').addClass('has_iframe4-3'); 
$('p:has(iframe[src*=google])').addClass('has_iframe4-3');  

$('iframe').removeAttr('width height frameborder');
$('.page main iframe[src*=youtube]').removeAttr('width height frameborder');
$('iframe[src*=youtube]').attr('title','Contenu vidéo provenant de Youtube');

$('.page main iframe[src*=dailymotion]').removeAttr('width height frameborder');
$('iframe[src*=dailymotion]').attr('title','Contenu vidéo provenant de Dailymotion');

$('.page main iframe[src*=vimeo]').removeAttr('width height frameborder');
$('iframe[src*=vimeo]').attr('title','Contenu vidéo provenant de Vimeo');

$('.page main iframe[src*=calameo]').removeAttr('width height frameborder');
$('iframe[src*=calameo]').attr('title','Contenu en provenance de Calameo');

$('.page main iframe[src*=google]').removeAttr('width height frameborder');
$('iframe[src*=google]').attr('title','Contenu en provenance de Google');

$('iframe[src*=recaptcha]').attr('title','ReCaptcha Google');

$('figure:has(img)').attr('role','group');

$('table:not(:has(caption))').prepend('<caption class="sr-only">Tableau</caption>');

$('[target="_blank"]').attr('rel','noopener noreferrer');

setTimeout(function(){
  $('iframe[class*=goog-te-banner-frame]').attr('title','Widget de traduction Google');
  $('iframe[class*=twitter]').attr({
        "aria-hidden":true,
        "tabindex":-1,
    });
  $('iframe[class*=twitter]').removeAttr('frameborder');
},2000)

    /* patch JS pour rendre accessible accordion */
    $(".accordion-toggle").each(function() { // loop through all matched elements
        $(this).removeAttr("tabindex");
    });
    if ($('#prehomeAlert').length > 0) {
        $('#prehomeAlert').modal('show');
        $('#closePrehomeDef').on("click", function(e) {
            var url = $(e.target).attr('data-url')
            $.get(url)
        });
        $("#prehomeAlert").on('hidden.bs.modal', function (e) {
            $("#prehomeAlert iframe").attr("src", "");
        });
    }
    if ($("#Choix_Langue").length > 0) {
        $("#Choix_Langue").on("change", function() {
            var langChosen = $(this).find(":selected").val()
            document.location.href = "/" + langChosen + "/"
        })
    }

    /* Bouton play pause carousel */
    
    $('.carousel a').focus(function() {
        let $carousel = $(this).closest(".carousel")
        $carousel.carousel('pause');
    });

    var html = "";
    html += "";
    
$( ".carousel" ).each(function( index ) {

  if($(this).find(".carousel-inner").children().length > 1){
    /*$(this).append(html);*/
    }else{
    $(this).find('.carouselButtons').addClass('none');
    $(this).find('.carousel-indicators').addClass('none');
    $(this).find('.carousel-control').addClass('none');
  }
});

    $('.carousel .playButton').click(function () {
        let $carousel = $(this).closest(".carousel")

        $carousel.carousel('cycle');
        $carousel.removeClass('stopcycle');
        $('.playButton',$carousel).toggleClass('none');
        $('.pauseButton',$carousel).toggleClass('none');
        $('.pauseButton',$carousel).focus();
    });

    $('.carousel .pauseButton').click(function () {
        let $carousel = $(this).closest(".carousel")
        
        $carousel.carousel('pause');
        $carousel.addClass('stopcycle');
        $('.playButton',$carousel).toggleClass('none');
        $('.pauseButton',$carousel).toggleClass('none');
        $('.playButton',$carousel).focus();
    });

    $('.pauseButton').tooltip();
    $('.playButton').tooltip();


        $('.nav > li.nav-item').hover(
            function(){
                $(this).find('.sub-nav').addClass("open");
            }, 
            function () {
                $(this).find('.sub-nav').removeClass("open");
            });



});


    /* The manually determine when an item should show and hide a tool tip. */
    $('[data-toggle="tooltip"]')
      .attr("tabindex", 0)
      .tooltip({ trigger: "manual" })
      .mouseenter(event => {
         let cible = $(event.target).closest('a, .btn')
         console.log(cible);
        $(cible).tooltip("show");
        $(".tooltip").on("mouseleave", function() {
          $(cible).tooltip("hide");
        });
      })
      .mouseleave(event => {
        let cible = $(event.target).closest('a, .btn')
        setTimeout(() => {
        if (!$(".tooltip:hover").length) $(cible).tooltip("hide");
        }, 100);
      })
      .focus(event => {
        let cible = $(event.target).closest('a, .btn')
        $(cible).tooltip("show");
      })
      .blur(event => {
        let cible = $(event.target).closest('a, .btn')
        $(cible).tooltip("hide");
      });

    /* Listen for the "escape key" so tool tips can easily be hidden */
    $("body").keydown(event => {
      if (event.keyCode === 27) {
        $('[data-toggle="tooltip"]').tooltip("hide");
        $('.sub-nav.accessible-megamenu-panel').removeClass("open");
      }
    });



/**

 * uisearch.js v1.0.0

 * http://www.codrops.com

 *

 * Licensed under the MIT license.

 * http://www.opensource.org/licenses/mit-license.php

 *

 * Copyright 2013, Codrops

 * http://www.codrops.com

 */
;
(function(window) {
    'use strict';
    // EventListener | @jon_neal | //github.com/jonathantneal/EventListener
    !window.addEventListener && window.Element && (function() {
        function addToPrototype(name, method) {
            Window.prototype[name] = HTMLDocument.prototype[name] = Element.prototype[name] = method;
        }
        var registry = [];
        addToPrototype("addEventListener", function(type, listener) {
            var target = this;
            registry.unshift({
                __listener: function(event) {
                    event.currentTarget = target;
                    event.pageX = event.clientX + document.documentElement.scrollLeft;
                    event.pageY = event.clientY + document.documentElement.scrollTop;
                    event.preventDefault = function() {
                        event.returnValue = false
                    };
                    event.relatedTarget = event.fromElement || null;
                    event.stopPropagation = function() {
                        event.cancelBubble = true
                    };
                    event.relatedTarget = event.fromElement || null;
                    event.target = event.srcElement || target;
                    event.timeStamp = +new Date;
                    listener.call(target, event);
                },
                listener: listener,
                target: target,
                type: type
            });
            this.attachEvent("on" + type, registry[0].__listener);
        });
        addToPrototype("removeEventListener", function(type, listener) {
            for (var index = 0, length = registry.length; index < length; ++index) {
                if (registry[index].target == this && registry[index].type == type && registry[index].listener == listener) {
                    return this.detachEvent("on" + type, registry.splice(index, 1)[0].__listener);
                }
            }
        });
        addToPrototype("dispatchEvent", function(eventObject) {
            try {
                return this.fireEvent("on" + eventObject.type, eventObject);
            } catch (error) {
                for (var index = 0, length = registry.length; index < length; ++index) {
                    if (registry[index].target == this && registry[index].type == eventObject.type) {
                        registry[index].call(this, eventObject);
                    }
                }
            }
        });
    })();
    // http://stackoverflow.com/a/11381730/989439
    function mobilecheck() {
        var check = false;
        (function(a) {
            if (/(android|ipad|playbook|silk|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true
        })(navigator.userAgent || navigator.vendor || window.opera);
        return check;
    }
    // http://www.jonathantneal.com/blog/polyfills-and-prototypes/
    !String.prototype.trim && (String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    });

    function UISearch(el, options) {
        this.el = el;
        this.inputEl = el.querySelector('form > input.sb-search-input');
        this._initEvents();
    }
    UISearch.prototype = {
        _initEvents: function() {
            var self = this,
                initSearchFn = function(ev) {
                    ev.stopPropagation();
                    // trim its value
                    self.inputEl.value = self.inputEl.value.trim();
                    if (!classie.has(self.el, 'sb-search-open')) { // open it
                        ev.preventDefault();
                        self.open();
                    } else if (classie.has(self.el, 'sb-search-open') && /^\s*$/.test(self.inputEl.value)) { // close it
                        ev.preventDefault();
                        self.close();
                    } else {
                        document.formrech.submit()
                    }
                }
            this.el.addEventListener('click', initSearchFn);
            this.el.addEventListener('touchstart', initSearchFn);
            this.inputEl.addEventListener('click', function(ev) {
                ev.stopPropagation();
            });
            this.inputEl.addEventListener('touchstart', function(ev) {
                ev.stopPropagation();
            });
        },
        open: function() {
            var self = this;
            classie.add(this.el, 'sb-search-open');
            // focus the input
            if (!mobilecheck()) {
                this.inputEl.focus();
            }
            // close the search input if body is clicked
            var bodyFn = function(ev) {
                self.close();
                this.removeEventListener('click', bodyFn);
                this.removeEventListener('touchstart', bodyFn);
            };
            document.addEventListener('click', bodyFn);
            document.addEventListener('touchstart', bodyFn);
        },
        close: function() {
            this.inputEl.blur();
            classie.remove(this.el, 'sb-search-open');
        }
    }
    // add to global namespace
    window.UISearch = UISearch;
})(window);
