////// ****************** ONETRUST ****************** //////
/*********************************************************/ 

 $(document).ready(function(){ 
    var isNotLoad = true;
    OptanonWrapper(); 
    $('.save-preference-btn-handler, .onetrust-accept-btn-handler, .accept-recommended-btn-handler, .onetrust-close-btn-handler').on("click touchstart", function () {
      OptanonWrapper();
    });
    $('.video-cookie-message a, .ot-sdk-footer_btn a').on('click', function () {
      event.preventDefault();
      OneTrust.ToggleInfoDisplay();
    });
  });

function OptanonWrapper() {    
  //Marketing/Targeting Cookies
  if (typeof OnetrustActiveGroups != 'undefined' && OnetrustActiveGroups.includes("C0004")) {   
    
    //console.log('Targeting Accepted');
      $('.video-cookie-message').hide(); 
      $('.video-container iframe').each(function(){
          var $this = $(this);
          var url = $this.attr("data-src");
          $this.attr("src", url);
          $this.show();
      });       
    } else {
      //console.log('Targeting Denied');
      $('.video-cookie-message').show();
      $('.video-container iframe').each(function(){
        var $this = $(this);
        $this.removeAttr( "src" );
        $this.hide();
      });
    
  } 
       
}

////// ************* ONETRUST END****************** //////
/*********************************************************/


$(document).ready(function() {
    $('.fusion-menu li.menu-item').each(function(index) {
      $(this).find('.awb-menu__open-nav-submenu_click').on('click keypress', function(event) {
    // Check if the screen width is 1024px or less and if the event is a click or Enter key
    if ($(window).width() <= 1024 && (event.type === 'click' || (event.type === 'keypress' && event.which === 13))) {
        // Toggle 'set' class on the clicked item's parent
        $(this).parent().toggleClass('set');

        // Remove 'set' class from all other siblings
        $(this).parent().siblings().removeClass('set');
    }
});
    });
});


$(document).ready(function() {
    // Check if the first child has the class .banner-section
    if ($('.post-content').children().first().hasClass('banner-section')) {
        $('.post-content').css('margin-top', '112px');
    }
    
    // Check if the second child has the class .banner-section
    if ($('.post-content').children().eq(1).hasClass('banner-section')) {
        $('.post-content').children().eq(1).addClass('banner-mrg'); // Replace 'your-new-class' with the class you want to add
    }
});


(function($, window, document) {
  
 /* $(document).ready(function() {
        function adjustImageMargin() {
            $('.slider-items .slick-slide').each(function() {
                var firstColumn = $(this).find('.fusion-builder-row .fusion-layout-column:first-child');
                var lastColumnImage = $(this).find('.fusion-builder-row .fusion-layout-column:last-child span.fusion-imageframe');

                if (firstColumn.length && lastColumnImage.length) {
                    var firstColumnHeight = firstColumn.outerHeight() + 10;
                    lastColumnImage.css('margin-top', firstColumnHeight);
                }
            });
        }

        // Debounce function
        function debounce(func, delay) {
            let timeout;
            return function(...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), delay);
            };
        }

        function checkViewport() {
            if ($(window).width() >= 1024) {
                setTimeout(adjustImageMargin, 100);
                $('.slider-items').on('afterChange', adjustImageMargin);
            } else {
                $('.slider-items').off('afterChange', adjustImageMargin);
            }
        }

        // Initial check
        checkViewport();

        // Check on window resize with debounce
        $(window).resize(debounce(checkViewport, 200));
    });*/
  
    $(function() {
      cwsRedesign();
      relatedContent();
      generalA11y();
      slickSlider();
      menuAlign();
      //pluginSlider();
      //accessibility();
      cleanup(); // avada adjustments      
      tagreplace(); //changes the h tag level for accessibility on the quick search banner
      unwrapdeadlinks(); // Unwrap a tag from empty generated menu items
      a11y(); // ada fixes sitewide   
      hjlinkreplace(); // Hot Jobs Link replace with details url
      threeslider(); // 3 slide carousel
      mobMenuFunc();
      videoswitcher(); //Video switcher from Standard to AD
      addutmlink();
      if(window.location.href.indexOf("/job/") > -1){ jdcleanup();}  // accounts for some of the stray html that often comes in from the ATS on job descriptons
     // menuEscapeA11y();
     setTimeout(function(){menua11y(); }, 1000);
    });  
    
    $(window).on('load resize orientationchange', function() {
        maindropitemcombine(); // navigation edits - combine dropdown button element
        //dropmenufix(); // accessibility fixes for dropdown menu issues
      });
    
    $(window).on('load', function() {
        readmorewrap(); // adds an accessible read more/less to the job description - will need to be adjusted dependent on what is coming in from the API
        jobcartsupp();
        jobcartbtn();
      //$('.jobcart-btn').click(jobcartbtn);
    });
 
  /**********************************************************/
 /********* GLOBAL VARIABLES - Location,LANGUAGE, Universal functions, etc. **********/
 
     /*** English ***/ 
        var allhomedir = '/';
        var minimenu = 'Supplemental menu';
        var primemenu = 'Main careers menu';
        var ftrcarmenu = 'Footer Careers Menu';
        var ftrsecmenu = 'Footer Secondary Menu';
        var ftrprivmenu = 'Footer Privacy & Terms Menu';
        var srtby = 'Sort by:';
        var sortOrd = 'Click the title column heading to change the sort order.';
        var srchjbs = 'Search Jobs';
        var srchfilt = 'Search Filters';
        var onttxt = ' Opens in a new tab';
        
        var mainmenuid = $('#menu-main-menu');
        var dropitem = $('#menu-main-menu .dropwrap');
        var dropitembtn = $('#menu-main-menu .dropwrap > button');
        var mobmainmenunav = $('nav.primary-menu');
        var mobmainmenubtn = $('nav.primary-menu > button');
 
 /**********************************************************************************/ 
/****************************** Universal impact scripts *************************/ 
      
      
    function cleanup() {
      $('h1 p,h2 p,h3 p').contents().unwrap();
      $( 'p:empty' ).remove();
    }
    
    /*** main menu and accessibility fixes ****/  
    //function navfixes() { }
    
      /***************** Menu Fixes **********************/
      
  function unwrapdeadlinks() {
    $('.fusion-menu > .dead-link > a').contents().unwrap();
  }
      
  function maindropitemcombine() {
    $('#menu-main-menu .dropwrap > a').css('display','none');
    $('#menu-main-menu .dropwrap.careerareas-menu .awb-menu__sub-ul').attr('aria-hidden','true').attr('id','cadrop');
    $('#menu-main-menu .dropwrap.careerareas-menu > button').html('<span class="menu-text">Career Areas</span>').attr('aria-controls','cadrop');
    $(dropitembtn).on( 'click',  function ( event ) {
      $(this).focus();
    });
  }    
      
//function dropmenufix() {
//  if($(window).width() > 769){ 
//    $(dropitembtn).on( 'click', function(e) {
//      setTimeout(function() {
//        if ($(dropitembtn).attr('aria-expanded') == 'true') {
//            $(dropitembtn).siblings('ul').attr('aria-hidden','false'); 
//        } else {
//            $(dropitembtn).siblings('ul').attr('aria-hidden','true'); 
//        }
//      }, 150);
//    });
//    // close locations sub when tabbed out
//    $('body').on( 'keypress keyup', function(e) {
//      if ((e.keyCode == 9) && $(dropitem).hasClass("expanded")) {   
//        if ($(dropitembtn).is(":focus") || $(dropitem).find('.awb-menu__sub-ul a').is(":focus") ) {
//          //do nothing
//        } else {
//          $(dropitem).removeClass('expanded');
//          $(dropitembtn).attr('aria-expanded','false');
//          $(dropitem).find('.awb-menu__sub-ul').attr('aria-hidden','true');
//        }   
//      } 
//    });
//  }
  // mobile
    // hide drop from screen readers

//}

 function mobMenuFunc() {
 if($(window).width() < 769){ 
    $(mainmenuid).attr('aria-hidden','true');
    $(mobmainmenubtn).on( 'click', function(e) {
      setTimeout(function() {
        if ($(mobmainmenubtn).attr('aria-expanded') == 'true') {
          $(mainmenuid).attr('aria-hidden','false');
        } else {
          $(mainmenuid).attr('aria-hidden','true');  
        }
      }, 150);
    });
      // close menu when tabbed out
    $('body').on( 'keypress keyup', function(e) {
      if ((e.keyCode == 9) && $(mobmainmenunav).hasClass("expanded")) {
        if ($(mainmenuid).find("*").is(":focus")) {
        } else {
          $(mobmainmenunav).removeClass('expanded').attr('aria-expanded','false');
          $(mobmainmenubtn).attr('aria-expanded','false');
          $(mainmenuid).attr('aria-hidden','true');
          $(mainmenuid).find('a, button').attr('tabindex','-1');
        } 
      } 
    });
  }
}
   
 /**********************************************************************************/ 
/****************************** Carousel scripts *************************/    
function threeslider() {   
  
 $( '.threeitem-slider > .fusion-column-wrapper > .fusion-builder-row' ).each(function() {
        $(this).wrap( "<div></div>" );
      }); 
  
  $('.threeitem-slider > .fusion-column-wrapper').slick({
    infinite: false,
    slidesToShow: 3, 
    slidesToScroll: 1,
    regionLabel: 'Carousel of content',
    centerMode: false,
    swipeToSlide: true,
    draggable: true,
    dots: true,
    arrows: true,
    //arrowsPlacement:"afterSlides",
    responsive: [
      {
      breakpoint: 769,
        settings: {
          slidesToShow: 1, 
          adaptiveHeight: true
        }
      }
    ]
  }); 
   }

 /**********************************************************************************/ 
/****************************** Video Switch scripts *************************/

function videoswitcher() {
  $('.vidset-wrapper').each(function() {
    var videoframe = $(this).find('.vidplayer iframe');
    $('.vidswitchbtn').on( 'click keydown',  function ( event ) {
      $(this).addClass('active');
      if ( $(this).hasClass('standardvid') ) { 
        $(this).parents('.vidbtnwrap').find('.advid').removeClass('active');
      }
      if ( $(this).hasClass('advid') ) { 
        $(this).parents('.vidbtnwrap').find('.standardvid').removeClass('active');
      }
      var videoid = $(this).attr('data-vidid');
      var videoemburl = "https://www.youtube.com/embed/" +videoid+ "?autoplay=0&enablejsapi=1&wmode=opaque";
      var videotitle = $(this).attr('data-vidttl');
      $(videoframe).attr('src', videoemburl).attr('title',videotitle); 
    });
  });
}

 /**********************************************************************************/ 
/*************** Accessibility/WCAG items on multiple site elements ***************/

  function a11y() {
    // General/Universal, Search, etc.
      // shift focus to skip after to-top is clicked
      $('a#toTop').on( 'click keydown',  function ( event ) {
        $('.skip-link').focus();    
      });
      
      // remove label and role from all site sections where it is unused - per Zenyth
      $('.fusion-fullwidth').each(function(){
        var alab = $(this).attr('aria-label');
        var arole = $(this).attr('role');
        if (alab == null || alab == undefined || alab == '') {$(this).removeAttr('aria-label');}
        if (arole == null || arole == undefined || arole == '') {$(this).removeAttr('role');}
      });
      
      // Header & Footer roles, etc.
      $('.fusion-tb-header').attr('role','banner');
      $('.fusion-tb-header nav.mini-menu').attr('aria-label', minimenu);
      $('.fusion-tb-header nav.primary-menuu').attr('aria-label', primemenu);
      $('.fusion-footer').attr('role','contentinfo');
      $('.fusion-footer nav.ftr-careers').attr('aria-label', ftrcarmenu);
      $('.fusion-footer nav.ftr-secmenu').attr('aria-label', ftrsecmenu);
      $('.fusion-footer nav.ftr-privmenu').attr('aria-label', ftrprivmenu);
      
      /*** Quick Search Banner ***/
      $('.search-banner .quicksearch-btn input').attr('aria-label', srchjbs);
      $( ".quicksearch-primary_category .select2-selection--single .select2-selection__rendered" ).text('');
      $( ".select2-selection--single .select2-selection__rendered" ).attr('tabindex','-1');
      
      /** Full Job search filters ***/ 
      $('.widget-jobsearch-full #toggleAdvSearch .avia_iconbox_title').html(srchfilt);
      $('.container-primary-category label').attr('id','catsearch');
      $('.container-primary-category .select2-selection--single').attr('aria-labelledby','catsearch');
      $('.container-department label').attr('id','deptsearch');
      $('.container-department .select2-selection--single').attr('aria-labelledby','deptsearch');
      $('.container-statecity label').attr('id','locsearch');
      $('.container-statecity .select2-selection--single').attr('aria-labelledby','locsearch');
       
      /** job search results table **/
      $('.widget-jobsearch-results .search-columns').prepend('<div class="sr-only" id="sortalert">Click the column heading to change the sort order.</div>');
      $('.widget-jobsearch-results .search-columns').attr('role','row');
      $('.widget-jobsearch-results .search-results-table').attr('role','table');
      $('.widget-jobsearch-results #colhead-title').attr('aria-sort','none');
      $(".widget-jobsearch-results #colhead-title").on("click", function(){  
        if ($('#colhead-title').hasClass('active')) {
          setTimeout(function() {
            if (window.location.href.indexOf("?sort=title&dir=ascending") > -1) {
              $('#colhead-title').attr('aria-sort','ascending');
            } else if (window.location.href.indexOf("?sort=title&dir=descending") > -1) {
              $('#colhead-title').attr('aria-sort','descending');
            }
          },1000);
        } else {          
          $(this).attr('aria-sort','none');
        }  
      });
      
      // tab alterations
    $('ul.nav-tabs').attr('role', 'tablist');
    $('ul.nav-tabs li').attr('role', 'presentation');
    $('ul.nav-tabs li a').attr('role', 'tab'); 
    $('ul.nav-tabs li a').on('click keydown focus', function(e) { 
      $(this).removeAttr('aria-expanded');
      $(this).parent().siblings().find('a').removeAttr('aria-expanded');
    });
    $('.fusion-tabs *').on('keydown', function(e) { 
      var key = e.which; 
      if (key == 36) { 
        //console.log('home click');
        e.preventDefault();
        $(this).find('.nav-tabs > li:first-child a').focus().click();
      } 
      if (key == 35) { 
        //console.log('end click');
        e.preventDefault();
        $(this).find('.nav-tabs > li:last-child a').focus().click();
      }
    });
    if($(window).width() < 769){
      $('.nav-tabs .tab-link').on('keypress keyup', function(e) {
        if ((e.keyCode == 40)) {
          //console.log('arrow down click');
          $(this).parent().next().find('a').focus();
        }   
        if ((e.keyCode == 38)) {
          //console.log('arrow up click');
          $(this).parent().prev().find('a').focus();
        }   
      });
    }
    
    // tab alterations
  $('ul.nav-tabs').attr('role', 'tablist');
  $('ul.nav-tabs li').attr('role', 'presentation');
  $('ul.nav-tabs li a').attr('role', 'tab'); 
  $('ul.nav-tabs li a').on('click keydown focus', function(e) { 
    $(this).removeAttr('aria-expanded');
    $(this).parent().siblings().find('a').removeAttr('aria-expanded');
  });
  $('.fusion-tabs *').on('keydown', function(e) { 
    var key = e.which; 
    if (key == 36) { 
      //console.log('home click');
      e.preventDefault();
      $(this).find('.nav-tabs > li:first-child a').focus().click();
    } 
    if (key == 35) { 
      //console.log('end click');
      e.preventDefault();
      $(this).find('.nav-tabs > li:last-child a').focus().click();
    }
  });
  if($(window).width() < 769){
    $('.nav-tabs .tab-link').on('keypress keyup', function(e) {
      if ((e.keyCode == 40)) {
        //console.log('arrow down click');
        $(this).parent().next().find('a').focus();
      }   
      if ((e.keyCode == 38)) {
        //console.log('arrow up click');
        $(this).parent().prev().find('a').focus();
      }   
    });
  }
    
    // accordion toggles
    $('.accordian .fusion-panel .panel-collapse').attr('role','region');
      
      
    /** Job List / Hot Jobs **/
    $('.widget-joblist').attr('role','list');
    $('.widget-joblist > .widget_joblist_row').attr('role','listitem');
      
        // Opens in a new window links
      $(".fusion-footer a, main a:not(.sharelink), .fusion-tb-header .fusion-imageframe a, .fusion-tb-header .fusion-social-network-icon").each(function(){
        var newlink = $(this);   
        if ( newlink.attr('target') == '_blank') {
          //$(this).addClass('addTooltip').attr('title', 'Opens in a new tab');
        }
        if ( $(newlink).hasClass('fusion-no-lightbox') ||  $(newlink).hasClass('fusion-social-network-icon') ) {
          //$(this).attr('data-placement','bottom');
        }
      }); 
      
  }
 
 /**********************************************************************************/ 
/************************** Job Cart Page & Menu Scripts **************************/
  function jobcartbtn() {  
    if ($('.saved-jobs-menu .jobcart-count').is(':empty')) { 
      $('.saved-jobs-menu .jobcart-count').text("0");
    }
    if ($('.jobcart-btn').text() === 'Save this job') {
      $('.jobcart-btn').attr('aria-pressed','false');
    } 
    if ($('.jobcart-btn').text() === 'Unsave this job') {
      $('.jobcart-btn').attr('aria-pressed','true');
    }
  }

  function jobcartsupp() {
    /*** job cart buttons - nav & ejd ****/
    $('.jobcart-btn').addClass('button-flat button-small fusion-button-default').removeClass('fusion-button-default-size');
    
    $("#gtm-jobdetail-cart a .fas").removeClass('fa-shopping-cart').addClass('fa-bookmark'); 
    $('.saved-jobs-menu .awb-menu__main-a').detach(); 

    /*** job cart page ****/
    $('.jobcart').attr({"role": "table", "aria-label": "Job cart", "aria-describedby": "jobcart_table_desc"});
    $('.jobcart').prepend('<div id="jobcart_table_desc" style="display:none;">Job cart table with saved jobs</div>');
    $('<div role="row" class="column-headers"><span class="fusion-layout-column one_fifth first" role="columnheader" aria-sort="none">View Job</span><span class="fusion-layout-column two_fifth" role="columnheader" aria-sort="none">Job Title</span><span class="fusion-layout-column one_fifth" role="columnheader" aria-sort="none">Location</span><span class="fusion-layout-column one_fifth last" role="columnheader" aria-sort="none">Remove from Cart</span></div>').insertAfter(".jobcart .error");
    $('.jobcart .jobcart-row').wrapAll('<div role="rowgroup" class="jobcart-rowgroup"></div>').attr('role','row');
    $('.jobcart .jobcart-row .flex_column').attr('role','cell');
    $('#gtm-jobcart-apply a').addClass('jcapp-btn fusion-button button-flat button-small button-default fusion-button-default').removeClass('avia-button avia-color-theme-color avia-size-small').text('View Job');
    $('.jobcart .jobcart-row > div.flex_column').removeClass('flex_column').addClass('fusion-layout-column');
    $('.jobcart .jobcart-row > div.av_one_fifth').removeClass('av_one_fifth').addClass('one_fifth');
    $('.jobcart .jobcart-row > div.av_two_fifth').removeClass('av_two_fifth').addClass('two_fifth');
    
    // jobs API ajax call
    $('.jobcart-rowgroup .jobcart-row').each(function(){
      var job_id = $(this).find('.flex_column:nth-child(2) a').attr('href');
      //console.log(job_id);
    });
    
    // remove full url domain from View Job Button
    $('#gtm-jobcart-apply a').each(function(){
      var viewurl = $('#gtm-jobcart-apply a').attr('href');
      var viewurlalt = viewurl.replace(/^.*\/\/[^\/]+/, '');
      $('#gtm-jobcart-apply a').attr('href', viewurlalt).removeAttr('target');
    });
  }

 /**********************************************************************************/ 
/************************** Feature Alteration Scripts **************************/

  /****** Hot Jobs / Job Lists ******/
    function hjlinkreplace() {
      $('.home-hotjobs .job-list-row').each(function() {  
        var viewjlink = $(this).find('.job-list-left-container a').attr('href');
        $(this).find('.job-list-right-container a').attr('href', viewjlink);
      });
    }
    
     /** QUick Search - change header designation ****/
    function tagreplace() {
      $('.search-banner .widgettitle').replaceWith(function () {
        return "<h2 class='widgettitle cws-widgetitle'>" + $(this).html() + "</h2>";
      });
    }
  
  
 /**********************************************************************************/
/******************************* Job Details Scripts *******************************/

  /****** Job Description cleanup from ATS ******/
    function jdcleanup() {
      $('.jd-desc font, .jd-desc p span, .jd-desc li span, .jd-desc h1, .lj-ttl p, .jd-desc h3, .jd-desc p em').contents().unwrap();
      $('.jd-desc p').each(function() {
        const $this = $(this);
        if( ($this.html().replace(/\s| /g, '').length === 0) || ($this.html().replace(/\s| /g, '').length === 0) )
        $this.remove();
      });
      $(".jd-desc p").html(function (i, html) {
        return html.replace(/ /g, '');
      });
      $('.jd-desc p').filter(function(){
        return !$.trim($(this).text());
      }).remove();
      $('.jd-desc h2, .jd-desc h3').replaceWith(function () {
        return "<div>" + $(this).html() + "</div>";
      });
      $(".jd-desc p strong").each(function() {
        var text = $(this).text();
      $(this).text(text.replace(/\u00a0/g, " "));
      });
    }
    
   /******AA Accessible Read more/less function on details ******/
    function readmorewrap() {
      $('.jd-responsibilities, .jd-qualifications').contents().unwrap();
      $('.jobdescfull p:nth-child(7)').nextAll().wrapAll( "<div id='hidedesc' class='more'/>");
      $('#hidedesc').hide();
      $('#morelessBtn').on('click touchstart', function(){
        event.preventDefault();
        if ($("#hidedesc.more")[0]) {
          $("#hidedesc").removeClass('more').addClass('less'); 
          $('#morelessBtn').text('Read less').attr('aria-expanded','true');
          $('#hidedesc').show().attr('tabindex','-1').focus();
        } else if ($("#hidedesc.less")[0]) {
          $("#hidedesc").removeClass('less').addClass('more');
          $('#morelessBtn').text('Read more').attr('aria-expanded','false');
          $('#hidedesc').removeAttr('tabindex').hide();
          $('html, body').animate({scrollTop: $("#fulldesc").offset().top}, 600);
        }
      });      
    }    
    
    function addutmlink() {  
      $(".zwt-wp-lnk-prev.full a").each(function() {
        var blogprevlink = $(this).attr('href');
        var blogutmsource = '?lang=en&utm_medium=affiliate&utm_source=td_careers'
        $(this).attr('href', blogprevlink + blogutmsource);
      });
    }

function relatedContent() {
      $('.related-content-links li a').on('mouseenter focus', function() {
        $(this).toggleClass('active');
        var dataSrcImg = $(this).find('.number').attr('data-src-img');
        var dataAltTxt = $(this).find('.number').attr('data-alttext');
            setTimeout(function() {
        $('.img-related img').attr('src', dataSrcImg).attr('alt', dataAltTxt);
        $('.img-related img').attr('srcset', dataSrcImg);
        }, 200);
    });

    $('.related-content-links li a').on('mouseleave blur', function() {
        $(this).removeClass('active');
        $('.img-related img').attr('src', function() {
         });
    });
    
    $('.related-content-links li a').on('focusin', function() {
        $(this).trigger('mouseenter');
    });

    $('.related-content-links li a').on('focusout', function() {
        $(this).trigger('mouseleave');
    });
}

function generalA11y() {

    $('.fusion-imageframe img').removeAttr('title');
    $('.list-wrap .fusion-builder-row').attr('role', 'list');
    $('.list-wrap .fusion-builder-row .fusion-layout-column ').attr('role', 'listitem');
    $('.nested-list .fusion-builder-row').attr('role', 'list');
    $('.nested-list .fusion-layout-column ').attr('role', 'listitem');
    $('.slick-dots').removeAttr('role');
    $('.slick-dots button').removeAttr('role');
    $('.slick-dots li.slick-active button').attr('aria-current', 'true');

    

  $('.plugin-slider .slick-track div.plugin-slide').each(function(index) {
        var slideNumber_new = index + 1;
        setTimeout(function() {
         $(this).attr('aria-label', 'slide' + slideNumber_new);
        }, 2000);
    });


  $('html[lang="en-US"] a[target="_blank"]').each(function() {
    if ($(this).attr('data-src')) {
        $(this).find('.fusion-button-text').after('<span class="sr-only"> ' + $(this).attr('data-src') + ' Opens in new tab</span>'
     );
    } 
    else {
        $(this).append(' <span class="sr-only">  Opens in new tab</span>');
    }
   });
  
    $('html[lang="fr-ca"] a[target="_blank"]').each(function() {
    if ($(this).attr('data-src')) {
        $(this).find('.fusion-button-text').after("<span class='sr-only''> " + $(this).attr('data-src') + " S'ouvre dans un nouvel onglet</span>");
    } 
    else {
        $(this).append(" <span class='sr-only'>  S'ouvre dans un nouvel onglet</span>");
    }
   });
  $('a[target="_self"]').each(function() {
    if ($(this).attr('data-src')) {
        $(this).find('.fusion-button-text').after('<span class="sr-only">' + $(this).attr('data-src')  +'</span>');
    } 
   });

      
    $('.no-label').removeAttr('aria-label');
    $('.cta-ul-links').attr('role', 'navigation').attr('aria-label', 'Page content links');
    
    /* Modal pop-up focus return to the modal button/element after close */
   /* modal close button aria-label */
   $('.fusion-modal .close').attr('aria-label', 'Close dialog window');
   $('html[lang="fr-ca"] .fusion-modal .modal-header .close').attr('aria-label', 'Fermer la boîte de dialogue');
   /* END modal close button aria-label */
   $('.fusion-modal').on('hidden.bs.modal', function() {
      var getAllClass = $(this).attr('class');
      var splitClass = getAllClass.split(' ');
      var dataTargetAttr = '.'+splitClass[0]+'.'+splitClass[4];
      $('.fusion-modal-text-link[data-target="'+dataTargetAttr+'"]').focus();
    });
    /* End of Accessibility */
    $('.slick-dots').removeAttr('role');
    $('.slick-dots li').removeAttr('role');
    $('.slick-dots li button').removeAttr('aria-selected').removeAttr('aria-label');
    $('.slick-dots li button').on('click keypress', function(e) {
        // Check if the event is a click or a keypress (Enter key)
        if (e.type === 'click' || (e.type === 'keypress' && e.key === 'Enter')) {
            // Toggle aria-current attribute for the parent of the clicked button
            $(this).attr('aria-current', function(_, attr) {
                $('.slick-dots li button').removeAttr('role');
                return attr === 'true' ? 'false' : 'true';
            });

            // Remove role="tab" from the parents and buttons within .slick-dots
            setTimeout(function() {
            $('.slick-dots').removeAttr('role');
            $('.slick-dots li button').removeAttr('role').removeAttr('aria-current');
            $('.slick-dots li.slick-active button').attr('aria-current', 'true');
            $('.slick-dots li button').removeAttr('aria-selected').removeAttr('aria-label');
            }, 2000);
        }
    });
    $('.breadcrumb-leaf').attr('aria-current', 'page');


//$('.awb-menu.collapse-enabled.mobile-mode-collapse-to-button .awb-menu__m-toggle').attr('role', 'button').attr('aria-expanded', 'false');
//    $(".awb-menu.collapse-enabled.mobile-mode-collapse-to-button .awb-menu__m-toggle").on("click keypress", function(event){
//            if(event.type === "keypress" && event.which !== 13) {
//                return; // If not enter key, return
//            }
//            event.preventDefault(); // Prevent default behavior of the link
//
//            $(this).toggleClass("active"); // Toggle the "active" class
//
//            // Update aria-expanded attribute
//            setTimeout(function() {
//            
//            var expanded = $(this).attr("aria-expanded") === "true";
//            $(this).attr("aria-expanded", !expanded);
//            }, 2000);
//            $('.fusion-flyout-menu, #menu-main-menu').removeAttr('tabindex').removeAttr('aria-hidden').css('display', 'block');
//        });

        setTimeout(function() {
     $('img.zwt-wp-lnk-prev-img').attr('alt', '');
     $('.plugin-slider a.zwt-wp-lnk-prev-url-host').remove();
     $('.zwt-wp-lnk-prev.full a').attr('target', '_blank').removeAttr('aria-label');
     $('.plugin-slide').removeAttr('tabindex');
     $('.slick-track .plugin-slide').each(function() {
       $(this).find('.zwt-wp-lnk-prev-texts').slice().insertAfter($(this).find('.zwt-wp-lnk-prev-img'));
       var link = $(this).find('.zwt-wp-lnk-prev-desc').text();
       //$(this).attr('aria-label', link + " Opens in new tab");
       //$('.slick-dots li button').removeAttr('aria-label');
       $('a.url.zwt-wp-lnk-prev-title').attr('tabindex', '-1');
       $('a.url.zwt-wp-lnk-prev-title .sr-only').hide();
    });
    
    $('input.fusion-search-submit.searchsubmit').attr('value', 'Search');
    $('.sub-menu-section h2 img').attr('alt','');
    $('.fusion-privacy-bar.fusion-privacy-bar-bottom').remove();
    //$('.slick-slide').removeAttr('role').removeAttr('aria-hidden').removeAttr('aria-describedby');
    $('#onetrust-policy-title').remove();
    $('nav.primary-menu').attr('aria-label', 'Primary');
    //$('.ot-sdk-show-settings').attr('tabindex', '0');
    }, 2000);
    
    
    $(".plugin-slider .slick-arrow").on("click keypress", function(event){
      setTimeout(function() {
      $('.zwt-wp-lnk-prev.full a').attr('target', '_blank').attr('tabindex', '-1').attr('aria-hidden', 'true');
      }, 3000);
    });

    $('.relate-cont li').on('mouseenter', function() {
            $('.relate-cont li').removeClass('active');
            $(this).addClass('active');
        });
        
        // Initial setup
    $('.fusion-footer .wpml-ls ul a.wpml-ls-item-toggle')
        .attr('aria-expanded', 'false')
        .attr('role', 'button');
    $('.fusion-footer .wpml-ls ul a.wpml-ls-item-toggle').on('click keypress', function(e) {
        $(this).toggleClass('active');

        // Toggle aria-expanded attribute
        var expanded = $(this).attr('aria-expanded') === 'true' || false;
        $(this).attr('aria-expanded', !expanded);
    });
}




        
function menuEscapeA11y(){
    $(document).on("keyup", function(e) {
      var kcode = (e.keyCode ? e.keyCode : e.which);
      if(kcode == 9){
          if( $('.primary-menu ul.fusion-menu > li > a:focus').length){
              if(!$(this).parent('li').hasClass('expanded')){
                  $('.primary-menu').find('li.expanded > a').trigger('click');
              }
          }
      }
      if(kcode == 27){
          if( $('.primary-menu a:focus').length){
              $('.primary-menu').find('li.expanded > a').trigger('click').focus();
          } 
      }
  });
  $('.primary-menu ul.fusion-menu').on('focusout', function (e) {
    setTimeout(function () { // needed because nothing has focus during 'focusout'
        if ($(':focus').closest('.primary-menu ul.fusion-menu').length <= 0) {
            $('.primary-menu').find('li.expanded > a').trigger('click');
        }
    }, 0);
  });
}


function cwsRedesign() {
  //$('.awb-menu_dc-yes.awb-menu_em-click .awb-menu__open-nav-submenu_click').remove();
  $('html[lang="en-US"] .has-fusion-sticky-logo.fusion-imageframe a').append('<span class="logo-text">TD Careers</span>');
  $('html[lang="fr-ca"] .has-fusion-sticky-logo.fusion-imageframe a').append('<span class="logo-text">Carrières à la TD</span>');
  $('.has-fusion-standard-logo img').attr('alt', '');
  $("#year").text((new Date).getFullYear());
}


function menua11y() {
    // Set 'aria-current' for the current menu item
    $('.menu-item.current-menu-item > a').attr('aria-current', 'page');

    // Set 'aria-controls' for submenus
    $('.fusion-tb-header nav .menu-item-has-children').each(function() {
        let subMegaMenu = $(this).find('.awb-menu__mega-wrap').attr('id');
        $(this).find('button.awb-menu__open-nav-submenu_main').attr('aria-controls', subMegaMenu);
    });

$('.awb-menu__open-nav-submenu_click').on('click keypress', function(event) {
    let x = $(this);
    // Set a timeout to focus after the click/keypress event
    setTimeout(function() {
        x.focus();
    }, 200);
    
});


    
    // Toggle submenu expansion state and focus management
//    $("button.awb-menu__open-nav-submenu_mobile").each(function() {
//        $(this).off('click').on('click', function() {
//            const expanded = $(this).attr("aria-expanded") === "true";
//            $(this).attr("aria-expanded", !expanded);
//            if (!expanded) {
//                setTimeout(() => {
//                    $(this).siblings("#menu-main-menu").find("a[href], button, textarea, input, select, [tabindex='0']").first().focus();
//                }, 100);
//            }
//        });
//    });

    // Close submenu on Escape key press and manage focus
    $(document).on("keyup", function(e) {
        if (e.key === "Escape") {
            $("button.awb-menu__open-nav-submenu_mobile[aria-expanded='true']").each(function() {
                $(this).attr("aria-expanded", false);
                setTimeout(() => {
                    $(this).focus();
                }, 100);
            });
        }
    });

    // Manage focus out to automatically close expanded submenu
    $(".menu-item").each(function() {
        $(this).on('focusout', function(e) {
            if (!$(this).has(e.relatedTarget).length) {
                const $toggleButton = $(this).find("button.awb-menu__open-nav-submenu_mobile");
                if ($toggleButton.attr('aria-expanded') === 'true') {
                    $toggleButton.attr("aria-expanded", false);
                }
            }
        });
    });
    
    
       $(document).on('click keypress', '.jumplink-desk.mega-sub-menu a', function(event) {
        event.preventDefault(); // Prevent default anchor click behavior
    $(this).closest('li.menu-item').removeClass('expanded');
    $(this).closest('li.menu-item').find('button').attr('aria-expanded', 'false');
        var targetId = $(this).attr('href'); // Get the target section ID

        // Check if the target exists
        if ($(targetId).length) {
            // Set offset based on window width
            var offset = $(window).width() >= 1024 ? 200 : 100; // 200 for min-width 1024px, 100 for max-width 1024px
            var targetOffset = $(targetId).offset().top - offset; // Calculate target position with offset

            // If the screen width is 1024px or more, animate the scroll
            if ($(window).width() >= 1024) {
                $('html, body').animate({
                    scrollTop: targetOffset
                }, 600); // Duration of the scroll in milliseconds
            } 
            else if ($(window).width() < 1024) {
                window.location.hash = targetId;
                $('nav.awb-menu').removeClass('expanded');
            }
            else {
                // If the screen width is less than 1024px, just jump to the section
                window.location.hash = targetId;
            }
        } else {
            console.warn("Target section does not exist: " + targetId);
        }
    });
    /*Mobiel menu close */
    $('.fusion-tb-header .awb-menu.collapse-enabled .awb-menu__sub-li a').on('click keypress', function(event) {
        // Check if it's a keypress event and if the key pressed is not Enter or Space
        if (event.type === 'keypress' && event.which !== 13 && event.which !== 32) {
            return; // Exit if it's not Enter or Space
        }
        
        // Find the closest parent nav.awb-menu and remove the expanded class
        $(this).closest('.fusion-tb-header').find('nav.awb-menu').removeClass('expanded');
    });
    
    function handleMenuToggle() {
        // Only execute if the window width is 1024 pixels or less
        if ($(window).width() <= 1024) {
            $('.fusion-tb-header .awb-menu__sub-li a, .fusion-tb-header a[href^="#"]').off('click keypress').on('click keypress', function(event) {
                // Check if it's a keypress event and if the key pressed is not Enter or Space
                if (event.type === 'keypress' && event.which !== 13 && event.which !== 32) {
                    return; // Exit if it's not Enter or Space
                }

                // Find the closest parent nav.awb-menu and remove the expanded class
                $(this).closest('.fusion-tb-header').find('nav.awb-menu').removeClass('expanded');
            });
        } else {
            // If the width is greater than 1024, unbind the event handler
            $('.fusion-tb-header .awb-menu.collapse-enabled .awb-menu__sub-li a').off('click keypress');
        }
    }

    // Initial call
    handleMenuToggle();

    // Re-evaluate on window resize
    $(window).resize(function() {
        handleMenuToggle();
    });
    /* End of mobile menu close*/
    
    
    $('.cta-ul-links a').on('click keypress', function(event) {
        // Check if the screen width is less than or equal to 1024px
            event.preventDefault(); // Prevent default anchor click behavior
            
            // Get the target section's ID
            var target = $(this).attr('href');
            var offset = 100; // Set the offset

            // Animate the scroll to the target section
            $('html, body').animate({
                scrollTop: $(target).offset().top - offset
            }, 600); // Duration of the scroll animation in milliseconds
    });
    
    
}


function menuAlign() {
    // Get the width of the image inside the .fusion-title
    var imgWidth = $('.sub-menu-section .fusion-title h2 img').width();
    $('.sub-menu-section .fusion-text').css('padding-left', (imgWidth + 10) + 'px');
}


  function slickSlider() {
  $(".slider-items > .fusion-column-wrapper").on("init", function(event, slick) {
    $('.slider-items > .fusion-column-wrapper').attr({'aria-label': 'Testimonial Slider', 'aria-roledescription':'carousel'});
    $('.slider-items > .fusion-column-wrapper .slick-slide').attr('aria-roledescription', 'slide');
    $('.slider-items > .fusion-column-wrapper .slick-prev .slick-sr-only').text('Previous Testimonial Slide');
    $('.slider-items > .fusion-column-wrapper .slick-next .slick-sr-only').text('Next Testimonial Slide');
    setTimeout(function(){
        $('.slider-items .slick-slide').attr('aria-hidden', true);
        $('.slider-items .slick-active.slick-slide').attr('aria-hidden', false);
    },1000);
    $('.slider-items > .fusion-column-wrapper .slick-slide').each(function(){
      var slideNumText  = 'Slide {current_slide} of {total_slide}';
      let slideNumber = $(this).attr('aria-label').split(' ').pop();
      slideNumText = slideNumText.replace('{current_slide}', slideNumber);
      slideNumText = slideNumText.replace('{total_slide}', slick.slideCount);
     $(this).attr('aria-label', slideNumText)
    });
  $('.slider-items .slick-list').attr('aria-live', 'off').attr('aria-relevant', 'additions');
  });
  
  $('.slider-items > .fusion-column-wrapper').slick({
      dots: true,
      fade: false,
      pauseOnHover: false,
      arrows: true,
      infinite: false,
      loop: false,
      slidesToShow: 2,
      centerPadding: '20px',
      responsive: [
        {
            breakpoint: 1024,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
            }
        },
        {
            breakpoint: 600,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1
            }
        },
        {
            breakpoint: 480,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1
            }
        }

  ]
    }).each(function(){
      var $slider = $(this);

      // Manage focus as slides change
      $slider.on('beforeChange', function(event, slick, currentSlide, nextSlide){
        $('.slider-items > .fusion-column-wrapper .slick-list').attr('aria-live', 'polite');
       // $slider.find('.slick-slide').attr('aria-hidden', true);
           setTimeout(function() {
             $('.slick-slide').attr('role', 'group').removeAttr('tabindex');
            }, 2000);
      });
      $slider.on('afterChange', function(event, slick, currentSlide){
        $(".slider-items > .fusion-column-wrapper .slick-list").attr('aria-live', 'off');
        setTimeout(function(){
        $('.slider-items .slick-active.slick-slide').attr('aria-hidden', false);
        },100);
       // $slider.find('.slick-active').attr('aria-hidden', false);
           setTimeout(function() {
             $('.slick-slide').attr('role', 'group').removeAttr('tabindex');
            }, 2000);
      });
    });

    setTimeout(function() {
     $('.slick-slide').attr('role', 'group').removeAttr('tabindex');
    }, 2000);
   
 $(".plugin-slider > .fusion-column-wrapper").on("init", function(event, slick) {
    $('.plugin-slider > .fusion-column-wrapper').attr({'aria-label': 'Our stories', 'aria-roledescription':'carousel'});
    $('.plugin-slider > .fusion-column-wrapper .slick-slide').attr('aria-roledescription', 'slide');
    $('.plugin-slider > .fusion-column-wrapper .slick-prev .slick-sr-only').text('Previous Slide');
    $('.plugin-slider > .fusion-column-wrapper .slick-next .slick-sr-only').text('Next Slide');
    $('.plugin-slider > .fusion-column-wrapper .slick-slide').each(function(){
      var slideNumText  = 'Slide {current_slide} of {total_slide}';
      let slideNumber = $(this).attr('aria-label').split(' ').pop();
      slideNumText = slideNumText.replace('{current_slide}', slideNumber);
      slideNumText = slideNumText.replace('{total_slide}', slick.slideCount);
     $(this).attr('aria-label', slideNumText)
    });
      $('.plugin-slider .slick-list').attr('aria-live', 'off').attr('aria-relevant', 'additions');
  });
    
  $('.plugin-slider > .fusion-column-wrapper').slick({
    infinite: false,
    slidesToShow: 3, 
    slidesToScroll: 1,
    regionLabel: 'Carousel of Employee quotes',
    centerMode: false,
    swipeToSlide: true,
    draggable: true,
    dots: true,
    arrows: true,
    arrowsPlacement:"afterSlides",
     responsive: [{
        breakpoint: 1200,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3
        }
      }, {
        breakpoint: 1150,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1
        }
      }, {
        breakpoint: 767,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }]
  }).each(function(){
      var $slider_1 = $(this);
      // Manage focus within slider
      $slider_1.on('init', function(event, slick){
     //   $slider_1.find('.slick-active').attr('aria-hidden', false);
      });

      // Manage focus as slides change
      $slider_1.on('beforeChange', function(event, slick, currentSlide, nextSlide){
     //   $slider_1.find('.slick-slide').attr('aria-hidden', true);
     $('.plugin-slider > .fusion-column-wrapper .slick-list').attr('aria-live', 'polite');
           setTimeout(function() {
      //       $('.slick-slide').attr('role', 'group').removeAttr('tabindex');
            }, 2000);
      });
      $slider_1.on('afterChange', function(event, slick, currentSlide){
       // $slider_1.find('.slick-active').attr('aria-hidden', false);
       $('.plugin-slider > .fusion-column-wrapper .slick-list').attr('aria-live', 'off');
           setTimeout(function() {
        //     $('.slick-slide').attr('role', 'group').removeAttr('tabindex');
            }, 2000);
      });
    });
    
      $('.plugin-slider').each(function(){
      var $slider_1 = $(this);
      // Set initial aria-label for each slide
      $slider_1.find('.slick-slide').each(function(index){
     //   $(this).attr('aria-label', 'Slide ' + (index + 1));
      });

      // Update aria-label when slides change
      $slider_1.on('beforeChange', function(event, slick, currentSlide, nextSlide){
       // $slider_1.find('.slick-slide').attr('aria-label', ''); // Clear all aria-labels
      });
      $slider_1.on('afterChange', function(event, slick, currentSlide){
        $slider_1.find('.slick-slide').each(function(index){
        //  $(this).attr('aria-label', 'Slide ' + (index + 1)); // Update aria-labels
        });
      });
    });
  
  //$('.plugin-slider .fusion-column-wrapper').attr('role', 'region').attr('aria-label', 'Slider'); 
    
  }



})(jQuery, window, document);




/**********************************************************************************/
/***************** ADA - Additional Scripting - OUTSIDE OF READY SET *****************/

  /****** Job Results Row ADA fix ******/
function add_column(job_html, job) {
  if ($("body.jobresults")[0]) {
  /** if (window.location.href.indexOf("/job-search-results/") > -1) { **/
    searchReultsTableFix(); 
    return job_html; 
  }
}
CWS.add_filter('after_job_columns', add_column);       
function searchReultsTableFix() {
  setTimeout(function(){
   $('.job .job-innerwrap').each(function() {
     $(this).find('.flex_column.first').removeAttr('role');
     $(this).find('.jobTitle').attr('role','cell');
   });
  },500);
}



$(document).ready(function(){

function stopAllVideos() {
        // Select all iframe videos within the modal body
        $(".modal-body iframe").each(function() {
            var video = $(this)[0]; // Select the current iframe
            var videoSrc = video.src;
            video.src = videoSrc; // Reset the src attribute to stop the video
        });
    }

    // Close Modal
    $(".close, [data-dismiss='modal']").click(function(){
        stopAllVideos(); // Call the function to stop all videos
    });

    // Optional: Close modal when clicking outside of it
    $(window).click(function(event) {
        if ($(event.target).hasClass('modal')) {
            stopAllVideos(); // Call the function to stop all videos
        }
    });

  // Function to pause the video and remove autoplay parameter
function pauseVideoAndRemoveAutoplay(iframe) {
    var src = iframe.attr('src');
    // Remove autoplay=1 from the src
    var newSrc = src.replace(/([&?]autoplay=1)/, '');
    
    // Pause the video by resetting the src
    iframe.attr('src', '').attr('src', newSrc);
}
});

$(document).ready(function() {
    setTimeout(function() {
        // Create the <h2> element with a placeholder for the 's' value
        var jump_faq = $('<a href="#faq" class="jump_faq">Back to FAQs</h2>');
        
        
        var h2Element = $('<h2 id="red">Your search results for: <span class="value"></span></h2>');
        
        // Insert the <h2> element before #posts-container
        h2Element.insertBefore('html[lang="en-US"] #posts-container');
        
        var jump_faq_fr = $('<a href="#faq" class="jump_faq">Retour à la FAQ</h2>');
        
        var h2Element_fr = $('<h2 id="red">Vos résultats de recherche pour :  <span class="value"></span></h2>');
        
        // Insert the <h2> element before #posts-container
        h2Element_fr.insertBefore('html[lang="fr-ca"] #posts-container');
        
        
        // Insert the <h2> element before #posts-container
        jump_faq.insertAfter('html[lang="en-US"] #red');
        jump_faq_fr.insertAfter('html[lang="fr-ca"] #red');
        
        // Function to get URL parameter by name
        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
        
        // Get the 's' value from the URL
        var sValue = getParameterByName('s');
        
        // Update the <span class="value"> with the extracted 's' value
        $('.value').text(sValue);
        $('body.search-results input.fusion-search-submit.searchsubmit').attr('value', 'Search');
        //$('.ot-sdk-show-settings').append('<span class="sr-only"> Opens in modal window</span>') ;
        $('.ot-sdk-footer_btn > a').append('<span class="sr-only"> Opens in modal window</span>');
        $('.ot-sdk-footer_btn > a').attr('role', 'button');
    }, 2000); // Wait 2 seconds before executing this code
});

$(document).ready(function() {
    // Count the number of <article> tags
    var articleCount = $("html[lang='en-US'] .fusion-posts-container article").length;
    // Create a <p> tag with the count and append it
    var pTag = $("<p>").addClass("article_count").text(articleCount + " results found");
    pTag.insertBefore('#posts-container');
    //var pTag = $("<p>").addClass("article_count").text(articleCount + " results found");
    
    var articleCount_fr = $("html[lang='fr-ca'] .fusion-posts-container article").length;
    // Create a <p> tag with the count and append it
    var pTag_fr = $("<p>").addClass("article_count_fr").text(articleCount_fr + " résultats trouvés");
    pTag_fr.insertBefore('#posts-container');
    //var pTag_fr = $("<p>").addClass("article_count_fr").text(articleCount_fr + " résultats trouvés");
    
});

$(document).ready(function() {
    // Loop through each article tag with class fusion-post-grid
    $('.fusion-post-grid').each(function() {
        // Find the href attribute of .fusion-post-title a
        var href = $(this).find('.fusion-post-title a').attr('href');
        
        // Update the text of .fusion-alignleft a with the href
        $(this).find('.fusion-alignleft a').text(href);
    });
    setTimeout(function() {
    $('html[lang="fr-ca"] .page-id-7603 input.fusion-search-submit.searchsubmit').attr('value', 'Rechercher').attr('aria-label', 'Rechercher');
    $('html[lang="fr-ca"] .search-results input.fusion-search-submit.searchsubmit').attr('value', 'Rechercher').attr('aria-label', 'Rechercher');
    $('html[lang="fr-ca"] .search-results .pagination-next .page-text').text('Suivante');
    $('html[lang="fr-ca"] .search-results .pagination-prev .page-text').text('Précédente');
    $('html[lang="fr-ca"] input.s').attr('placeholder', 'Comment pouvons-nous vous aider dans vos recherches?');
    $('a.skip-link.screen-reader-text').text('Skip to main content');
    $('html[lang="fr-ca"] a.skip-link.screen-reader-text').text('Passer au contenu principal');
    $('html[lang="en-US"] .relate-cont').attr('aria-label', 'Related Content');
    $('html[lang="fr-ca"] .relate-cont').attr('aria-label', 'Contenu connexe');
    $('.stick-position img').attr('alt', '');
    }, 2000);
    
});

// jQuery code to add <span class="sr-only">Current Language</span>
$(document).ready(function() {
    // Select the element with class .wpml-ls-current-language .wpml-ls-native
    var languageElement = $('.wpml-ls-current-language .wpml-ls-native');

    // Check if the element exists
    if (languageElement.length > 0) {
        // Get the current text content
        var currentText = languageElement.text().trim();
        
        // Append " current language" and <span class="sr-only">Current Language</span>
        currentText += ' <span class="sr-only">Current Language</span>';
        
        // Update the text content of the element
        languageElement.html(currentText);
    }
});


$(document).ready(function() {
            function updatePlaceholder() {
                if ($(window).width() <= 767) {
                    $('html[lang="fr-ca"] input.s').attr('placeholder', 'Que cherchez-vous?');
                } else {
                    $('html[lang="fr-ca"] input.s').attr('placeholder', 'Comment pouvons-nous vous aider dans vos recherches?');
                }
            }

            // Call the function on page load
            updatePlaceholder();

            // Call the function on window resize
            $(window).resize(function() {
                updatePlaceholder();
            });
        });


$(document).ready(function() {
    // Select the #content element
    var $content = $('.search-results #content');
    
    // Create the new wrapping div
    var $wrapper = $('<div class="first-column"></div>');
    
    // Move all child elements into the new wrapper
    $content.children().each(function() {
        $(this).appendTo($wrapper);
    });
    
    // Prepend the wrapper to the #content
    $content.prepend($wrapper);
    
    $('.first-column').after('<div class="second-column"></div>');
        var resultsBanner = $('#results-banner');
    
    // Append the #results-banner element into the .second-column div
    $('.second-column').append(resultsBanner);
    
    $('.search-results input.s').attr('value', '').attr('placeholder', '');
    setTimeout(function() {
      $('.search-results #red').replaceWith(function() {
          return $("<h1>", {
            class: this.className,
            html: $(this).html()
          });
        });
        
    $('html[lang="fr-ca"] .search-results input.s').attr('value', '').attr('placeholder', '');
    }, 2000);
    

function recalculatePadding() {
        // Iterate through each menu item with the class .menu-item-type-custom
        $('.menu-item-type-custom').each(function() {
            var $menuItem = $(this); // Current menu item
            
            // Get the outer heights of the elements within the current menu item
            var fusionTitleHeight = $menuItem.find('.fusion-title').outerHeight(true); // true includes margin
            var minHghtMenuHeight = $menuItem.find('.min-hght-menu-sub-text').outerHeight(true);
            
            // Calculate total height and add 30px
            var totalHeight = fusionTitleHeight + minHghtMenuHeight + 40; // Add 30px to total height
            
            // Set the padding-top of .mega-sub-menu within the current menu item
            $menuItem.find('.awb-menu__mega-wrap .mega-sub-menu').css('padding-top', totalHeight + 'px');
             $menuItem.find('.awb-menu__mega-wrap .min-hght-menu-sub-text+.mega-sub-menu').css('padding-top', '0' + 'px');
        });
    }

    // Initial calculation
    recalculatePadding();

    // Set up click event on the main menu items
    $('.main-menu-item-class').on('click', function() { // Replace with the actual class of the main menu items
        // Recalculate padding when a main menu item is clicked
        recalculatePadding();
    });

    // Set up resize event to recalculate padding
    $(window).on('resize', function() {
        recalculatePadding();
    });
    
});


$(document).ready(function() {
    // Listen for click or keypress on submenu open buttons
    $('.awb-menu__open-nav-submenu_click').on('click keypress', function(e) {
        // Prevent default action for keypress if it's Enter or Space
        if (e.type === 'keypress' && e.which !== 13 && e.which !== 32) return;

        // Find the parent <li> of the clicked button
        var $parentLi = $(this).closest('li');

        // Remove 'active' class from all <li> elements
        $('#menu-main-menu li').removeClass('active');

        // Add 'active' class only to the clicked button's parent <li>
        $parentLi.addClass('active');

    });
});


/*jQuery(document).ready(function($) {
    function toggleMenuHover() {
        if ($(window).width() >= 1024) {
            // Hover functionality for larger screens
            $('.awb-menu .awb-menu__main-ul li').hover(
                function() {
                    // Add the active class to the parent <li>
                    $(this).addClass('active');
                    
                    // Set the visibility of .awb-menu__mega-wrap to visible
                    $(this).find('.awb-menu__mega-wrap, .awb-menu__sub-ul').css('visibility', 'visible');
                },
                function() {
                    // Hover out: Remove the active class from the parent <li>
                    $(this).removeClass('active');
                    
                    // Set the visibility of .awb-menu__mega-wrap to hidden
                    $(this).find('.awb-menu__mega-wrap, .awb-menu__sub-ul').css('visibility', 'hidden');
                }
            );
        } else {
            // Remove hover events for smaller screens
            $('.awb-menu .awb-menu__main-ul li').off('mouseenter mouseleave');
        }
    }

    // Run on page load
    toggleMenuHover();

    // Re-run on window resize
    $(window).resize(function() {
        toggleMenuHover();
    });
});*/
