// close search box if clicked out of div
/*document.addEventListener("DOMContentLoaded", function() {
    var body = document.body;
    var searchDiv = document.querySelector('.search');

    if (body.classList.contains('search-active')) {
        document.addEventListener('click', function(event) {
          if (!searchDiv.contains(event.target)) {
            body.classList.remove('search-active');
          }
        });
    }
});*/

const buttonClose = document.querySelector(".js-remove-alert-urgent");
if (buttonClose) { buttonClose.focus(); }


$(document).ready(function () {
  $(".js-remove-alert-urgent").on("click", function () {
    $(".emergencynotice").hide();
  });
  /*$(".close-action").on("click", function () {
    $(".information-alert").hide();
  });*/
});

  /*$(".close-action").on("click", function () {
    $(".information-alert").hide();
  });*/

window.onload = function() {
  const urgentButtons = document.querySelectorAll('.js-remove-alert-urgent');
  const emergencyDiv = document.querySelector('.emergencynotice');

  urgentButtons.forEach(button => {
    button.addEventListener('click', () => {
        emergencyDiv.style.display = 'none!important';
    });
  });
};

/*document.addEventListener("DOMContentLoaded", function() {
  const eventIntroductionMeta = document.querySelector('meta[name="EventIntroduction"]');
  if (eventIntroductionMeta) {
    let content = eventIntroductionMeta.getAttribute('content');
    content = content.replace(/<[^>]+>/g,'');
    if (content.length > 100) {
      content = content.substring(0, 200) + '...';
    }
    eventIntroductionMeta.removeAttribute('https:');
    eventIntroductionMeta.setAttribute('content', content);
}  
})*/

/*document.addEventListener("DOMContentLoaded", function() {
let detailsDeg = document.querySelector('#deg-dets'); 
  if (detailsDeg && detailsDeg.hasAttribute('open')) {
    document.addEventListener('click', function (e) { 
      const contentDiv1 = document.querySelector('#deg-dets .content'); 

      if(e.target !== contentDiv1) { 
        detailsDeg.removeAttribute('open'); 
      } 
    });
  }

let detailsArea = document.querySelector('#area-dets'); 
  if (detailsArea && detailsArea.hasAttribute('open')) {
    document.addEventListener('click', function (e) { 
      const contentDiv2 = document.querySelector('#area-dets .content'); 

      if(e.target !== contentDiv2) { 
        detailsArea.removeAttribute('open'); 
      } 
    });
  }

function clickOut() {
let detailsDeg1 = document.querySelector('#deg-dets'); 
  if (detailsDeg1 && detailsDeg1.hasAttribute('open')) {
    document.addEventListener('click', function (e) { 
      const contentDiv1 = document.querySelector('#deg-dets .content'); 

      if(e.target !== contentDiv1) { 
        detailsDeg1.removeAttribute('open'); 
      } 
    });
  }

let detailsArea1 = document.querySelector('#area-dets'); 
  if (detailsArea1 && detailsArea1.hasAttribute('open')) {
    document.addEventListener('click', function (e) { 
      const contentDiv2 = document.querySelector('#area-dets .content'); 

      if(e.target !== contentDiv2) { 
        detailsArea1.removeAttribute('open'); 
      } 
    });
  }
}
document.addEventListener("t4-after-ajax", clickOut);
});*/

//for general course search tab closing
/*function courseSearchTabChange() {
  var degreeButton = document.getElementById("deg-btn");
  var areaButton = document.getElementById("area-btn");

  var degreeDetails = document.getElementById("deg-dets");
  var areaDetails = document.getElementById("area-dets");

  // Event listener for tabs
  if (typeof degreeButton != "undefined" && degreeButton != null) {
    degreeButton.addEventListener("click", function () {
      if (areaDetails.hasAttribute("open") == true) {
        //remove open attribute
        areaDetails.removeAttribute("open");
      } else {
        console.log("");
      }
    });
  }

  if (typeof areaButton != "undefined" && areaButton != null) {
    areaButton.addEventListener("click", function () {
      if (degreeDetails.hasAttribute("open") == true) {
        //remove open attribute
        degreeDetails.removeAttribute("open");
      } else {
        console.log("");
      }
    });
  }
}*/



function checkboxAfter() {
    var checkboxToRemove = document.querySelector('input[type="checkbox"][value="Category>T4_container"]');

    // Check if the checkbox was found
    if (checkboxToRemove) {
        // Remove the checkbox element from its parent div
        checkboxToRemove.parentNode.remove();
    }
}
document.addEventListener("t4-after-ajax", checkboxAfter);


document.addEventListener("DOMContentLoaded", function() {
    var checkboxToRemove = document.querySelector('input[type="checkbox"][value="Category>T4_container"]');

    // Check if the checkbox was found
    if (checkboxToRemove) {
        // Remove the checkbox element from its parent div
        checkboxToRemove.parentNode.remove();
    }
});

/* Remove Quotes Metatag */
// var tables = document.querySelectorAll('table');
var tables = document.querySelectorAll("table:not(.table-force-wrap)");
tables.forEach(function(table) {
  /*var parentDiv = table.closest('div');
  if (parentDiv) {
    parentDiv.style.overflowX = 'auto';
  }*/
  var parentDiv = document.createElement('div');
  parentDiv.appendChild(table.cloneNode(true));
  parentDiv.style.overflowX = 'auto';
  table.parentNode.insertBefore(parentDiv, table);
  table.parentNode.removeChild(table);
});



function updateMetaTagContent() {
  const metaTags = document.querySelector('meta[name="EventIntroduction"]');
  if (metaTags) {
    const content = metaTags.getAttribute('content');
    if (content) {
      metaTags.setAttribute('content', content.replace(/"/g, '"'));
    }
  }
}
updateMetaTagContent();

  const currentYear = new Date().getFullYear();
  
  const spanElement = document.getElementById('copyrightYear');

if(spanElement) {
  spanElement.textContent = currentYear;
}

//JS to resetURL
//document.getElementById("#resetURL").addEventListener("click", resetURLOnFilterUnset);

function resetURLOnFilterUnset(clicked_button) {
  //var clicked_button = $(this).val();
  var clickedButton = clicked_button
    .replaceAll("+", "%2B")
    .replaceAll(",", "%2C")
    .replaceAll("_", "+");

  var currentLocation = location.toString();

  const newUrl = currentLocation.split("?");

  newUrl[1];

  var newloc = newUrl[1].split("&");

  const match = newloc.find((element) => {
    if (element.includes(clickedButton)) {
      return true;
    }
  });

  const removeDataFromURL = currentLocation.replace(match, "");

  const updatedURL = removeDataFromURL.replace("&&", "&");

  const finalURL = updatedURL.replace(/&\s*$/, "");

  window.location.href = finalURL;
}

// Wraps all the table elements in a <div> and adds "c-table" and "hscroll" classes to that <div>.
(function () {
  //const tables = document.querySelectorAll("table");
  const tables = document.querySelectorAll("table:not(.table-force-wrap)");
  const tablesArray = Array.from(tables);

  tables.forEach((table) => {
    //const parent = table.parentNode;
    const wrapper = document.createElement("div");
    wrapper.classList.add("c-table", "hscroll");
    //wrapper.appendChild(table);
    //parent.appendChild(wrapper);
    table.parentNode.insertBefore(wrapper, table)
    wrapper.appendChild(table)
  });
})();



//for general header video play pause
var playButton = document.getElementById("play_button");
var video = document.getElementById("video_lib");

// Event listener for the play/pause button

if (typeof video != "undefined" && video != null) {
  playButton.addEventListener("click", function () {
    if (video.paused == true) {
      // Play the video
      video.play();
      playButton.setAttribute("data-playing", "");
    } else if (video.paused == false) {
      // Pause the video
      video.pause();
      playButton.removeAttribute("data-playing");
    } else {
      console.log("no video");
    }
  });
}


//for grid and list views
function courseSearchViewChange() {
  var listButton = document.getElementById("btn-list-view");
  var gridButton = document.getElementById("btn-grid-view");

  var programView = document.getElementById("content-main");

  // Event listener for the grid list buttons

  if (typeof listButton != "undefined" && listButton != null) {
    listButton.addEventListener("click", function () {
      if (programView.hasAttribute("data-grid") == true) {
        //remove grid attribute
        programView.removeAttribute("data-grid");
      } else {
        //do nothing
      }
    });
  }

  if (typeof gridButton != "undefined" && gridButton != null) {
    gridButton.addEventListener("click", function () {
      if (programView.hasAttribute("data-grid") == false) {
        //add grid attribute
        programView.setAttribute("data-grid", "");
      } else {
        //do nothing
      }
    });
  }
}


/* automated faculty list order js */
/* 
$(".auto-list-1col-group .auto-list-1col, .auto-list-2col-group .auto-list-2col, .auto-list-only-group .auto-list-only").each(function() {
  $(this).find('div.staff').sort(function(a, b) {
    var aText = $(a).text(),
      bText = $(b).text();
    return aText < bText ? -1 : aText > bText ? 1 : 0;
  }).appendTo(this);
});
*/


           









/* Accordion Javascript */
document.addEventListener('DOMContentLoaded', function () {
    const searchResultsDiv = document.querySelector('#search-results');

    if (searchResultsDiv) {
        searchResultsDiv.addEventListener('click', function (event) {
            const trigger = event.target.closest('.umass-course-accordion-title');

            if (trigger) {
                const parentRow = trigger.closest('.umass-course-accordion-header');
                const isOpen = parentRow.classList.toggle('open');
                let nextRow = parentRow.nextElementSibling;

                const allAccordionContent = document.querySelectorAll('.umass-course-accordion-content');
                allAccordionContent.forEach(row => row.classList.remove('last-open'));

                let lastVisibleRow = null;

                while (nextRow && nextRow.classList.contains('umass-course-accordion-content')) {
                    const contentWrapper = nextRow.querySelector('.accordion-content-wrapper');  

                    if (isOpen) {
                        nextRow.style.display = 'table-row';  
                        expandAccordion(contentWrapper); 

                        lastVisibleRow = nextRow;
                    } else {

                        collapseAccordion(contentWrapper, nextRow);   
                    }
                    nextRow = nextRow.nextElementSibling;
                }

                if (lastVisibleRow) {
                    lastVisibleRow.classList.add('last-open');
                }
            }
        });
    }

    function expandAccordion(element) {
        element.style.height = '0'; 
        element.style.overflow = 'hidden';  
        element.style.opacity = '1';  

        const fullHeight = element.scrollHeight + 'px';

        element.offsetHeight;

        element.style.transition = 'height 600ms ease-out, opacity 600ms ease-out';
        element.style.height = fullHeight; 

        element.addEventListener('transitionend', () => {
            element.style.height = 'auto'; 
            element.style.overflow = '';
        }, { once: true });
    }


    function collapseAccordion(element, nextRow) {

        const startHeight = element.scrollHeight + 'px';

        element.style.height = startHeight;

        element.offsetHeight;

        requestAnimationFrame(() => {
            element.style.transition = 'height 600ms ease-out, opacity 300ms ease-out';
            element.style.height = '0px'; 
            element.style.opacity = '0'; 
        });

        element.addEventListener('transitionend', () => {
            nextRow.style.display = 'none'; 
            element.style.opacity = '1';  
        }, { once: true });
    }
});


/* link click to show/hide divs */

$(document).ready(function() {
    // When any link is clicked
    $('.social-media-directory-link').click(function(event) {
        event.preventDefault(); // Prevent default link behavior
        
        // Hide all divs
        $('.social-media-content').hide();
        
        // Show the corresponding div based on the link clicked
        var targetDiv = $(this).data('target');
        $(targetDiv).show();
    });
});


document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('a[href]').forEach(link => {
    link.addEventListener('click', event => {
      
      // Extract the number after 'd.en.' in the href
      const href = link.getAttribute('href');
      const match = href.match(/d\.en\.(\d+)/);

      if (match && match[1]) {
        const elementId = match[1];
        const targetElement = document.getElementById(elementId);

        if (targetElement) {
          // Add the 'open' property
          targetElement.setAttribute('open', 'true');
        } else {
          console.warn(`Element with ID ${elementId} not found.`);
        }
      } else {
        console.warn('No valid ID found in href:', href);
      }
    });
  });
});


