// Change layout orders according to the device resolution 
function layouting() {

    if ($('body').data('page') === 'homepage') {
        if (window.matchMedia('(min-width: 992px)').matches) {
            $("#nav").detach().insertBefore('#main-content');
            $("#access").detach().insertBefore('#news');
            $("#promo").detach().insertAfter('#events');
            $("#procedures").detach().appendTo('#header');
            /*$("#right_bar").detach().insertAfter('#webtv');*/
        } else if (window.matchMedia('(max-width: 991px)').matches) {
            $("#nav").detach().insertAfter('#main-content');
            $("#access").detach().insertAfter('#webtv');
            $("#procedures").detach().insertAfter('#navigation');
            $("#right_bar").detach().insertAfter('#access');
            $("#promo").detach().insertAfter('#right_bar');
            if (window.matchMedia('(min-width: 481px)').matches) {
                $("#promo").detach().insertAfter('#right_bar');
            }
        }
    } else {
        if (window.matchMedia('(min-width: 992px)').matches) {
            $("#nav").detach().insertBefore('#main-content');
            $("#access").show();
            $("#events").detach().appendTo('#col-right > .row');
            $("#promo").detach().insertAfter('#events');
            $("#procedures").detach().appendTo('#header');
            if (!$('body').hasClass('theme_33212')) {
                $("#right_bar").detach().insertAfter('#promo');

            }
        } else if (window.matchMedia('(max-width: 991px)').matches) {
            $("#nav").detach().insertAfter('#main-content');
            $("#procedures").detach().insertAfter('#navigation');

            $("#events").detach().insertAfter('#main');
            $("#access").hide();
            $("#access").detach().insertAfter('#events');
            $("#right_bar").detach().insertAfter('#access');
            $("#promo").detach().insertAfter('#right_bar');
            if (window.matchMedia('(min-width: 481px)').matches) {
                $("#promo").detach().insertAfter('#right_bar');
            }
        }
    }
}

$(function() {

    $(document).on('click', '.yamm .dropdown-menu', function(e) {
      e.stopPropagation()
      // alert('click');
    });
    /*var hauteurSite = (window.innerHeight);*/
    /*console.log(haut);*/

    layouting();

    $(window).resize(function(event) {
        layouting();
    });

    // Add class "active" on collapse trigger when they are open
    $('[data-toggle="collapse"]').on('click', function() {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    });

    // Background image parallax only if min-width > 768px
    // if ( window.matchMedia('(min-width: 768px)').matches ) {
    //     $('body').stellar({
    //         horizontalOffset: 50
    //     });
    // }

    $('.yamm-content').find('.change-img').find('img').not(':first-child').css('top', '-5000px');

    // Change image visible when navigation dropdown items are hovered
    $('#navigation').find('[data-img]').hover(function() {
        var img = $(this).data('img');
        $(this).parents('.yamm-content').find('.img' + img).css('top', '0').siblings('img').css('top', '-5000px');
    });

    // Detect if device has a touch interface
    if ("ontouchstart" in window || navigator.msMaxTouchPoints) {
        $('html').addClass('touchable');
        isTouch = true;
    } else {
        $('html').addClass('untouchable');
        isTouch = false;
    }


    /* Manipulation du DOM */
    /* déplacé dans le template : */
    /*
    $(".procedures--body ul li a").each(function(index) {
        $(this).parent('li').addClass('col-md-8');
        if (index > 0) {
            $(this).prepend('<i class="fa fa-caret-right"></i>');
        }
    });
    */

    // scroll vers l'ancre
    // $('a[href^="#"]').click(function(){ var the_id = $(this).attr("href"); $('html, body').animate({ scrollTop:$(the_id).offset().top }, 'slow'); return false; });



});


$(document).ready(function($) { // http://ashleydw.github.io/lightbox/#single-image

    // delegate calls to data-toggle="lightbox"
    $(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
        event.preventDefault();
        return $(this).ekkoLightbox({
            always_show_close: true
        });
    });

});


$(document).ready(function() {


    /*$('ul.nav li.dropdown').hover(function() {
        $(this).addClass('open').find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
    }, function() {
        $(this).removeClass('open').find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
    });*/

    /*$('.navigation--body .change-img').each(function() {
        console.log($(this).find('img').css('z-index'));
    });*/

    /*$('#acces-menu i').each(function(e){

        $(this).removeClass('fa-caret-square-o-down');
        /*console.log(e);*/

    /*});*/
    /*$('.panel-heading a').on('click', function(){
        $(this).find('i').addClass('fa-caret-square-o-up').siblings().removeClass('fa-caret-square-o-down');
    });*/



    $('.panel-heading a').on('click', function(e) {
            $(this).find('i').addClass('fa-caret-square-o-down');
            $(this).find('i').removeClass('fa-caret-square-o-up');
            var $this = $(this);
            var hash = $this.attr('href');
            var titre = $this.parent('h4');
            var titreParent = titre.parent('.panel-heading');
            var collapse = titreParent.next('div');
            /*console.log(collapse.attr('id')); */
            hashTraite = hash.substring(1, hash.length);
            /*console.log(collapse.attr('id'));*/
            if ($(collapse).hasClass('in')) {
                /*console.log('toto');*/
                var parent01 = $this.parent('.panel-heading');
                var enfant01 = parent01.children('h4');
                var enfant02 = enfant01.children('a');
                var enfant03 = enfant02.children('i');
                /*enfant03.removeClass('fa-caret-square-o-down');*/
                $(this).find('i').addClass('fa-caret-square-o-down');
                $(this).find('i').removeClass('fa-caret-square-o-up');
            } else {


                $(this).find('i').removeClass('fa-caret-square-o-down');
                $(this).find('i').addClass('fa-caret-square-o-up');
            }
            /*if(hashTraite == collapse.attr('id')) {
                console.log('ok');
                $this.find('i').toggleClass('fa-caret-square-o-up fa-caret-square-o-down');
            }
            else {

            }*/
            /*if (!$this.hasClass('panel-collapsed')) {
              /*$this.parents('.panel').find('.panel-title').slideUp();*/
            /*$this.addClass('panel-collapse');

      } else {
        $this.parents('.panel').find('.panel').slideDown();
        /*$this.removeClass('.panel-title');*/
            /*$this.find('i').toggleClass('fa-caret-square-o-up fa-caret-square-o-down');
      }*/

        })
        // Lightbox (à conserver)
        /*$(function() {
            var lightbox1 = $(".singleLightbox").ariaLightbox({ altText: function() { return $(this).find("img").attr("alt"); }, descText: function() { return $(this).attr("rel"); }, useDimmer: false, closeText: i18n[lang].close, pos: "auto", em: false, imgClose: '/extension/iagutils/design/ezwebin/images/contenu/fermer01.gif' });
            var lightbox2 = $("#gallery , .tab-content").ariaLightbox({ imageArray: "a.seriesLightbox", altText: function() { return $(this).find("img").attr("alt"); }, descText: function() { return $(this).attr("rel"); }, useDimmer: true, closeText: i18n[lang].close, pictureText: i18n[lang].image, ofText:i18n[lang].of, prevText: i18n[lang].prevImage, nextText: i18n[lang].nextImage, pos: "auto", em: false, imgClose: '/extension/iagutils/design/ezwebin/images/contenu/fermer01.gif' });
        });*/
        // Onglets (à conserver : fiches et galeries carousel)
        /*$(".onglets").tabs({fx:{opacity:"toggle"}});
        $("ul.ui-tabs-nav").removeClass("masquer");
        // Accordéon (à conserver : moteur de recherche, FAQ)
        $(".accordeon").accordion({ autoHeight: false, navigation: true });
        // Placeholder (à conserver : moteur de recherche)
        $("[placeholder]").textPlaceholder();
        // Panneau latéral coulissant (à conserver : filtres agenda)
        rightMenuWidthControl();
        $("#filtre_agenda-showhide").removeClass("masquer");

        // AnythingSlider (optionnel), liste des options dans V:\valerian440\extension\iagutils\design\ezwebin\javascript\jquery.anythingslider.js
        // $('#slider').addClass("avec-js");
        // $('#slider').anythingSlider({hashTags:false});

        // EasySlider (optionnel) - Options http://cssglobe.com/easy-slider-17-numeric-navigation-jquery-slider/
        $("#slider02").easySlider({
            imgWidth:       35,
            imgHeight:      75,
            imgRight:       '/extension/iagutils/design/ezwebin/images/contenu/slider_droite.png',
            imgLeft:        '/extension/iagutils/design/ezwebin/images/contenu/slider_gauche.png'
        });

        // ExtendAnchor (optionnel)
        // $("#carte").extendAnchor();  // Penser à ajouter .hover{cursor:pointer;} dans le CSS

        // $('#pictos li').hover(function(){ $(this).siblings().stop().fadeTo("fast",0.5); }, function(){ $(this).siblings().stop().fadeTo("fast",1); });

        // scroll vers l'ancre
        $('a[href^="#"]').click(function(){ var the_id = $(this).attr("href"); $('html, body').animate({ scrollTop:$(the_id).offset().top }, 'slow'); return false; });

        // ouvrir les liens externes dans une nouvelle fenêtre (attention, nécessite de modifier le tpl de lightbox pour mettre URL en relatif).
        // $("a[href^='http']").click(function(){ window.open($(this).attr('href')); return false; });

        // permet de garder les vidéos en arrière plan des menus et lightbox
        $('iframe').each(function(){
              var url = $(this).attr("src");
              var char = "?";
              if(url.indexOf("?") != -1){ var char = "&"; }
              $(this).attr("src",url+char+"wmode=transparent");
        });
        $(".onglets-fiche").tabs({ selected: 0, collapsible:true, fx:{opacity:"toggle"} });
        */

});
/**
 * Project: Bootstrap Hover Dropdown
 * Author: Cameron Spear
 * Contributors: Mattia Larentis
 *
 * Dependencies: Bootstrap's Dropdown plugin, jQuery
 *
 * A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
 *
 * License: MIT
 *
 * http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
 */
/*;(function ($, window, undefined) {
    // outside the scope of the jQuery plugin to
    // keep track of all dropdowns
    var $allDropdowns = $();

    // if instantlyCloseOthers is true, then it will instantly
    // shut other nav items when a new one is hovered over
    $.fn.dropdownHover = function (options) {
        // don't do anything if touch is supported
        // (plugin causes some issues on mobile)
        if('ontouchstart' in document) return this; // don't want to affect chaining

        // the element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());

        return this.each(function () {
            var $this = $(this),
                $parent = $this.parent(),
                defaults = {
                    delay: 500,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                showEvent   = 'show.bs.dropdown',
                hideEvent   = 'hide.bs.dropdown',
                // shownEvent  = 'shown.bs.dropdown',
                // hiddenEvent = 'hidden.bs.dropdown',
                settings = $.extend(true, {}, defaults, options, data),
                timeout;

            $parent.hover(function (event) {
                // so a neighbor can't open the dropdown
                if(!$parent.hasClass('open') && !$this.is(event.target)) {
                    // stop this event, stop executing any code 
                    // in this callback but continue to propagate
                    return true; 
                }

                $allDropdowns.find(':focus').blur();

                if(settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
                $this.trigger(showEvent);
            }, function () {
                timeout = window.setTimeout(function () {
                    $parent.removeClass('open');
                    $this.trigger(hideEvent);
                }, settings.delay);
            });

            // this helps with button groups!
            $this.hover(function () {
                $allDropdowns.find(':focus').blur();

                if(settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
                $this.trigger(showEvent);
            });

            // handle submenus
            $parent.find('.dropdown-submenu').each(function (){
                var $this = $(this);
                var subTimeout;
                $this.hover(function () {
                    window.clearTimeout(subTimeout);
                    $this.children('.dropdown-menu').show();
                    // always close submenu siblings instantly
                    $this.siblings().children('.dropdown-menu').hide();
                }, function () {
                    var $submenu = $this.children('.dropdown-menu');
                    subTimeout = window.setTimeout(function () {
                        $submenu.hide();
                    }, settings.delay);
                });
            });
        });
    };

    $(document).ready(function () {
        // apply dropdownHover to all elements with the data-hover="dropdown" attribute
        $('[data-hover="dropdown"]').dropdownHover();                
    });
})(jQuery, this);*/


/* Script original de Julien Royer */
if (document.getElementById && document.createTextNode) {

    (function() {

        function init() {
            if (!init.done) {
                init.done = true;
                var spans =
                    document.getElementsByTagName("span"),
                    m = [];
                for (var i = 0, span;
                    (span = spans[i]); ++i) {
                    if (belongsToClass(span, classNames.email)) {
                        m[m.length] = span;
                    }
                }

                for (i = 0;
                    (span = m[i]); ++i) {
                    initSpan(span);
                }

            }

        }

        function initSpan(span) {

            var p, u, h, d;

            var spans = span.getElementsByTagName("span");

            for (var i = 0, s;
                (s = spans[i]); ++i) {

                var str = s.firstChild && s.firstChild.nodeValue;

                if (belongsToClass(s, classNames.user)) {

                    u = str;

                } else if (belongsToClass(s, classNames.host)) {

                    h = str;

                } else if (belongsToClass(s, classNames.domain)) {

                    d = str;

                }

            }

            if (u && h && d) {

                chgSpan(span, u, h, d);

            }

        }

        function chgSpan(span, u, h, d) {

            var email = u + "@" + h + "." + d;

            var a = createElement("a");

            a.href = "mailto:" + email;

            a.className = classNames.email;

            a.appendChild(document.createTextNode(email));

            span.parentNode.replaceChild(a, span);

        }

        // DOM

        function createElement(nn) {

            return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", nn) : document.createElement(nn);

        }

        function belongsToClass(n, cn) {

            return new RegExp("(^| )" + cn + "( |$)").test(n.className);

        }

        // Events

        function addLoadEvent(f) {

            if (document.addEventListener) {

                document.addEventListener("DOMContentLoaded", f, false);

            }

            if (window.addEventListener) {

                window.addEventListener("load", f, false);

            } else if (document.addEventListener) {

                document.addEventListener("load", f, false);

            } else if (window.attachEvent) {

                window.attachEvent("onload", f);

            }

        }

        var classNames = {

            "email": "email",

            "user": "u",

            "host": "h",

            "domain": "d"

        };

        addLoadEvent(init);

    })();

}

/* open class="popup" links in new tabs/windows */
$(function() {
  $('#content .popup a').on('click', function(e) {
      e.preventDefault();
      window.open($(this).attr('href'), '_blank');
  });
});
