jQuery(document).ready(function ($){
function replacePlaceholder(str, num){
return str.replace(/%d/g, num);
}
function initializeForm(formSelector){
const $form=$(formSelector);
$form.attr("novalidate", true);
const $submitButton=$form.find(".rne-submit-button");
const $formSteps=$form.find(".form-step");
const hasSteps=$formSteps.length > 0;
let currentStep=1;
const totalSteps=hasSteps ? $formSteps.length:1;
let $captchaInput=$form.find('input[name="captcha_at_solution"]');
if(!$captchaInput.length){
$captchaInput=$("<input>", {
type: "hidden",
name: "captcha_at_solution"
}).appendTo($form);
}
function fetchCaptcha(){
return KROT.getSolution().then((sol)=> {
$captchaInput.val(JSON.stringify(sol));
return sol;
});
}
async function ensureFreshCaptcha(){
try {
const cur=JSON.parse($captchaInput.val()||"{}");
if(!cur.expires||Date.now() > cur.expires - 15_000){
return fetchCaptcha();
}
return cur;
} catch (_){
return fetchCaptcha();
}}
let captchaTimer=null;
function startCaptchaWatchdog(sol){
clearTimeout(captchaTimer);
if(!sol.expires) return;
const delay=Math.max(sol.expires - Date.now() - 15_000, 30_000);
captchaTimer=setTimeout(async ()=> {
const newSol=await ensureFreshCaptcha();
startCaptchaWatchdog(newSol);
}, delay);
}
$form.one("focusin", ":input:not([type='hidden']):not(:disabled)", async ()=> {
try {
const sol=await fetchCaptcha();
startCaptchaWatchdog(sol);
} catch (err){
console.error("captcha bootstrap failed", err);
}});
$form.on("remove", ()=> clearTimeout(captchaTimer));
function validateCheckbox($input){
const $field=$input.closest(".form-item");
const $errorMessage=$field.find(".error-message");
$errorMessage.text("").hide();
$field.removeClass("not-valid is-valid");
if($input.closest(".rne-multi-checkbox-group").length){
return validateMultiCheckbox($input.closest(".rne-multi-checkbox-group"));
}else{
return validateSingleCheckbox($input);
}}
function validateSingleCheckbox($input){
const $field=$input.closest(".form-item");
const $errorMessage=$field.find(".error-message");
const showErrors=$field.data("show-errors")===true;
if($input.prop("required")&&!$input.prop("checked")){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.requiredField).show();
}
$field.addClass("not-valid");
return false;
}
$field.addClass("is-valid");
return true;
}
function validateMultiCheckbox($group){
const $field=$group.closest(".form-item");
const $errorMessage=$field.find(".error-message");
const showErrors=$field.data("show-errors")===true;
const checkedCount=$group.find('input[type="checkbox"]:checked').length;
const maxSelections=$field.data("max-selections")||Infinity;
const minSelections=$field.data("required")===true ? 1:0;
$field.removeClass("not-valid is-valid");
$errorMessage.text("").hide();
if(checkedCount < minSelections){
if(showErrors){
const message=replacePlaceholder(window.rne_translations.forms.minSelections, minSelections);
$errorMessage.text(message).show();
}
$field.addClass("not-valid");
return false;
}
else if(checkedCount > maxSelections){
if(showErrors){
const message=replacePlaceholder(window.rne_translations.forms.maxSelections, maxSelections);
$errorMessage.text(message).show();
}
$field.addClass("not-valid");
return false;
}
$field.addClass("is-valid");
return true;
}
function validateSelect($input){
const $field=$input.closest(".form-item");
const $errorMessage=$field.find(".error-message");
const showErrors=$field.data("show-errors")===true;
const $selectTrigger=$field.find(".rne-select-trigger");
$selectTrigger.removeClass("not-valid is-valid");
$errorMessage.text("").hide();
const value=$input.val();
if($input.prop("required")&&!value){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.requiredField).show();
}
$selectTrigger.addClass("not-valid");
return false;
}
$selectTrigger.addClass("is-valid");
return true;
}
function validateField($input){
const $field=$input.closest(".form-item");
const value=$input.val();
const $errorMessage=$field.find(".error-message");
$errorMessage.text("").hide();
$field.removeClass("not-valid is-valid");
const showErrors=$field.data("show-errors")===true;
if($input.attr("type")==="checkbox"){
return validateCheckbox($input);
}
if($input.attr("type")==="hidden"&&$input.closest(".rne-select-container").length){
return validateSelect($input);
}
if($input.prop("required")&&!value){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.requiredField).show();
}
$field.addClass("not-valid");
return false;
}else if(value){
switch ($input.attr("type")){
case "email":
if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidEmail).show();
}
$field.addClass("not-valid");
return false;
}
break;
case "number":
if(!/^\d+$/.test(value)){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidNumber).show();
}
$field.addClass("not-valid");
return false;
}
break;
case "url":
try {
const url=value.startsWith("http://")||value.startsWith("https://") ? value:"http://" + value;
const parsedUrl=new URL(url);
const hostname=parsedUrl.hostname;
if(!/^.+\..+$/.test(hostname)){
throw new Error("Hostname must contain at least one dot with characters on both sides.");
}} catch (error){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidUrl).show();
}
$field.addClass("not-valid");
return false;
}
break;
case "text":
if($input.hasClass("air-datepicker-input")){
const dateFormat=$input.data("date-format")||"MM/dd/yyyy";
let datePattern;
let dayIndex, monthIndex, yearIndex;
switch (dateFormat){
case "dd.MM.yyyy":
datePattern=/^(\d{2})\.(\d{2})\.(\d{4})$/;
dayIndex=1;
monthIndex=2;
yearIndex=3;
break;
case "MM/dd/yyyy":
datePattern=/^(\d{2})\/(\d{2})\/(\d{4})$/;
monthIndex=1;
dayIndex=2;
yearIndex=3;
break;
default:
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidDate).show();
}
$field.addClass("not-valid");
return false;
}
const dateParts=value.match(datePattern);
if(!dateParts){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidDate).show();
}
$field.addClass("not-valid");
return false;
}
const day=parseInt(dateParts[dayIndex], 10);
const month=parseInt(dateParts[monthIndex], 10) - 1;
const year=parseInt(dateParts[yearIndex], 10);
const date=new Date(year, month, day);
if(date.getFullYear()!==year||date.getMonth()!==month||date.getDate()!==day){
if(showErrors){
$errorMessage.text(window.rne_translations.forms.invalidDate).show();
}
$field.addClass("not-valid");
return false;
}}
break;
}
$field.addClass("is-valid");
}
return true;
}
function updateConditionalFields(){
$form.find("[data-condition]").each(function (){
const $field=$(this);
const conditions=$field.data("condition");
const conditionsArray=Array.isArray(conditions) ? conditions:[conditions];
const show=conditionsArray.every(function (condition){
const $triggerField=$form.find('[name="' + condition.field + '"]');
let triggerValue;
if($triggerField.attr("type")==="checkbox"){
triggerValue=$triggerField.prop("checked");
}else if($triggerField.attr("type")==="radio"){
triggerValue=$triggerField.filter(":checked").val();
}else{
triggerValue=$triggerField.val();
}
return Array.isArray(condition.value) ? condition.value.includes(triggerValue):triggerValue==condition.value;
});
$field.toggle(show);
updateFieldRequired($field, show);
if(show){
initializeDatePickers();
}});
}
function updateFieldRequired($field, show){
const $inputs=$field.find("input, select, textarea");
const isRequired=$field.data("required")==="conditional" ? show:$field.data("required")===true;
$inputs.prop("required", isRequired);
const $label=$field.find("label");
if(isRequired){
if(!$label.find(".required-asterisk").length){
$label.append('<span class="required-asterisk">*</span>');
}}else{
$label.find(".required-asterisk").remove();
}}
function validateForm(){
let isValid=true;
const $fieldsToValidate=hasSteps ? $form.find(`.form-step[data-step="${currentStep}"] :input:visible`):$form.find(":input:visible");
$fieldsToValidate.each(function (){
if(!validateField($(this))){
isValid=false;
}});
return isValid;
}
function updateStepperUI(){
if(!hasSteps) return;
$(".step").removeClass("active");
$(`.step[data-step="${currentStep}"]`).addClass("active");
$form.find(".prev-step").toggle(currentStep > 1);
$form.find(".next-step").toggle(currentStep < totalSteps);
$submitButton.toggle(currentStep===totalSteps);
}
function goToStep(step, direction){
if(!hasSteps) return;
const $currentStep=$formSteps.filter(".active");
const $targetStep=$formSteps.filter(`[data-step="${step}"]`);
const $stepperOverview=$form.find(".stepper.container");
$currentStep.removeClass("active");
$targetStep.addClass("active");
if(direction==="forward"){
$currentStep.addClass("previous").removeClass("next");
$targetStep.addClass("next").removeClass("previous");
$stepperOverview.find(`.step[data-step="${currentStep}"]`).addClass("done");
}else{
$currentStep.addClass("next").removeClass("previous");
$targetStep.addClass("previous").removeClass("next");
$stepperOverview.find(`.step[data-step="${step}"]`).removeClass("done");
}
$targetStep[0].offsetWidth;
$currentStep.removeClass("previous next");
$targetStep.removeClass("previous next");
currentStep=step;
updateStepperUI();
const SCROLL_TOP_OFFSET=340;
$("html, body").animate({
scrollTop: $(".stepper.container").offset().top - SCROLL_TOP_OFFSET
},
500
);
const $firstInput=$targetStep.find("input, select, textarea").filter(":visible").first();
if($firstInput.length){
$firstInput.focus();
}}
function setLoadingState($button, isLoading){
if(isLoading){
$button.addClass("btn-loading").prop("disabled", true).find(".btn-text").after('<span class="spinner"></span>');
}else{
$button.removeClass("btn-loading").prop("disabled", false).find(".spinner").remove();
}}
const NAV_SVG=`
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M1.64592 4.64592C1.69236 4.59935 1.74754 4.56241 1.80828 4.5372C1.86903 4.512 1.93415 4.49902 1.99992 4.49902C2.06568 4.49902 2.13081 4.512 2.19155 4.5372C2.2523 4.56241 2.30747 4.59935 2.35392 4.64592L7.99992 10.2929L13.6459 4.64592C13.6924 4.59943 13.7476 4.56255 13.8083 4.53739C13.8691 4.51223 13.9342 4.49929 13.9999 4.49929C14.0657 4.49929 14.1308 4.51223 14.1915 4.53739C14.2522 4.56255 14.3074 4.59943 14.3539 4.64592C14.4004 4.6924 14.4373 4.74759 14.4624 4.80833C14.4876 4.86907 14.5005 4.93417 14.5005 4.99992C14.5005 5.06566 14.4876 5.13076 14.4624 5.1915C14.4373 5.25224 14.4004 5.30743 14.3539 5.35392L8.35392 11.3539C8.30747 11.4005 8.2523 11.4374 8.19155 11.4626C8.13081 11.4878 8.06568 11.5008 7.99992 11.5008C7.93415 11.5008 7.86903 11.4878 7.80828 11.4626C7.74754 11.4374 7.69236 11.4005 7.64592 11.3539L1.64592 5.35392C1.59935 5.30747 1.56241 5.2523 1.5372 5.19155C1.512 5.13081 1.49902 5.06568 1.49902 4.99992C1.49902 4.93415 1.512 4.86903 1.5372 4.80828C1.56241 4.74754 1.59935 4.69236 1.64592 4.64592Z" fill="#1A1A1A"/>
</svg>
`;
const isMobile=document.body.classList.contains("touch-device");
function initializeDatePickers(){
const $form=$("form");
$form.find("input.air-datepicker-input").each(function (){
if(this._datepicker){
this._datepicker.destroy();
}
const $input=$(this);
const minDateStr=$input.data("min-date");
const maxDateStr=$input.data("max-date");
const config={
isMobile: isMobile,
autoClose: true,
prevHtml: NAV_SVG,
nextHtml: NAV_SVG,
onSelect: ({ formattedDate })=> {
$input.val(formattedDate);
validateField($input);
const changeEvent=new Event("change", { bubbles: true });
$input[0].dispatchEvent(changeEvent);
}};
if(minDateStr){
if(minDateStr==="today"){
config.minDate=new Date();
}else{
config.minDate=new Date(minDateStr);
}}
if(maxDateStr){
if(maxDateStr==="today"){
config.maxDate=new Date();
}else{
config.maxDate=new Date(maxDateStr);
}}
this._datepicker=window.initializeLocalizedDatepicker(this, config);
});
}
function attachDatepickerButtonListeners(){
$form.find(".datepicker-toggle").each(function (){
$(this).on("click", function (){
var $wrapper=$(this).closest(".datepicker-wrapper");
var $input=$wrapper.find("input");
if($input.length > 0&&$input[0]._datepicker){
$input[0].focus();
}});
});
}
function initializeEvents(){
$form.on("change", "input, select, textarea", function (){
updateConditionalFields();
if($(this).attr("type")==="checkbox"){
validateCheckbox($(this));
}});
$form.on("rne-select-change", function (e){
const $hiddenInput=$(e.target);
validateSelect($hiddenInput);
});
$form.on("blur", ":input", function (){
validateField($(this));
});
if(hasSteps){
$form.on("click", ".next-step", function (e){
e.preventDefault();
if(validateForm()&&currentStep < totalSteps){
goToStep(currentStep + 1, "forward");
}});
$form.on("click", ".prev-step", function (e){
e.preventDefault();
if(currentStep > 1){
goToStep(currentStep - 1, "backward");
}});
}
$form.on("submit", async function (e){
e.preventDefault();
updateConditionalFields();
$form.find(".rne-select-container input[type='hidden']").each(function (){
validateSelect($(this));
});
if(validateForm()){
setLoadingState($submitButton, true);
try {
const sol=await ensureFreshCaptcha();
if(!captchaTimer) startCaptchaWatchdog(sol);
} catch (err){
console.error("Captcha refresh failed", err);
setLoadingState($submitButton, false);
return;
}
let formData=$form.serialize();
formData +="&action=handle_form";
$form.find(".form-error").text("").hide();
$.post(window.rne_translations.common.ajax_url, formData, function (response){
$form.find(".form-errors").remove();
if(response.success){
$form.find(".form-error").text("").hide();
const isEventSuggestionForm=$form.hasClass("form-event-suggestion");
const isNewsletterSubscribeForm=$form.attr("id")==="form_newsletter_subscribe";
const isNewsletterUnsubscribeForm=$form.attr("id")==="form_newsletter_unsubscribe";
if(isNewsletterSubscribeForm){
$form.siblings(".form-description").remove();
$form.replaceWith(response.data.html);
}
if(isNewsletterUnsubscribeForm){
$form.siblings(".form-description").remove();
$form.replaceWith(response.data.html);
}
if(isEventSuggestionForm){
$(".entry-title").remove();
$form.closest('[data-module="form-event-suggestion"]').replaceWith(response.data.html);
window.scrollTo({ top: 0, behavior: "smooth" });
}else{
$form.replaceWith(response.data.html);
}}else{
if(response.data.form_error){
$form.find(".form-error").text(response.data.form_error).show();
fetchCaptcha().catch((err)=> console.error("Captcha retrieval error:", err));
}
if(response.data.errors){
$.each(response.data.errors, function (field, error){
$form.find(`#${field}-error`).text(error).show();
$form.find(`#${field}`).closest(".form-item").removeClass("is-valid").addClass("not-valid");
});
}}
})
.fail(function (){
$form.append('<div class="form-error">Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.</div>');
})
.always(function (){
setLoadingState($submitButton, false);
});
}});
}
updateConditionalFields();
if(hasSteps){
updateStepperUI();
}else{
$submitButton.show();
}
initializeEvents();
initializeDatePickers();
attachDatepickerButtonListeners();
}
$(".rne-form").each(function (){
initializeForm("#" + $(this).attr("id"));
var $form=$(this);
var actionValue=$form.find('input[name="form_action"]').val();
if(actionValue){
$.post(window.rne_translations.common.ajax_url,
{
action: "generate_form_nonce",
nonce_action: actionValue
},
function (response){
if(response.success){
$form.find(".nonce-field").html('<input type="hidden" name="security" value="' + response.data.nonce + '">');
}else{
console.error("Failed to fetch nonce for action: " + actionValue);
}}
);
}});
$(".rne-form").on("keydown", "input", function (event){
if(event.keyCode===13||event.key==="Enter"){
event.preventDefault();
return false;
}});
const customSelectTriggers=document.querySelectorAll(".rne-select-trigger");
customSelectTriggers.forEach((trigger)=> {
const container=trigger.closest(".rne-select-container");
const listbox=container.querySelector('[role="listbox"]');
const hiddenInput=container.querySelector('input[type="hidden"]');
const options=Array.from(listbox.querySelectorAll('[role="option"]'));
let expanded=false;
function openListbox(){
listbox.hidden=false;
trigger.setAttribute("aria-expanded", "true");
expanded=true;
trigger.focus();
}
function closeListbox(){
listbox.hidden=true;
trigger.setAttribute("aria-expanded", "false");
expanded=false;
}
function selectOption(option){
const value=option.getAttribute("data-value");
const label=option.textContent;
hiddenInput.value=value;
container.querySelector(".rne-select-selected-value").textContent=label;
options.forEach((opt)=> {
opt.classList.remove("selected");
opt.setAttribute("aria-selected", "false");
});
option.classList.add("selected");
option.setAttribute("aria-selected", "true");
closeListbox();
const event=new CustomEvent("rne-select-change", {
bubbles: true,
detail: { value }});
hiddenInput.dispatchEvent(event);
}
trigger.addEventListener("click", (e)=> {
e.preventDefault();
expanded ? closeListbox():openListbox();
});
document.addEventListener("click", (e)=> {
if(!container.contains(e.target)&&expanded){
closeListbox();
}});
trigger.addEventListener("keydown", (e)=> {
const currentIndex=options.findIndex((opt)=> opt.classList.contains("selected"));
let newIndex=currentIndex;
if(e.key==="ArrowDown"){
e.preventDefault();
if(!expanded){
openListbox();
}else{
newIndex=currentIndex + 1 < options.length ? currentIndex + 1:0;
options[newIndex].focus();
}}else if(e.key==="ArrowUp"){
e.preventDefault();
if(!expanded){
openListbox();
}else{
newIndex=currentIndex - 1 >=0 ? currentIndex - 1:options.length - 1;
options[newIndex].focus();
}}else if(e.key==="Enter"||e.key===" "){
e.preventDefault();
if(!expanded){
openListbox();
}else if(currentIndex > -1){
selectOption(options[currentIndex]);
}}else if(e.key==="Escape"){
e.preventDefault();
if(expanded) closeListbox();
}});
options.forEach((option, index)=> {
option.setAttribute("tabindex", "-1");
option.addEventListener("click", ()=> selectOption(option));
option.addEventListener("keydown", (e)=> {
if(e.key==="Enter"||e.key===" "){
e.preventDefault();
selectOption(option);
}else if(e.key==="Escape"){
e.preventDefault();
closeListbox();
}else if(e.key==="ArrowDown"){
e.preventDefault();
const nextIndex=index + 1 < options.length ? index + 1:0;
options[nextIndex].focus();
}else if(e.key==="ArrowUp"){
e.preventDefault();
const prevIndex=index - 1 >=0 ? index - 1:options.length - 1;
options[prevIndex].focus();
}});
});
});
});
document.addEventListener("DOMContentLoaded", function (){
Array.prototype.forEach.call(document.querySelectorAll(".accordion__content"), (el)=> new SimpleBar(el));
function toggleAccordion(icon){
const header=icon.closest(".accordion__header");
if(!header) return;
const isExpanded=header.getAttribute("aria-expanded")==="true";
const contentId=header.getAttribute("aria-controls");
const content=document.getElementById(contentId);
if(!content) return;
if(isExpanded){
header.setAttribute("aria-expanded", "false");
content.classList.remove("show");
content.hidden=true;
icon.setAttribute("aria-label", "Expand");
}else{
header.setAttribute("aria-expanded", "true");
content.classList.add("show");
content.hidden=false;
icon.setAttribute("aria-label", "Collapse");
}}
function closeAllAccordions(container){
if(!container) return;
const expandedHeaders=container.querySelectorAll('.accordion__header[aria-expanded="true"]');
expandedHeaders.forEach(header=> {
const icon=header.querySelector('.accordion__icon');
if(icon){
toggleAccordion(icon);
}});
}
const accordionIcons=document.querySelectorAll(".accordion__icon");
accordionIcons.forEach(function (icon){
icon.addEventListener("click", function (e){
e.stopPropagation();
toggleAccordion(icon);
});
icon.addEventListener("keydown", function (e){
if(e.key==="Enter"||e.key===" "){
e.preventDefault();
toggleAccordion(icon);
}});
});
const resetButton=document.getElementById("media-filter__reset");
if(resetButton){
resetButton.addEventListener("click", function (){
const container=document.querySelector(".media-filter-container");
if(container){
const checkboxes=container.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function (checkbox){
checkbox.checked=false;
});
}});
resetButton.addEventListener("keydown", function (e){
if(e.key==="Enter"||e.key===" "){
e.preventDefault();
resetButton.click();
}});
}
window.closeAllAccordions=closeAllAccordions;
window.toggleAccordion=toggleAccordion;
});
class ContentFilter {
constructor(options){
this.options=options;
this.root=options.root||null;
this.data=options.data||[];
this.hasMediaPlayers=options.hasMediaPlayers||false;
this.templates=options.templates||{};
this.state={
currentPage: 1,
itemsPerPage: options.itemsPerPage||10,
isMobileFilterOpen: false
};
this.totalItems=options.totalItems||(this.data ? this.data.length:0);
if(!this.root){
return;
}
this.indices={
titleIndex: new Map(),
dateIndex: new Map(),
sdgIndex: new Map(),
typeIndex: new Map(),
termIndex: new Map(),
eventCityIndex: new Map(),
postTermIndex: new Map(),
postCategoryIndex: new Map()
};
this.init();
}
init(){
this.cacheElements();
this.bindEvents();
this.buildIndices();
this.initTemplates();
if(this.totalItems > 0){
this.updatePaginationControls(this.totalItems);
}
this.updateResetButtonVisibility();
this.observeMobileFilterOverlay();
}
cacheElements(){
this.elements={
itemContainer: document.querySelector(".filtered-items"),
archiveFilters: document.querySelectorAll(".accordion__item"),
searchInput: document.getElementById("item_text_search"),
startDateInput: document.getElementById("start_date_input"),
startDateInputMobile: document.getElementById("start_date_mobile_input"),
endDateInput: document.getElementById("end_date_input"),
endDateInputMobile: document.getElementById("end_date_mobile_input"),
sortBySelect: document.getElementById("sort_by"),
sdgCheckboxes: document.querySelectorAll('input[name="sdg_terms[]"]'),
eventCityCheckboxes: document.querySelectorAll('input[name="event_cities[]"]'),
postTypeCheckboxes: document.querySelectorAll('input[name="post_terms[]"]'),
postTypeButtons: document.querySelectorAll(".post-type-button"),
postTypeDefaultButton: document.querySelector(".post-type-button[data-value='all']"),
documentTermCheckboxes: document.querySelectorAll(".term-checkbox input[type='checkbox']"),
documentTypeCheckboxes: document.querySelectorAll('input[name="pdf"], input[name="audio"], input[name="video"]'),
filterResetButtons: document.querySelectorAll(".filter-reset-button"),
paginationContainer: document.getElementById("pagination-controls"),
mobileFilterOverlay: document.querySelector(".mobile-filter-overlay"),
applyFilterButton: document.getElementById("apply-filter-button"),
filterHeadingText: document.querySelector(".filter-heading.item-filter-text"),
postCategoryButtons: document.querySelectorAll(".post-category-button"),
postCategoryDefaultButton: document.querySelector(".post-category-button[data-value='meldung']")
};}
debounce(func, delay){
let timeoutId;
return (...args)=> {
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId=setTimeout(()=> {
func.apply(this, args);
}, delay);
};}
bindEvents(){
if(this.elements.mobileFilterOverlay){
window.bindMobileFilterMenuEvents(this.root, this.elements.mobileFilterOverlay);
}
if(!this.data){
return;
}
this.debouncedHandleFilterChange=this.debounce(()=> this.handleFilterChange(), 300);
if(this.elements.searchInput){
this.elements.searchInput.addEventListener("input", this.debouncedHandleFilterChange);
}
if(this.elements.startDateInput){
this.elements.startDateInput.addEventListener("change", ()=> this.handleFilterChange());
}
if(this.elements.startDateInputMobile){
this.elements.startDateInputMobile.addEventListener("change", ()=> this.handleFilterChange());
}
if(this.elements.endDateInput){
this.elements.endDateInput.addEventListener("change", ()=> this.handleFilterChange());
}
if(this.elements.endDateInputMobile){
this.elements.endDateInputMobile.addEventListener("change", ()=> this.handleFilterChange());
}
if(this.elements.sdgCheckboxes){
this.elements.sdgCheckboxes.forEach((cb)=> cb.addEventListener("change", ()=> this.handleFilterChange()));
}
if(this.elements.eventCityCheckboxes){
this.elements.eventCityCheckboxes.forEach((cb)=> cb.addEventListener("change", ()=> this.handleFilterChange()));
}
if(this.elements.postTypeCheckboxes){
this.elements.postTypeCheckboxes.forEach((cb)=> cb.addEventListener("change", ()=> this.handleFilterChange()));
}
if(this.elements.sortBySelect){
this.elements.sortBySelect.addEventListener("rne-select-change", ()=> this.handleFilterChange());
}
if(this.elements.postTypeButtons){
this.elements.postTypeButtons.forEach((btn)=> {
btn.addEventListener("click", ()=> {
this.elements.postTypeButtons.forEach((b)=> b.classList.remove("embla__slide--active"));
btn.classList.add("embla__slide--active");
const filterValue=btn.dataset.value;
const filterFunctions={
newsletter_post: ()=> false,
all: (item)=> item.getAttribute("data-value")==="sdgs",
newsposts: (item)=> item.getAttribute("data-value")==="newsposts",
project: (item)=> item.getAttribute("data-value")==="sdgs",
event: (item)=> ["sdgs", "event"].includes(item.getAttribute("data-value")),
default: (item)=> {
const itemValue=item.getAttribute("data-value");
return !itemValue||itemValue===filterValue;
}};
if(filterValue==="newsletter_post"&&this.elements.filterHeadingText){
this.elements.filterHeadingText.style.display="none";
}else{
this.elements.filterHeadingText.style.display="block";
}
const filterFunction=filterFunctions[filterValue]||filterFunctions.default;
if(this.elements.archiveFilters){
this.elements.archiveFilters.forEach((item)=> {
item.style.display=filterFunction(item) ? "block":"none";
});
}
this.handleFilterChange();
});
});
}
if(this.elements.postCategoryButtons){
this.elements.postCategoryButtons.forEach((btn)=> {
btn.addEventListener("click", ()=> {
this.elements.postCategoryButtons.forEach((b)=> b.classList.remove("embla__slide--active"));
btn.classList.add("embla__slide--active");
this.handleFilterChange();
});
});
}
if(this.elements.documentTypeCheckboxes){
this.elements.documentTypeCheckboxes.forEach((cb)=> {
cb.addEventListener("change", ()=> {
if(!cb.checked){
const mediaType=cb.name;
this.elements.documentTermCheckboxes.forEach((termCb)=> {
if(termCb.name.startsWith(mediaType)){
termCb.checked=false;
}});
}
if(cb.checked){
const mediaType=cb.name;
this.elements.documentTermCheckboxes.forEach((termCb)=> {
if(termCb.name.startsWith(mediaType)){
termCb.checked=true;
}});
}
this.handleFilterChange();
});
});
}
if(this.elements.postTypeCheckboxes){
this.elements.postTypeCheckboxes.forEach((cb)=> {
cb.addEventListener("change", ()=> {
this.handleFilterChange();
});
});
}
if(this.elements.documentTermCheckboxes){
this.elements.documentTermCheckboxes.forEach((cb)=> {
cb.addEventListener("change", ()=> {
const mediaType=cb.name.split("_")[0];
const mediaTypeCheckbox=document.querySelector(`input[name="${mediaType}"]`);
if(cb.checked){
if(mediaTypeCheckbox&&!mediaTypeCheckbox.checked){
mediaTypeCheckbox.checked=true;
}}
this.handleFilterChange();
});
});
}
if(this.elements.filterResetButtons){
this.elements.filterResetButtons.forEach((btn)=> btn.addEventListener("click", ()=> this.resetFilters()));
}
if(this.elements.applyFilterButton){
this.elements.applyFilterButton.addEventListener("click", ()=> {
this.resetPageAndFilter();
if(this.elements.mobileFilterOverlay){
this.elements.mobileFilterOverlay.setAttribute("data-open", "false");
document.body.style.overflow="auto";
this.scrollToMediaItems();
}});
}}
observeMobileFilterOverlay(){
if(this.elements.mobileFilterOverlay){
const observer=new MutationObserver((mutations)=> {
mutations.forEach((mutation)=> {
if(mutation.attributeName==="data-open"){
const dataOpen=mutation.target.getAttribute("data-open");
this.state.isMobileFilterOpen=dataOpen==="true";
}});
});
observer.observe(this.elements.mobileFilterOverlay, { attributes: true, attributeFilter: ["data-open"] });
}}
handleFilterChange(){
if(!this.state.isMobileFilterOpen){
this.resetPageAndFilter();
}}
resetPageAndFilter(){
this.state.currentPage=1;
this.filterAndUpdateUI();
this.updateResetButtonVisibility();
}
resetSdgCheckboxes(){
if(this.elements.sdgCheckboxes){
this.elements.sdgCheckboxes.forEach((cb)=> (cb.checked=false));
}}
resetPostTypeCheckboxes(){
if(this.elements.postTypeCheckboxes){
this.elements.postTypeCheckboxes.forEach((cb)=> (cb.checked=false));
}}
resetEventCityCheckboxes(){
if(this.elements.eventCityCheckboxes){
this.elements.eventCityCheckboxes.forEach((cb)=> (cb.checked=false));
}}
resetDocumentTermCheckboxes(){
if(this.elements.documentTermCheckboxes){
this.elements.documentTermCheckboxes.forEach((cb)=> (cb.checked=false));
}}
resetDocumentTypeCheckboxes(){
if(this.elements.documentTypeCheckboxes){
this.elements.documentTypeCheckboxes.forEach((cb)=> (cb.checked=false));
}}
resetPostTypeButtons(){
if(this.elements.postTypeButtons){
this.elements.postTypeButtons.forEach((btn)=> btn.classList.remove("embla__slide--active"));
if(this.elements.postTypeDefaultButton){
this.elements.postTypeDefaultButton.classList.add("embla__slide--active");
}}
}
resetPostCategoryButtons(){
if(this.elements.postCategoryButtons){
this.elements.postCategoryButtons.forEach((btn)=> btn.classList.remove("embla__slide--active"));
if(this.elements.postCategoryDefaultButton){
this.elements.postCategoryDefaultButton.classList.add("embla__slide--active");
}}
}
resetSearchInput(){
if(this.elements.searchInput){
this.elements.searchInput.value="";
}}
resetStartDateInputs(){
if(this.elements.startDateInput){
this.elements.startDateInput.value="";
}
if(this.elements.startDateInputMobile){
this.elements.startDateInputMobile.value="";
}}
resetEndDateInputs(){
if(this.elements.endDateInput){
this.elements.endDateInput.value="";
}
if(this.elements.endDateInputMobile){
this.elements.endDateInputMobile.value="";
}}
resetFilters(){
console.log("RESET CLICKED");
this.resetSearchInput();
this.resetStartDateInputs();
this.resetEndDateInputs();
this.resetSdgCheckboxes();
this.resetPostTypeCheckboxes();
this.resetEventCityCheckboxes();
this.resetDocumentTermCheckboxes();
this.resetDocumentTypeCheckboxes();
this.resetPostCategoryButtons();
if(!this.state.isMobileFilterOpen){
this.resetPageAndFilter();
}else{
this.updateResetButtonVisibility();
}}
getFilterState(){
const selectedTerms={};
if(this.elements.documentTermCheckboxes){
this.elements.documentTermCheckboxes.forEach((cb)=> {
if(cb.checked){
const mediaType=cb.name.split("_")[0];
if(!selectedTerms[mediaType]){
selectedTerms[mediaType]=[];
}
selectedTerms[mediaType].push(parseInt(cb.value, 10));
}});
}
return {
searchText: this.elements.searchInput?.value?.toLowerCase()||"",
startDate: this.elements.startDateInput?.value ? window.parseDateString(this.elements.startDateInput.value):this.elements.startDateInputMobile?.value ? window.parseDateString(this.elements.startDateInputMobile.value):null,
endDate: this.elements.endDateInput?.value ? window.parseDateString(this.elements.endDateInput.value):this.elements.endDateInputMobile?.value ? window.parseDateString(this.elements.endDateInputMobile.value):null,
selectedSdgTerms: this.elements.sdgCheckboxes
? Array.from(this.elements.sdgCheckboxes)
.filter((cb)=> cb.checked)
.map((cb)=> parseInt(cb.value, 10))
: [],
selectedEventCities: this.elements.eventCityCheckboxes
? Array.from(this.elements.eventCityCheckboxes)
.filter((cb)=> cb.checked)
.map((cb)=> cb.value)
: [],
selectedMediaTypes: this.elements.documentTypeCheckboxes
? Array.from(this.elements.documentTypeCheckboxes)
.filter((cb)=> cb.checked)
.map((cb)=> cb.value)
: [],
selectedTerms: selectedTerms,
sortingOption: this.elements.sortBySelect?.value||"date_newest",
selectedPostTerms: this.elements.postTypeCheckboxes
? Array.from(this.elements.postTypeCheckboxes)
.filter((cb)=> cb.checked)
.map((cb)=> cb.value)
: [],
postType: this.elements.postTypeButtons ? Array.from(this.elements.postTypeButtons).find((btn)=> btn.classList.contains("embla__slide--active"))?.dataset?.value||"all":"",
postCategory: this.elements.postCategoryButtons ? Array.from(this.elements.postCategoryButtons).find((btn)=> btn.classList.contains("embla__slide--active"))?.dataset?.value:""
};}
filterPosts(filters){
let matchingIndices=new Set(Array.from({ length: this.data.length }, (_, i)=> i));
if(filters.postCategory==="meldung"){
matchingIndices=new Set(
[...matchingIndices].filter((idx)=> {
return this.data[idx].post_term_ids.includes(0);
})
);
}else if(filters.postCategory==="pressemitteilung"){
matchingIndices=new Set(
[...matchingIndices].filter((idx)=> {
return this.data[idx].post_term_ids.includes(1);
})
);
}
if(filters.postType!=="all"){
matchingIndices=new Set(
[...matchingIndices].filter((idx)=> {
return this.data[idx].post_type===filters.postType;
})
);
}
if(filters.startDate||filters.endDate){
const filterStartDate=filters.startDate ? filters.startDate.getTime() / 1000:0;
const filterEndDate=filters.endDate ? filters.endDate.getTime() / 1000:Number.MAX_SAFE_INTEGER;
matchingIndices=new Set(
[...matchingIndices].filter((idx)=> {
const postDate=this.data[idx].post_filtering_date;
return (!filterStartDate||postDate >=filterStartDate)&&(!filterEndDate||postDate <=filterEndDate);
})
);
}
if(filters.searchText){
const searchText=filters.searchText.trim().toLowerCase();
const titleMatches=new Set();
for (const [title, indices] of this.indices.titleIndex){
const normalizedTitle=title.toLowerCase();
if(normalizedTitle.includes(searchText)){
indices.forEach((idx)=> titleMatches.add(idx));
}}
matchingIndices=new Set([...matchingIndices].filter((idx)=> titleMatches.has(idx)));
}
if(filters.postType==="newsletter_post"){
return matchingIndices;
}
if(filters.selectedPostTerms.length > 0&&["newsposts", "all"].includes(filters.postType)){
const postTermMatches=new Set();
filters.selectedPostTerms.forEach((term)=> {
const indices=this.indices.postTermIndex.get(term);
if(indices) indices.forEach((idx)=> postTermMatches.add(idx));
});
matchingIndices=new Set([...matchingIndices].filter((idx)=> postTermMatches.has(idx)));
}
if(filters.selectedSdgTerms.length > 0&&!["newsposts"].includes(filters.postType)){
const sdgMatches=new Set();
filters.selectedSdgTerms.forEach((termId)=> {
const indices=this.indices.sdgIndex.get(termId);
if(indices) indices.forEach((idx)=> sdgMatches.add(idx));
});
matchingIndices=new Set([...matchingIndices].filter((idx)=> sdgMatches.has(idx)));
}
if(filters.selectedEventCities.length > 0&&["event", "all"].includes(filters.postType)){
const eventCityMatches=new Set();
filters.selectedEventCities.forEach((city)=> {
const indices=this.indices.eventCityIndex.get(city.toLowerCase());
if(indices) indices.forEach((idx)=> eventCityMatches.add(idx));
});
matchingIndices=new Set([...matchingIndices].filter((idx)=> eventCityMatches.has(idx)));
}
if(filters.selectedMediaTypes.length > 0){
const mediaTypeMatchingIndices=new Set();
filters.selectedMediaTypes.forEach((type)=> {
if(filters.selectedTerms[type]&&filters.selectedTerms[type].length > 0){
filters.selectedTerms[type].forEach((termId)=> {
if(termId===0){
for (let i=0; i < this.data.length; i++){
const doc=this.data[i];
if(doc.post_type===type&&doc.term_ids.length===0){
mediaTypeMatchingIndices.add(i);
}}
}else{
const termIndices=this.indices.termIndex.get(type)?.get(termId);
if(termIndices){
termIndices.forEach((idx)=> mediaTypeMatchingIndices.add(idx));
}}
});
}else{
const typeIndices=this.indices.typeIndex.get(type);
if(typeIndices){
typeIndices.forEach((idx)=> mediaTypeMatchingIndices.add(idx));
}}
});
matchingIndices=new Set([...matchingIndices].filter((x)=> mediaTypeMatchingIndices.has(x)));
}
return matchingIndices;
}
filterAndUpdateUI(){
const filterState=this.getFilterState();
let matchingIndices=this.filterPosts(filterState);
let matchingPosts=Array.from(matchingIndices).map((idx)=> this.data[idx]);
if(filterState.sortingOption!=="date_newest"){
this.sortPosts(matchingPosts, filterState.sortingOption);
}
const totalItems=matchingPosts.length;
const totalPages=Math.ceil(totalItems / this.state.itemsPerPage);
if(this.state.currentPage > totalPages) this.state.currentPage=totalPages;
if(this.state.currentPage < 1) this.state.currentPage=1;
const startIndex=(this.state.currentPage - 1) * this.state.itemsPerPage;
const paginatedPosts=matchingPosts.slice(startIndex, startIndex + this.state.itemsPerPage);
this.updatePostsUI(paginatedPosts);
this.updatePaginationControls(totalItems);
}
sortPosts(postsArray, sortingOption){
switch (sortingOption){
case "date_oldest":
postsArray.reverse();
break;
default:
break;
}}
updatePostsUI(posts){
const container=this.elements.itemContainer;
if(!container){
console.warn("DEBUG: No item container found.");
return;
}
if(this.hasMediaPlayers){
if(window.PlyrInit&&typeof window.PlyrInit.destroyAllPlayers==="function"){
window.PlyrInit.destroyAllPlayers();
}}
while (container.firstChild){
container.removeChild(container.firstChild);
}
const fragment=document.createDocumentFragment();
posts.forEach((post)=> {
const element=this.createPostElement(post);
fragment.appendChild(element);
if(post.post_type==="audio"){
window.initSinglePlayer(element);
}else if(post.post_type==="video"){
const blockedElem=element.querySelector("[consent-required]");
if(blockedElem&&window.consentApi?.unblock){
window.consentApi.unblock(blockedElem).then(()=> {
window.initSinglePlayer(element);
});
}else{
window.initSinglePlayer(element);
}}
});
container.appendChild(fragment);
}
createPostElement(post){
const templateString=this.templates[post.post_type];
const filterState=this.getFilterState();
const selectedSdgTerms=Array.isArray(filterState.selectedSdgTerms) ? filterState.selectedSdgTerms.map(Number):[];
if(!templateString){
const postContainer=document.createElement("div");
postContainer.textContent="Unknown document type.";
return postContainer;
}
let badgeContainerKey=null;
if(post.badges?.badges?.sdg){
badgeContainerKey="badges";
}else if(post.badges_sdgs?.badges?.sdg){
badgeContainerKey="badges_sdgs";
}else if(post.badges_event_details?.badges?.sdg){
badgeContainerKey="badges_event_details";
}
if(!badgeContainerKey){
return this.populateTemplate(templateString, post);
}
const sdgBadges=Array.isArray(post[badgeContainerKey]?.badges?.sdg) ? [...post[badgeContainerKey].badges.sdg]:[];
const rawMaxShownSdgs=post[badgeContainerKey]?.max_shown_sdgs;
const MAX_SHOWN_SDGS=typeof rawMaxShownSdgs==="string"&&!isNaN(parseInt(rawMaxShownSdgs, 10)) ? parseInt(rawMaxShownSdgs, 10):typeof rawMaxShownSdgs==="number" ? rawMaxShownSdgs:2;
const rearrangedSdgBadges=this.rearrangeSdgBadges(sdgBadges, selectedSdgTerms, MAX_SHOWN_SDGS);
const clonedPost=JSON.parse(JSON.stringify(post));
if(clonedPost[badgeContainerKey]?.badges?.sdg){
clonedPost[badgeContainerKey].badges.sdg=rearrangedSdgBadges;
}
return this.populateTemplate(templateString, clonedPost);
}
rearrangeSdgBadges(sdgBadges, selectedSdgTerms, maxShownSdgs){
const selectedSdgsSet=new Set(selectedSdgTerms);
if(selectedSdgsSet.size===0){
return sdgBadges.slice(0, maxShownSdgs);
}
const selectedBadges=[];
const nonSelectedBadges=[];
sdgBadges.forEach((badge)=> {
const badgeTermId=parseInt(badge.term_id, 10);
if(selectedSdgsSet.has(badgeTermId)){
selectedBadges.push(badge);
}else{
nonSelectedBadges.push(badge);
}});
const rearrangedSdgBadges=selectedBadges.concat(nonSelectedBadges);
return rearrangedSdgBadges.slice(0, maxShownSdgs);
}
generateBadges(badges, badgeClass){
return badges
.map((badge)=> {
let content="";
let extraClass="";
switch (badge.type){
case "sdg":
content=badge.name;
return `<li class="${badgeClass}" data-sdg-id="${badge.term_id}">${content}</li>`;
case "more_sdgs":
const remainingSdgsJson=JSON.stringify(badge.remaining_sdgs);
return `
<li class="${badgeClass} more-sdgs-badge" data-remaining-sdgs='${remainingSdgsJson}' data-badge-class="${badgeClass}">
<svg class="icon"><use href="#icon-plus"></use></svg>
<span class="more-sdgs-text">${badge.remaining_count} Weitere</span>
</li>
`;
case "date":
case "event_date":
content=badge.value;
extraClass=badge.type==="event_date" ? " event-date":"";
break;
case "project":
case "category":
case "event_type":
case "document_term":
content=badge.name;
extraClass=badge.type==="event_type"&&badge.is_internal ? " rne-event":"";
break;
case "event_location":
content=badge.value;
extraClass=" event-location";
break;
default:
content=badge.name||badge.value||"";
}
return `<li class="${badgeClass}${extraClass}">${content}</li>`;
})
.join("");
}
populateTemplate(templateString, data){
let template=templateString;
template=template.replace(/{{(\w+)}}/g, (_, key)=> {
if(key.startsWith("badges")){
const badgeData=data[key];
if(badgeData&&badgeData.badges){
let iconIncluded=false;
let badgesHtml="";
if(badgeData.badges.sdg&&badgeData.badges.sdg.length > 0){
badgesHtml +='<ul class="badge-list sdg-badge-list">';
if(!iconIncluded&&badgeData.icon_name){
badgesHtml +=window.getSvg(badgeData.icon_name);
iconIncluded=true;
}
badgesHtml +=this.generateBadges(badgeData.badges.sdg, badgeData.badge_class);
badgesHtml +="</ul>";
}
if(badgeData.badges.others&&badgeData.badges.others.length > 0){
badgesHtml +='<ul class="badge-list">';
if(!iconIncluded&&badgeData.icon_name){
badgesHtml +=window.getSvg(badgeData.icon_name);
iconIncluded=true;
}
badgesHtml +=this.generateBadges(badgeData.badges.others, badgeData.badge_class);
badgesHtml +="</ul>";
}
return badgesHtml;
}else{
return "";
}}else if(key==="video_player_html_blocked"){
const blocked=(data.video_player_html_blocked||"").trim();
if(blocked===""){
return data.video_player_html ?? "";
}else{
return blocked;
}}else{
return data[key]!=null ? data[key]:"";
}});
const tempDiv=document.createElement("div");
tempDiv.innerHTML=template.trim();
tempDiv.querySelectorAll("[data-src]").forEach((element)=> {
element.setAttribute("src", element.dataset.src);
element.removeAttribute("data-src");
});
return tempDiv.firstChild;
}
updatePaginationControls(totalItems){
const container=this.elements.paginationContainer;
if(!container) return;
container.innerHTML="";
const totalPages=Math.ceil(totalItems / this.state.itemsPerPage);
if(totalPages <=1) return;
const currentPage=this.state.currentPage;
if(currentPage > 1){
const prevContent=window.getSvg("icon-arrow");
this.createPaginationButton(prevContent,
()=> {
this.state.currentPage--;
this.filterAndUpdateUI();
this.scrollToMediaItems();
},
container,
false,
"pagination__button--prev",
"prev"
);
}
let pageNumbers=[];
if(totalPages <=5){
for (let i=1; i <=totalPages; i++){
pageNumbers.push(i);
}}else{
pageNumbers.push(1);
if(currentPage > 3){
pageNumbers.push("...");
}
let startPage=Math.max(2, currentPage - 1);
let endPage=Math.min(totalPages - 1, currentPage + 1);
for (let i=startPage; i <=endPage; i++){
pageNumbers.push(i);
}
if(currentPage < totalPages - 2){
pageNumbers.push("...");
}
pageNumbers.push(totalPages);
}
pageNumbers.forEach((page)=> {
if(page==="..."){
const ellipsis=document.createElement("span");
ellipsis.textContent="...";
ellipsis.classList.add("ellipsis");
container.appendChild(ellipsis);
}else{
const pageContent=page.toString();
this.createPaginationButton(pageContent,
()=> {
this.state.currentPage=page;
this.filterAndUpdateUI();
this.scrollToMediaItems();
},
container,
page===currentPage
);
}});
if(currentPage < totalPages){
const nextContent=window.getSvg("icon-arrow");
this.createPaginationButton(nextContent,
()=> {
this.state.currentPage++;
this.filterAndUpdateUI();
this.scrollToMediaItems();
},
container,
false,
"pagination__button--next",
"next"
);
}}
createPaginationButton(content, onClick, container, isActive=false, extraClasses="", direction="prev"){
const button=document.createElement("button");
button.innerHTML=content;
button.classList.add("pagination__button");
if(direction==="prev"){
button.setAttribute("rel", "prev");
}else if(direction==="next"){
button.setAttribute("rel", "next");
}
if(isActive){
button.classList.add("pagination__button--active");
}
if(extraClasses){
extraClasses.split(" ").forEach((cls)=> button.classList.add(cls));
}
button.addEventListener("click", onClick);
container.appendChild(button);
}
scrollToMediaItems(){
if(this.elements.itemContainer){
const yOffset=-240;
const element=this.elements.itemContainer;
const yPosition=element.getBoundingClientRect().top + window.scrollY + yOffset;
window.scrollTo({ top: yPosition, behavior: "smooth" });
}}
buildIndices(){
Object.values(this.indices).forEach((index)=> index.clear());
this.data.forEach((post, idx)=> {
if(post.post_title){
const normalizedTitle=post.post_title.trim().toLowerCase();
if(!this.indices.titleIndex.has(normalizedTitle)){
this.indices.titleIndex.set(normalizedTitle, new Set());
}
this.indices.titleIndex.get(normalizedTitle).add(idx);
}
if(post.post_filtering_date){
const dateKey=post.post_filtering_date;
if(!this.indices.dateIndex.has(dateKey)){
this.indices.dateIndex.set(dateKey, new Set());
}
this.indices.dateIndex.get(dateKey).add(idx);
}
if(Array.isArray(post.sdg_ids)){
post.sdg_ids.forEach((sdgId)=> {
if(!this.indices.sdgIndex.has(sdgId)){
this.indices.sdgIndex.set(sdgId, new Set());
}
this.indices.sdgIndex.get(sdgId).add(idx);
});
}
if(post.post_type){
const mediaType=post.post_type.toLowerCase();
if(!this.indices.typeIndex.has(mediaType)){
this.indices.typeIndex.set(mediaType, new Set());
}
this.indices.typeIndex.get(mediaType).add(idx);
}
if(Array.isArray(post.terms)&&Array.isArray(post.term_ids)){
const mediaType=post.post_type.toLowerCase();
post.term_ids.forEach((termId)=> {
if(!this.indices.termIndex.has(mediaType)){
this.indices.termIndex.set(mediaType, new Map());
}
const mediaTypeMap=this.indices.termIndex.get(mediaType);
if(!mediaTypeMap.has(termId)){
mediaTypeMap.set(termId, new Set());
}
const termSet=mediaTypeMap.get(termId);
termSet.add(idx);
});
}
if(Array.isArray(post.post_terms)){
post.post_term_ids.forEach((term)=> {
const termKey=term.toString();
if(!this.indices.postTermIndex.has(termKey)){
this.indices.postTermIndex.set(termKey, new Set());
}
this.indices.postTermIndex.get(termKey).add(idx);
});
}
if(post.event_city){
const eventCity=post.event_city.toLowerCase();
if(!this.indices.eventCityIndex.has(eventCity)){
this.indices.eventCityIndex.set(eventCity, new Set());
}
this.indices.eventCityIndex.get(eventCity).add(idx);
}});
}
initTemplates(){
if(this.options.templates){
this.templates=this.options.templates;
}else{
console.warn("No templates provided.");
}}
updateResetButtonVisibility(){
let anyFilterActive=false;
this.elements.archiveFilters.forEach((accordionItem)=> {
const inputs=accordionItem.querySelectorAll("input, select, textarea");
inputs.forEach((input)=> {
if(input.type==="checkbox"||input.type==="radio"){
if(input.checked){
anyFilterActive=true;
}}else if(input.tagName==="SELECT"&&input.value!==""){
anyFilterActive=true;
}else if(input.tagName==="INPUT"&&input.value!==""){
anyFilterActive=true;
}});
});
if(this.elements.mobileFilterOverlay){
const mobileInputs=this.elements.mobileFilterOverlay.querySelectorAll("input, select, textarea");
mobileInputs.forEach((input)=> {
if(input.type==="checkbox"||input.type==="radio"){
if(input.checked){
anyFilterActive=true;
}}else if(input.tagName==="SELECT"&&input.value!==""){
anyFilterActive=true;
}else if(input.tagName==="INPUT"&&input.value!==""){
anyFilterActive=true;
}});
}
this.elements.filterResetButtons.forEach((btn)=> {
btn.style.display=anyFilterActive ? "block":"none";
});
}
filterAndUpdateUI(){
const filterState=this.getFilterState();
let matchingIndices=this.filterPosts(filterState);
let matchingPosts=Array.from(matchingIndices).map((idx)=> this.data[idx]);
if(filterState.sortingOption!=="date_newest"){
this.sortPosts(matchingPosts, filterState.sortingOption);
}
const totalItems=matchingPosts.length;
const totalPages=Math.ceil(totalItems / this.state.itemsPerPage);
if(this.state.currentPage > totalPages) this.state.currentPage=totalPages;
if(this.state.currentPage < 1) this.state.currentPage=1;
const startIndex=(this.state.currentPage - 1) * this.state.itemsPerPage;
const paginatedPosts=matchingPosts.slice(startIndex, startIndex + this.state.itemsPerPage);
this.updatePostsUI(paginatedPosts);
this.updatePaginationControls(totalItems);
}}
window.ContentFilter=ContentFilter;
var SimpleBar=function(){"use strict";var t=function(e,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])},t(e,i)};var e="object"==typeof global&&global&&global.Object===Object&&global,i="object"==typeof self&&self&&self.Object===Object&&self,s=e||i||Function("return this")(),r=s.Symbol,l=Object.prototype,o=l.hasOwnProperty,n=l.toString,a=r?r.toStringTag:void 0;var c=Object.prototype.toString;var h=r?r.toStringTag:void 0;function u(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=o.call(t,a),i=t[a];try{t[a]=void 0;var s=!0}catch(t){}var r=n.call(t);return s&&(e?t[a]=i:delete t[a]),r}(t):function(t){return c.call(t)}(t)}var d=/\s/;var p=/^\s+/;function v(t){return t?t.slice(0,function(t){for(var e=t.length;e--&&d.test(t.charAt(e)););return e}(t)+1).replace(p,""):t}function f(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}var m=/^[-+]0x[0-9a-f]+$/i,b=/^0b[01]+$/i,g=/^0o[0-7]+$/i,x=parseInt;function y(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return null!=t&&"object"==typeof t}(t)&&"[object Symbol]"==u(t)}(t))return NaN;if(f(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=f(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=v(t);var i=b.test(t);return i||g.test(t)?x(t.slice(2),i?2:8):m.test(t)?NaN:+t}var E=function(){return s.Date.now()},O=Math.max,w=Math.min;function S(t,e,i){var s,r,l,o,n,a,c=0,h=!1,u=!1,d=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function p(e){var i=s,l=r;return s=r=void 0,c=e,o=t.apply(l,i)}function v(t){return c=t,n=setTimeout(b,e),h?p(t):o}function m(t){var i=t-a;return void 0===a||i>=e||i<0||u&&t-c>=l}function b(){var t=E();if(m(t))return g(t);n=setTimeout(b,function(t){var i=e-(t-a);return u?w(i,l-(t-c)):i}(t))}function g(t){return n=void 0,d&&s?p(t):(s=r=void 0,o)}function x(){var t=E(),i=m(t);if(s=arguments,r=this,a=t,i){if(void 0===n)return v(a);if(u)return clearTimeout(n),n=setTimeout(b,e),p(a)}return void 0===n&&(n=setTimeout(b,e)),o}return e=y(e)||0,f(i)&&(h=!!i.leading,l=(u="maxWait"in i)?O(y(i.maxWait)||0,e):l,d="trailing"in i?!!i.trailing:d),x.cancel=function(){void 0!==n&&clearTimeout(n),c=0,s=a=r=n=void 0},x.flush=function(){return void 0===n?o:g(E())},x}var A=function(){return A=Object.assign||function(t){for(var e,i=1,s=arguments.length;i<s;i++)for(var r in e=arguments[i])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t},A.apply(this,arguments)};function k(t){return t&&t.ownerDocument&&t.ownerDocument.defaultView?t.ownerDocument.defaultView:window}function W(t){return t&&t.ownerDocument?t.ownerDocument:document}var M=function(t){return Array.prototype.reduce.call(t,(function(t,e){var i=e.name.match(/data-simplebar-(.+)/);if(i){var s=i[1].replace(/\W+(.)/g,(function(t,e){return e.toUpperCase()}));switch(e.value){case"true":t[s]=!0;break;case"false":t[s]=!1;break;case void 0:t[s]=!0;break;default:t[s]=e.value}}return t}),{})};function N(t,e){var i;t&&(i=t.classList).add.apply(i,e.split(" "))}function L(t,e){t&&e.split(" ").forEach((function(e){t.classList.remove(e)}))}function z(t){return".".concat(t.split(" ").join("."))}var C=!("undefined"==typeof window||!window.document||!window.document.createElement),T=Object.freeze({__proto__:null,addClasses:N,canUseDOM:C,classNamesToQuery:z,getElementDocument:W,getElementWindow:k,getOptions:M,removeClasses:L}),D=null,R=null;function V(){if(null===D){if("undefined"==typeof document)return D=0;var t=document.body,e=document.createElement("div");e.classList.add("simplebar-hide-scrollbar"),t.appendChild(e);var i=e.getBoundingClientRect().right;t.removeChild(e),D=i}return D}C&&window.addEventListener("resize",(function(){R!==window.devicePixelRatio&&(R=window.devicePixelRatio,D=null)}));var H=k,j=W,B=M,_=N,q=L,P=z,X=function(){function t(e,i){void 0===i&&(i={});var s=this;if(this.removePreventClickId=null,this.minScrollbarWidth=20,this.stopScrollDelay=175,this.isScrolling=!1,this.isMouseEntering=!1,this.isDragging=!1,this.scrollXTicking=!1,this.scrollYTicking=!1,this.wrapperEl=null,this.contentWrapperEl=null,this.contentEl=null,this.offsetEl=null,this.maskEl=null,this.placeholderEl=null,this.heightAutoObserverWrapperEl=null,this.heightAutoObserverEl=null,this.rtlHelpers=null,this.scrollbarWidth=0,this.resizeObserver=null,this.mutationObserver=null,this.elStyles=null,this.isRtl=null,this.mouseX=0,this.mouseY=0,this.onMouseMove=function(){},this.onWindowResize=function(){},this.onStopScrolling=function(){},this.onMouseEntered=function(){},this.onScroll=function(){var t=H(s.el);s.scrollXTicking||(t.requestAnimationFrame(s.scrollX),s.scrollXTicking=!0),s.scrollYTicking||(t.requestAnimationFrame(s.scrollY),s.scrollYTicking=!0),s.isScrolling||(s.isScrolling=!0,_(s.el,s.classNames.scrolling)),s.showScrollbar("x"),s.showScrollbar("y"),s.onStopScrolling()},this.scrollX=function(){s.axis.x.isOverflowing&&s.positionScrollbar("x"),s.scrollXTicking=!1},this.scrollY=function(){s.axis.y.isOverflowing&&s.positionScrollbar("y"),s.scrollYTicking=!1},this._onStopScrolling=function(){q(s.el,s.classNames.scrolling),s.options.autoHide&&(s.hideScrollbar("x"),s.hideScrollbar("y")),s.isScrolling=!1},this.onMouseEnter=function(){s.isMouseEntering||(_(s.el,s.classNames.mouseEntered),s.showScrollbar("x"),s.showScrollbar("y"),s.isMouseEntering=!0),s.onMouseEntered()},this._onMouseEntered=function(){q(s.el,s.classNames.mouseEntered),s.options.autoHide&&(s.hideScrollbar("x"),s.hideScrollbar("y")),s.isMouseEntering=!1},this._onMouseMove=function(t){s.mouseX=t.clientX,s.mouseY=t.clientY,(s.axis.x.isOverflowing||s.axis.x.forceVisible)&&s.onMouseMoveForAxis("x"),(s.axis.y.isOverflowing||s.axis.y.forceVisible)&&s.onMouseMoveForAxis("y")},this.onMouseLeave=function(){s.onMouseMove.cancel(),(s.axis.x.isOverflowing||s.axis.x.forceVisible)&&s.onMouseLeaveForAxis("x"),(s.axis.y.isOverflowing||s.axis.y.forceVisible)&&s.onMouseLeaveForAxis("y"),s.mouseX=-1,s.mouseY=-1},this._onWindowResize=function(){s.scrollbarWidth=s.getScrollbarWidth(),s.hideNativeScrollbar()},this.onPointerEvent=function(t){var e,i;s.axis.x.track.el&&s.axis.y.track.el&&s.axis.x.scrollbar.el&&s.axis.y.scrollbar.el&&(s.axis.x.track.rect=s.axis.x.track.el.getBoundingClientRect(),s.axis.y.track.rect=s.axis.y.track.el.getBoundingClientRect(),(s.axis.x.isOverflowing||s.axis.x.forceVisible)&&(e=s.isWithinBounds(s.axis.x.track.rect)),(s.axis.y.isOverflowing||s.axis.y.forceVisible)&&(i=s.isWithinBounds(s.axis.y.track.rect)),(e||i)&&(t.stopPropagation(),"pointerdown"===t.type&&"touch"!==t.pointerType&&(e&&(s.axis.x.scrollbar.rect=s.axis.x.scrollbar.el.getBoundingClientRect(),s.isWithinBounds(s.axis.x.scrollbar.rect)?s.onDragStart(t,"x"):s.onTrackClick(t,"x")),i&&(s.axis.y.scrollbar.rect=s.axis.y.scrollbar.el.getBoundingClientRect(),s.isWithinBounds(s.axis.y.scrollbar.rect)?s.onDragStart(t,"y"):s.onTrackClick(t,"y")))))},this.drag=function(e){var i,r,l,o,n,a,c,h,u,d,p;if(s.draggedAxis&&s.contentWrapperEl){var v=s.axis[s.draggedAxis].track,f=null!==(r=null===(i=v.rect)||void 0===i?void 0:i[s.axis[s.draggedAxis].sizeAttr])&&void 0!==r?r:0,m=s.axis[s.draggedAxis].scrollbar,b=null!==(o=null===(l=s.contentWrapperEl)||void 0===l?void 0:l[s.axis[s.draggedAxis].scrollSizeAttr])&&void 0!==o?o:0,g=parseInt(null!==(a=null===(n=s.elStyles)||void 0===n?void 0:n[s.axis[s.draggedAxis].sizeAttr])&&void 0!==a?a:"0px",10);e.preventDefault(),e.stopPropagation();var x=("y"===s.draggedAxis?e.pageY:e.pageX)-(null!==(h=null===(c=v.rect)||void 0===c?void 0:c[s.axis[s.draggedAxis].offsetAttr])&&void 0!==h?h:0)-s.axis[s.draggedAxis].dragOffset,y=(x="x"===s.draggedAxis&&s.isRtl?(null!==(d=null===(u=v.rect)||void 0===u?void 0:u[s.axis[s.draggedAxis].sizeAttr])&&void 0!==d?d:0)-m.size-x:x)/(f-m.size)*(b-g);"x"===s.draggedAxis&&s.isRtl&&(y=(null===(p=t.getRtlHelpers())||void 0===p?void 0:p.isScrollingToNegative)?-y:y),s.contentWrapperEl[s.axis[s.draggedAxis].scrollOffsetAttr]=y}},this.onEndDrag=function(t){s.isDragging=!1;var e=j(s.el),i=H(s.el);t.preventDefault(),t.stopPropagation(),q(s.el,s.classNames.dragging),s.onStopScrolling(),e.removeEventListener("mousemove",s.drag,!0),e.removeEventListener("mouseup",s.onEndDrag,!0),s.removePreventClickId=i.setTimeout((function(){e.removeEventListener("click",s.preventClick,!0),e.removeEventListener("dblclick",s.preventClick,!0),s.removePreventClickId=null}))},this.preventClick=function(t){t.preventDefault(),t.stopPropagation()},this.el=e,this.options=A(A({},t.defaultOptions),i),this.classNames=A(A({},t.defaultOptions.classNames),i.classNames),this.axis={x:{scrollOffsetAttr:"scrollLeft",sizeAttr:"width",scrollSizeAttr:"scrollWidth",offsetSizeAttr:"offsetWidth",offsetAttr:"left",overflowAttr:"overflowX",dragOffset:0,isOverflowing:!0,forceVisible:!1,track:{size:null,el:null,rect:null,isVisible:!1},scrollbar:{size:null,el:null,rect:null,isVisible:!1}},y:{scrollOffsetAttr:"scrollTop",sizeAttr:"height",scrollSizeAttr:"scrollHeight",offsetSizeAttr:"offsetHeight",offsetAttr:"top",overflowAttr:"overflowY",dragOffset:0,isOverflowing:!0,forceVisible:!1,track:{size:null,el:null,rect:null,isVisible:!1},scrollbar:{size:null,el:null,rect:null,isVisible:!1}}},"object"!=typeof this.el||!this.el.nodeName)throw new Error("Argument passed to SimpleBar must be an HTML element instead of ".concat(this.el));this.onMouseMove=function(t,e,i){var s=!0,r=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return f(i)&&(s="leading"in i?!!i.leading:s,r="trailing"in i?!!i.trailing:r),S(t,e,{leading:s,maxWait:e,trailing:r})}(this._onMouseMove,64),this.onWindowResize=S(this._onWindowResize,64,{leading:!0}),this.onStopScrolling=S(this._onStopScrolling,this.stopScrollDelay),this.onMouseEntered=S(this._onMouseEntered,this.stopScrollDelay),this.init()}return t.getRtlHelpers=function(){if(t.rtlHelpers)return t.rtlHelpers;var e=document.createElement("div");e.innerHTML='<div class="simplebar-dummy-scrollbar-size"><div></div></div>';var i=e.firstElementChild,s=null==i?void 0:i.firstElementChild;if(!s)return null;document.body.appendChild(i),i.scrollLeft=0;var r=t.getOffset(i),l=t.getOffset(s);i.scrollLeft=-999;var o=t.getOffset(s);return document.body.removeChild(i),t.rtlHelpers={isScrollOriginAtZero:r.left!==l.left,isScrollingToNegative:l.left!==o.left},t.rtlHelpers},t.prototype.getScrollbarWidth=function(){try{return this.contentWrapperEl&&"none"===getComputedStyle(this.contentWrapperEl,"::-webkit-scrollbar").display||"scrollbarWidth"in document.documentElement.style||"-ms-overflow-style"in document.documentElement.style?0:V()}catch(t){return V()}},t.getOffset=function(t){var e=t.getBoundingClientRect(),i=j(t),s=H(t);return{top:e.top+(s.pageYOffset||i.documentElement.scrollTop),left:e.left+(s.pageXOffset||i.documentElement.scrollLeft)}},t.prototype.init=function(){C&&(this.initDOM(),this.rtlHelpers=t.getRtlHelpers(),this.scrollbarWidth=this.getScrollbarWidth(),this.recalculate(),this.initListeners())},t.prototype.initDOM=function(){var t,e;this.wrapperEl=this.el.querySelector(P(this.classNames.wrapper)),this.contentWrapperEl=this.options.scrollableNode||this.el.querySelector(P(this.classNames.contentWrapper)),this.contentEl=this.options.contentNode||this.el.querySelector(P(this.classNames.contentEl)),this.offsetEl=this.el.querySelector(P(this.classNames.offset)),this.maskEl=this.el.querySelector(P(this.classNames.mask)),this.placeholderEl=this.findChild(this.wrapperEl,P(this.classNames.placeholder)),this.heightAutoObserverWrapperEl=this.el.querySelector(P(this.classNames.heightAutoObserverWrapperEl)),this.heightAutoObserverEl=this.el.querySelector(P(this.classNames.heightAutoObserverEl)),this.axis.x.track.el=this.findChild(this.el,"".concat(P(this.classNames.track)).concat(P(this.classNames.horizontal))),this.axis.y.track.el=this.findChild(this.el,"".concat(P(this.classNames.track)).concat(P(this.classNames.vertical))),this.axis.x.scrollbar.el=(null===(t=this.axis.x.track.el)||void 0===t?void 0:t.querySelector(P(this.classNames.scrollbar)))||null,this.axis.y.scrollbar.el=(null===(e=this.axis.y.track.el)||void 0===e?void 0:e.querySelector(P(this.classNames.scrollbar)))||null,this.options.autoHide||(_(this.axis.x.scrollbar.el,this.classNames.visible),_(this.axis.y.scrollbar.el,this.classNames.visible))},t.prototype.initListeners=function(){var t,e=this,i=H(this.el);if(this.el.addEventListener("mouseenter",this.onMouseEnter),this.el.addEventListener("pointerdown",this.onPointerEvent,!0),this.el.addEventListener("mousemove",this.onMouseMove),this.el.addEventListener("mouseleave",this.onMouseLeave),null===(t=this.contentWrapperEl)||void 0===t||t.addEventListener("scroll",this.onScroll),i.addEventListener("resize",this.onWindowResize),this.contentEl){if(window.ResizeObserver){var s=!1,r=i.ResizeObserver||ResizeObserver;this.resizeObserver=new r((function(){s&&i.requestAnimationFrame((function(){e.recalculate()}))})),this.resizeObserver.observe(this.el),this.resizeObserver.observe(this.contentEl),i.requestAnimationFrame((function(){s=!0}))}this.mutationObserver=new i.MutationObserver((function(){i.requestAnimationFrame((function(){e.recalculate()}))})),this.mutationObserver.observe(this.contentEl,{childList:!0,subtree:!0,characterData:!0})}},t.prototype.recalculate=function(){if(this.heightAutoObserverEl&&this.contentEl&&this.contentWrapperEl&&this.wrapperEl&&this.placeholderEl){var t=H(this.el);this.elStyles=t.getComputedStyle(this.el),this.isRtl="rtl"===this.elStyles.direction;var e=this.contentEl.offsetWidth,i=this.heightAutoObserverEl.offsetHeight<=1,s=this.heightAutoObserverEl.offsetWidth<=1||e>0,r=this.contentWrapperEl.offsetWidth,l=this.elStyles.overflowX,o=this.elStyles.overflowY;this.contentEl.style.padding="".concat(this.elStyles.paddingTop," ").concat(this.elStyles.paddingRight," ").concat(this.elStyles.paddingBottom," ").concat(this.elStyles.paddingLeft),this.wrapperEl.style.margin="-".concat(this.elStyles.paddingTop," -").concat(this.elStyles.paddingRight," -").concat(this.elStyles.paddingBottom," -").concat(this.elStyles.paddingLeft);var n=this.contentEl.scrollHeight,a=this.contentEl.scrollWidth;this.contentWrapperEl.style.height=i?"auto":"100%",this.placeholderEl.style.width=s?"".concat(e||a,"px"):"auto",this.placeholderEl.style.height="".concat(n,"px");var c=this.contentWrapperEl.offsetHeight;this.axis.x.isOverflowing=0!==e&&a>e,this.axis.y.isOverflowing=n>c,this.axis.x.isOverflowing="hidden"!==l&&this.axis.x.isOverflowing,this.axis.y.isOverflowing="hidden"!==o&&this.axis.y.isOverflowing,this.axis.x.forceVisible="x"===this.options.forceVisible||!0===this.options.forceVisible,this.axis.y.forceVisible="y"===this.options.forceVisible||!0===this.options.forceVisible,this.hideNativeScrollbar();var h=this.axis.x.isOverflowing?this.scrollbarWidth:0,u=this.axis.y.isOverflowing?this.scrollbarWidth:0;this.axis.x.isOverflowing=this.axis.x.isOverflowing&&a>r-u,this.axis.y.isOverflowing=this.axis.y.isOverflowing&&n>c-h,this.axis.x.scrollbar.size=this.getScrollbarSize("x"),this.axis.y.scrollbar.size=this.getScrollbarSize("y"),this.axis.x.scrollbar.el&&(this.axis.x.scrollbar.el.style.width="".concat(this.axis.x.scrollbar.size,"px")),this.axis.y.scrollbar.el&&(this.axis.y.scrollbar.el.style.height="".concat(this.axis.y.scrollbar.size,"px")),this.positionScrollbar("x"),this.positionScrollbar("y"),this.toggleTrackVisibility("x"),this.toggleTrackVisibility("y")}},t.prototype.getScrollbarSize=function(t){var e,i;if(void 0===t&&(t="y"),!this.axis[t].isOverflowing||!this.contentEl)return 0;var s,r=this.contentEl[this.axis[t].scrollSizeAttr],l=null!==(i=null===(e=this.axis[t].track.el)||void 0===e?void 0:e[this.axis[t].offsetSizeAttr])&&void 0!==i?i:0,o=l/r;return s=Math.max(~~(o*l),this.options.scrollbarMinSize),this.options.scrollbarMaxSize&&(s=Math.min(s,this.options.scrollbarMaxSize)),s},t.prototype.positionScrollbar=function(e){var i,s,r;void 0===e&&(e="y");var l=this.axis[e].scrollbar;if(this.axis[e].isOverflowing&&this.contentWrapperEl&&l.el&&this.elStyles){var o=this.contentWrapperEl[this.axis[e].scrollSizeAttr],n=(null===(i=this.axis[e].track.el)||void 0===i?void 0:i[this.axis[e].offsetSizeAttr])||0,a=parseInt(this.elStyles[this.axis[e].sizeAttr],10),c=this.contentWrapperEl[this.axis[e].scrollOffsetAttr];c="x"===e&&this.isRtl&&(null===(s=t.getRtlHelpers())||void 0===s?void 0:s.isScrollOriginAtZero)?-c:c,"x"===e&&this.isRtl&&(c=(null===(r=t.getRtlHelpers())||void 0===r?void 0:r.isScrollingToNegative)?c:-c);var h=c/(o-a),u=~~((n-l.size)*h);u="x"===e&&this.isRtl?-u+(n-l.size):u,l.el.style.transform="x"===e?"translate3d(".concat(u,"px, 0, 0)"):"translate3d(0, ".concat(u,"px, 0)")}},t.prototype.toggleTrackVisibility=function(t){void 0===t&&(t="y");var e=this.axis[t].track.el,i=this.axis[t].scrollbar.el;e&&i&&this.contentWrapperEl&&(this.axis[t].isOverflowing||this.axis[t].forceVisible?(e.style.visibility="visible",this.contentWrapperEl.style[this.axis[t].overflowAttr]="scroll",this.el.classList.add("".concat(this.classNames.scrollable,"-").concat(t))):(e.style.visibility="hidden",this.contentWrapperEl.style[this.axis[t].overflowAttr]="hidden",this.el.classList.remove("".concat(this.classNames.scrollable,"-").concat(t))),this.axis[t].isOverflowing?i.style.display="block":i.style.display="none")},t.prototype.showScrollbar=function(t){void 0===t&&(t="y"),this.axis[t].isOverflowing&&!this.axis[t].scrollbar.isVisible&&(_(this.axis[t].scrollbar.el,this.classNames.visible),this.axis[t].scrollbar.isVisible=!0)},t.prototype.hideScrollbar=function(t){void 0===t&&(t="y"),this.isDragging||this.axis[t].isOverflowing&&this.axis[t].scrollbar.isVisible&&(q(this.axis[t].scrollbar.el,this.classNames.visible),this.axis[t].scrollbar.isVisible=!1)},t.prototype.hideNativeScrollbar=function(){this.offsetEl&&(this.offsetEl.style[this.isRtl?"left":"right"]=this.axis.y.isOverflowing||this.axis.y.forceVisible?"-".concat(this.scrollbarWidth,"px"):"0px",this.offsetEl.style.bottom=this.axis.x.isOverflowing||this.axis.x.forceVisible?"-".concat(this.scrollbarWidth,"px"):"0px")},t.prototype.onMouseMoveForAxis=function(t){void 0===t&&(t="y");var e=this.axis[t];e.track.el&&e.scrollbar.el&&(e.track.rect=e.track.el.getBoundingClientRect(),e.scrollbar.rect=e.scrollbar.el.getBoundingClientRect(),this.isWithinBounds(e.track.rect)?(this.showScrollbar(t),_(e.track.el,this.classNames.hover),this.isWithinBounds(e.scrollbar.rect)?_(e.scrollbar.el,this.classNames.hover):q(e.scrollbar.el,this.classNames.hover)):(q(e.track.el,this.classNames.hover),this.options.autoHide&&this.hideScrollbar(t)))},t.prototype.onMouseLeaveForAxis=function(t){void 0===t&&(t="y"),q(this.axis[t].track.el,this.classNames.hover),q(this.axis[t].scrollbar.el,this.classNames.hover),this.options.autoHide&&this.hideScrollbar(t)},t.prototype.onDragStart=function(t,e){var i;void 0===e&&(e="y"),this.isDragging=!0;var s=j(this.el),r=H(this.el),l=this.axis[e].scrollbar,o="y"===e?t.pageY:t.pageX;this.axis[e].dragOffset=o-((null===(i=l.rect)||void 0===i?void 0:i[this.axis[e].offsetAttr])||0),this.draggedAxis=e,_(this.el,this.classNames.dragging),s.addEventListener("mousemove",this.drag,!0),s.addEventListener("mouseup",this.onEndDrag,!0),null===this.removePreventClickId?(s.addEventListener("click",this.preventClick,!0),s.addEventListener("dblclick",this.preventClick,!0)):(r.clearTimeout(this.removePreventClickId),this.removePreventClickId=null)},t.prototype.onTrackClick=function(t,e){var i,s,r,l,o=this;void 0===e&&(e="y");var n=this.axis[e];if(this.options.clickOnTrack&&n.scrollbar.el&&this.contentWrapperEl){t.preventDefault();var a=H(this.el);this.axis[e].scrollbar.rect=n.scrollbar.el.getBoundingClientRect();var c=null!==(s=null===(i=this.axis[e].scrollbar.rect)||void 0===i?void 0:i[this.axis[e].offsetAttr])&&void 0!==s?s:0,h=parseInt(null!==(l=null===(r=this.elStyles)||void 0===r?void 0:r[this.axis[e].sizeAttr])&&void 0!==l?l:"0px",10),u=this.contentWrapperEl[this.axis[e].scrollOffsetAttr],d=("y"===e?this.mouseY-c:this.mouseX-c)<0?-1:1,p=-1===d?u-h:u+h,v=function(){o.contentWrapperEl&&(-1===d?u>p&&(u-=40,o.contentWrapperEl[o.axis[e].scrollOffsetAttr]=u,a.requestAnimationFrame(v)):u<p&&(u+=40,o.contentWrapperEl[o.axis[e].scrollOffsetAttr]=u,a.requestAnimationFrame(v)))};v()}},t.prototype.getContentElement=function(){return this.contentEl},t.prototype.getScrollElement=function(){return this.contentWrapperEl},t.prototype.removeListeners=function(){var t=H(this.el);this.el.removeEventListener("mouseenter",this.onMouseEnter),this.el.removeEventListener("pointerdown",this.onPointerEvent,!0),this.el.removeEventListener("mousemove",this.onMouseMove),this.el.removeEventListener("mouseleave",this.onMouseLeave),this.contentWrapperEl&&this.contentWrapperEl.removeEventListener("scroll",this.onScroll),t.removeEventListener("resize",this.onWindowResize),this.mutationObserver&&this.mutationObserver.disconnect(),this.resizeObserver&&this.resizeObserver.disconnect(),this.onMouseMove.cancel(),this.onWindowResize.cancel(),this.onStopScrolling.cancel(),this.onMouseEntered.cancel()},t.prototype.unMount=function(){this.removeListeners()},t.prototype.isWithinBounds=function(t){return this.mouseX>=t.left&&this.mouseX<=t.left+t.width&&this.mouseY>=t.top&&this.mouseY<=t.top+t.height},t.prototype.findChild=function(t,e){var i=t.matches||t.webkitMatchesSelector||t.mozMatchesSelector||t.msMatchesSelector;return Array.prototype.filter.call(t.children,(function(t){return i.call(t,e)}))[0]},t.rtlHelpers=null,t.defaultOptions={forceVisible:!1,clickOnTrack:!0,scrollbarMinSize:25,scrollbarMaxSize:0,ariaLabel:"scrollable content",tabIndex:0,classNames:{contentEl:"simplebar-content",contentWrapper:"simplebar-content-wrapper",offset:"simplebar-offset",mask:"simplebar-mask",wrapper:"simplebar-wrapper",placeholder:"simplebar-placeholder",scrollbar:"simplebar-scrollbar",track:"simplebar-track",heightAutoObserverWrapperEl:"simplebar-height-auto-observer-wrapper",heightAutoObserverEl:"simplebar-height-auto-observer",visible:"simplebar-visible",horizontal:"simplebar-horizontal",vertical:"simplebar-vertical",hover:"simplebar-hover",dragging:"simplebar-dragging",scrolling:"simplebar-scrolling",scrollable:"simplebar-scrollable",mouseEntered:"simplebar-mouse-entered"},scrollableNode:null,contentNode:null,autoHide:!0},t.getOptions=B,t.helpers=T,t}(),Y=X.helpers,F=Y.getOptions,I=Y.addClasses,U=Y.canUseDOM,$=function(e){function i(){for(var t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];var r=e.apply(this,t)||this;return i.instances.set(t[0],r),r}return function(e,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function s(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}(i,e),i.initDOMLoadedElements=function(){document.removeEventListener("DOMContentLoaded",this.initDOMLoadedElements),window.removeEventListener("load",this.initDOMLoadedElements),Array.prototype.forEach.call(document.querySelectorAll("[data-simplebar]"),(function(t){"init"===t.getAttribute("data-simplebar")||i.instances.has(t)||new i(t,F(t.attributes))}))},i.removeObserver=function(){var t;null===(t=i.globalObserver)||void 0===t||t.disconnect()},i.prototype.initDOM=function(){var t,e,i,s=this;if(!Array.prototype.filter.call(this.el.children,(function(t){return t.classList.contains(s.classNames.wrapper)})).length){for(this.wrapperEl=document.createElement("div"),this.contentWrapperEl=document.createElement("div"),this.offsetEl=document.createElement("div"),this.maskEl=document.createElement("div"),this.contentEl=document.createElement("div"),this.placeholderEl=document.createElement("div"),this.heightAutoObserverWrapperEl=document.createElement("div"),this.heightAutoObserverEl=document.createElement("div"),I(this.wrapperEl,this.classNames.wrapper),I(this.contentWrapperEl,this.classNames.contentWrapper),I(this.offsetEl,this.classNames.offset),I(this.maskEl,this.classNames.mask),I(this.contentEl,this.classNames.contentEl),I(this.placeholderEl,this.classNames.placeholder),I(this.heightAutoObserverWrapperEl,this.classNames.heightAutoObserverWrapperEl),I(this.heightAutoObserverEl,this.classNames.heightAutoObserverEl);this.el.firstChild;)this.contentEl.appendChild(this.el.firstChild);this.contentWrapperEl.appendChild(this.contentEl),this.offsetEl.appendChild(this.contentWrapperEl),this.maskEl.appendChild(this.offsetEl),this.heightAutoObserverWrapperEl.appendChild(this.heightAutoObserverEl),this.wrapperEl.appendChild(this.heightAutoObserverWrapperEl),this.wrapperEl.appendChild(this.maskEl),this.wrapperEl.appendChild(this.placeholderEl),this.el.appendChild(this.wrapperEl),null===(t=this.contentWrapperEl)||void 0===t||t.setAttribute("tabindex",this.options.tabIndex.toString()),null===(e=this.contentWrapperEl)||void 0===e||e.setAttribute("role","region"),null===(i=this.contentWrapperEl)||void 0===i||i.setAttribute("aria-label",this.options.ariaLabel)}if(!this.axis.x.track.el||!this.axis.y.track.el){var r=document.createElement("div"),l=document.createElement("div");I(r,this.classNames.track),I(l,this.classNames.scrollbar),r.appendChild(l),this.axis.x.track.el=r.cloneNode(!0),I(this.axis.x.track.el,this.classNames.horizontal),this.axis.y.track.el=r.cloneNode(!0),I(this.axis.y.track.el,this.classNames.vertical),this.el.appendChild(this.axis.x.track.el),this.el.appendChild(this.axis.y.track.el)}X.prototype.initDOM.call(this),this.el.setAttribute("data-simplebar","init")},i.prototype.unMount=function(){X.prototype.unMount.call(this),i.instances.delete(this.el)},i.initHtmlApi=function(){this.initDOMLoadedElements=this.initDOMLoadedElements.bind(this),"undefined"!=typeof MutationObserver&&(this.globalObserver=new MutationObserver(i.handleMutations),this.globalObserver.observe(document,{childList:!0,subtree:!0})),"complete"===document.readyState||"loading"!==document.readyState&&!document.documentElement.doScroll?window.setTimeout(this.initDOMLoadedElements):(document.addEventListener("DOMContentLoaded",this.initDOMLoadedElements),window.addEventListener("load",this.initDOMLoadedElements))},i.handleMutations=function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){1===t.nodeType&&(t.hasAttribute("data-simplebar")?!i.instances.has(t)&&document.documentElement.contains(t)&&new i(t,F(t.attributes)):t.querySelectorAll("[data-simplebar]").forEach((function(t){"init"!==t.getAttribute("data-simplebar")&&!i.instances.has(t)&&document.documentElement.contains(t)&&new i(t,F(t.attributes))})))})),t.removedNodes.forEach((function(t){var e;1===t.nodeType&&("init"===t.getAttribute("data-simplebar")?!document.documentElement.contains(t)&&(null===(e=i.instances.get(t))||void 0===e||e.unMount()):Array.prototype.forEach.call(t.querySelectorAll('[data-simplebar="init"]'),(function(t){var e;!document.documentElement.contains(t)&&(null===(e=i.instances.get(t))||void 0===e||e.unMount())})))}))}))},i.instances=new WeakMap,i}(X);return U&&$.initHtmlApi(),$}();