
(function($){

    /* All Images Loaded */

	$(window).on('load', function(){

        setTimeout(function(){
            $('[data-aos]').addClass('aos-animate');
        }, 100); 

        var rtl = false;
        if( $('body').hasClass('rtl') ){
            rtl = true;
        }

        // Sticky elements

		var document_width = $(document).width();
        if( document_width > 1200 && $('#header').hasClass('enable-sticky') ){
            var header_height = $('#header div.menu-wrapper').outerHeight();
            $('#header').height( header_height );
        }

        $(window).scroll(function(){
            if( document_width > 1200 && $('#header').hasClass('enable-sticky') ){
                if( $(window).scrollTop() >= 300) {
                    $('#header').addClass('is-sticky');                        
                } else {
                    $('#header').removeClass('is-sticky');
                }
            } else{
                $('#header').removeClass('is-sticky');  
            }
        });           

        $(window).on('resize', function() {
            var document_width = $(document).width();
            $('#header').removeClass('is-sticky');
            var header_height = $('#header div.menu-wrapper').outerHeight();
            $('#header').height( header_height );
            if( document_width < 1200 ){
                $('#header').removeClass('enable-sticky is-sticky');
            }
        });
        
		if($(document).width() > 767){
            var $grid = $('.grid-posts div.articles:not(.classic)').masonry({
                itemSelector: 'article',
                gutter: 0,
                horizontalOrder: true,
                isOriginLeft: !rtl,
            });
            setTimeout(function(){
                $grid.masonry('layout');
            }, 500);
            
        }     

    });
    
    /* Dom Loaded */

	$(document).ready(function($){ 

        var rtl = false;
        if( $('body').hasClass('rtl') ){
            rtl = true;
        }

        // Last submenu fix
        $('#header nav ul.menu > li.menu-item-has-children:last').addClass('last-menu-item');

        // Enable HTML5 form validation
        $('#commentform').removeAttr('novalidate');

        // Submenu on Mobile

        if( $('.epcl-single-toc').length > 0 ){
            $('.epcl-single-toc .toggle-title').on('click', function(){
                $(this).next().stop().slideToggle();
                $(this).parent().toggleClass('active');
            });

            var titleCount = $('.main-article div.text').find('h1, h2, h3, h4, h5, h6').length;
            if( titleCount < 1 ){
                $('.main-article .epcl-single-toc').hide();
            }
            $('.main-article div.text').find('h1, h2, h3, h4, h5, h6').each(function(index){
                if( !$(this).attr('id') ){
                    var id = Diacritics.clean( $(this).text().toLowerCase() ).replace(/ /g, '-');
                    $(this).attr('id', id);
                }
            });
            var heading_selector = $('.epcl-single-toc').data('heading-selector'); 
            if( !heading_selector ){
                heading_selector = 'h1, h2, h3, h4, h5';
            }
            tocbot.init({
                tocSelector: '.epcl-single-toc .epcl-toc',
                contentSelector: 'article div.text',
                headingSelector: heading_selector,
                linkClass: 'epcl-toc-link',
                collapseDepth: 6,
                headingsOffset: 0,
                scrollSmoothOffset: 0,    
                activeListItemClass: 'epcl-is-active-li',
                activeLinkClass: 'epcl-is-active-link',
            });
        }

        // Open mobile menu            
        $('#header button.menu-mobile').on('click', function(){
            const isOpen = $('#header').hasClass('menu-open');
            $('#header').toggleClass('menu-open');
            
            // Update aria-expanded attribute
            const menuButton = document.querySelector('#header button.menu-mobile');
            if (menuButton) {
                menuButton.setAttribute('aria-expanded', !isOpen);
            }
            
            // If menu is now open, set up focus trap. If it's closed, remove focus trap.
            if($('#header').hasClass('menu-open')) {
                breek_lite_setup_focus_trap();
            } else {
                breek_lite_close_mobile_menu(true);
            }
        });

        // Close mobile menu on escape key press
        $(document).on('keydown', function(event) {
            if (event.key === "Escape") {
                breek_lite_close_mobile_menu(true);
            }
        });


		$('.filters select').change(function(){
			var url = $(this).val();
			if(url)
				document.location = url;
        });

        // Back to top button

		$('#back-to-top').on('click', function(event) {
			event.preventDefault();
			$('html, body').animate({scrollTop: 0}, 500);
			return false;
        });

        // Single Post copy button

        $(".permalink .copy").on('click', function(){
            $("#copy-link").select();
            document.execCommand('copy');
        });  

		// Global: lightbox

        var mfp_close_markup = '<button title="%title%" class="mfp-close">&times;</button>';
		$('.lightbox').magnificPopup({
			mainClass: 'my-mfp-zoom-in',
			removalDelay: 300,
			closeMarkup: mfp_close_markup,
			fixedContentPos: true
        });

        $('.main-nav .lightbox, .epcl-search-button').magnificPopup({
			mainClass: 'my-mfp-zoom-in',
			removalDelay: 300,
			closeMarkup: mfp_close_markup,
            fixedContentPos: true,
            closeBtnInside: false,
            callbacks: {
                beforeOpen: function(item) {
                    setTimeout(function() { $('#search-lightbox form #s').focus() }, 500);
                },
            }
        });

        // Global: related galleries

        $('.epcl-gallery').each(function() {
            var elem = $(this);
            elem.find('ul').magnificPopup({
                type: 'image',
                gallery:{
                    enabled: true,
                    arrowMarkup: '<i class="mfp-arrow mfp-arrow-%dir% fa fa-chevron-%dir%"></i>',
                    tCounter: '%curr% / %total%'
                },
                delegate: 'a',
                mainClass: 'my-mfp-zoom-in',
                removalDelay: 300,
                closeMarkup: mfp_close_markup
            });
        });

        // Gutenberg Gallery with lightbox
        $('.wp-block-gallery, .woocommerce-product-gallery').each(function() {
            var elem = $(this);
            elem.magnificPopup({
                type: 'image',
                gallery:{
                    enabled: true,
                    arrowMarkup: '<i class="mfp-arrow mfp-arrow-%dir% fa fa-chevron-%dir%"></i>',
                    tCounter: '%curr% / %total%'
                },
                delegate: "a[href*='.jpg'],a[href*='.png'],a[href*='.gif'],a[href*='.jpeg'],a[href*='.webp']",
                mainClass: 'my-mfp-zoom-in',
                removalDelay: 300,
                closeMarkup: mfp_close_markup,
                image: {
                    titleSrc: function(item) {
                        return item.el.parent().find('figcaption').text();
                    }
                }
            });
        });

        // Gutenberg Single Image with lightbox
        $(".wp-block-image").not('.wp-block-gallery .wp-block-image').magnificPopup({
            type: 'image',
            gallery:{
                enabled: true,
                arrowMarkup: '<i class="mfp-arrow mfp-arrow-%dir% fa fa-chevron-%dir%"></i>',
                tCounter: '%curr% / %total%'
            },
            delegate: "a[href*='.jpg'],a[href*='.png'],a[href*='.gif'],a[href*='.jpeg'],a[href*='.webp']",
            mainClass: 'my-mfp-zoom-in',
            removalDelay: 300,
            closeMarkup: mfp_close_markup,
            image: {
                titleSrc: function(item) {
                    return item.el.parent().find('figcaption').text();
                }
            }
        });

        // Focus trap variables
        var breek_lite_focusableElements = [];
        var breek_lite_mobileNav = null;
        var breek_lite_firstFocusableElement = null;
        var breek_lite_lastFocusableElement = null;

        function breek_lite_setup_focus_trap() {
            breek_lite_mobileNav = document.querySelector('#header .main-nav');            
            if (!breek_lite_mobileNav) return;
            
            breek_lite_focusableElements = breek_lite_mobileNav.querySelectorAll(
                'a, button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );
            
            if (breek_lite_focusableElements.length > 0) {
                breek_lite_firstFocusableElement = breek_lite_focusableElements[0];
                breek_lite_lastFocusableElement = breek_lite_focusableElements[breek_lite_focusableElements.length - 1];
                setTimeout(function() {
                    breek_lite_firstFocusableElement.focus();
                }, 100);
                $(document).on('keydown.focustrap', breek_lite_trap_focus);
                $(breek_lite_mobileNav).on('focusout.focustrap', function() {
                    setTimeout(function() {
                        if (
                            breek_lite_mobileNav &&
                            !breek_lite_mobileNav.contains(document.activeElement) &&
                            $('#header').hasClass('menu-open')
                        ) {
                            breek_lite_close_mobile_menu(false);
                        }
                    }, 0);
                });
            }
        }

        function breek_lite_remove_focus_trap(restoreFocus) {
            if (typeof restoreFocus === 'undefined') {
                restoreFocus = true;
            }
            $(document).off('keydown.focustrap');
            if (breek_lite_mobileNav) {
                $(breek_lite_mobileNav).off('focusout.focustrap');
            }
            const menuButton = document.querySelector('#header button.menu-mobile');
            if (restoreFocus && menuButton) {
                menuButton.focus();
            }
        }

        function breek_lite_close_mobile_menu(restoreFocus) {
            $('#header').removeClass('menu-open');
            const menuButton = document.querySelector('#header button.menu-mobile');
            if (menuButton) {
                menuButton.setAttribute('aria-expanded', false);
            }
            breek_lite_remove_focus_trap(restoreFocus);
        }

        function breek_lite_trap_focus(e) {
            if (e.key !== 'Tab') return;
            
            if (e.shiftKey) {
                if (document.activeElement === breek_lite_firstFocusableElement) {
                    e.preventDefault();
                    breek_lite_lastFocusableElement.focus();
                }
            } else {
                if (document.activeElement === breek_lite_lastFocusableElement) {
                    setTimeout(function() {
                        breek_lite_close_mobile_menu(false);
                    }, 0);
                }
            }
        }

	});

})(jQuery);

(function() {
    var supportsPassive = eventListenerOptionsSupported();  
  
    if (supportsPassive) {
      var addEvent = EventTarget.prototype.addEventListener;
      overwriteAddEvent(addEvent);
    }
  
    function overwriteAddEvent(superMethod) {
      var defaultOptions = {
        passive: true,
        capture: false
      };
  
      EventTarget.prototype.addEventListener = function(type, listener, options) {
        var usesListenerOptions = typeof options === 'object';
        var useCapture = usesListenerOptions ? options.capture : options;
        options = usesListenerOptions ? options : {};
        if( type == 'touchstart' || type == 'touchmove'){
            options.passive = options.passive !== undefined ? options.passive : defaultOptions.passive;
        }        
        options.capture = useCapture !== undefined ? useCapture : defaultOptions.capture;
  
        superMethod.call(this, type, listener, options);
      };
    }
  
    function eventListenerOptionsSupported() {
      var supported = false;
      try {
        var opts = Object.defineProperty({}, 'passive', {
          get: function() {
            supported = true;
          }
        });
        window.addEventListener("test", null, opts);
      } catch (e) {}
  
      return supported;
    }

  })();