(function (){
'use strict';
var cfg=window.PIPChatbot||{};
function renderMarkdown(text){
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2">$1</a>')
.replace(/((?:^[ \t]*[-*][ \t]+.+\n?)+)/gm, function (block){
var items=block.trim().split('\n').map(function (line){
return '<li>' + line.replace(/^[ \t]*[-*][ \t]+/, '') + '</li>';
}).join('');
return '<ul>' + items + '</ul>';
})
.replace(/\n{2,}/g, '</p><p>')
.replace(/\n/g, '<br>')
.replace(/^/, '<p>').replace(/$/, '</p>');
}
var timeoutMs=(cfg.sessionTimeout||30) * 60 * 1000;
var lastActive=parseInt(sessionStorage.getItem('pip_chat_time')||'0', 10);
if(lastActive&&Date.now() - lastActive > timeoutMs){
['pip_session_id','pip_lead_id','pip_lead_name','pip_lead_email',
'pip_messages','pip_chat_time','pip_auto_opened'].forEach(function (k){
sessionStorage.removeItem(k);
});
}
var sessionId=sessionStorage.getItem('pip_session_id');
if(!sessionId){
sessionId='pip_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now().toString(36);
sessionStorage.setItem('pip_session_id', sessionId);
}
var savedMessages=JSON.parse(sessionStorage.getItem('pip_messages')||'[]');
var state={
open:           false,
leadCaptured:   !!sessionStorage.getItem('pip_lead_id')||cfg.leadMode==='off',
leadId:         sessionStorage.getItem('pip_lead_id')||null,
leadName:       sessionStorage.getItem('pip_lead_name')||'',
leadEmail:      sessionStorage.getItem('pip_lead_email')||'',
skipped:        false,
messages:       savedMessages,
pendingMessage: null,
loading:        false,
initialized:    false,
};
var iconChat='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4a2 2 0 0 0-2 2v18l4-4h14a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';
var iconClose='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>';
var iconSend='';
var el={};
function build(){
if(cfg.primaryColor){
document.documentElement.style.setProperty('--pip-primary', cfg.primaryColor);
}
var wrapper=document.createElement('div');
wrapper.id='pip-chatbot-wrapper';
var toggle=document.createElement('button');
toggle.id='pip-chatbot-toggle';
toggle.setAttribute('aria-label', 'Open PIP chat');
toggle.setAttribute('aria-expanded', 'false');
toggle.innerHTML='<span class="pip-icon-open">' + iconChat + '</span>'
+ '<span class="pip-icon-close">' + iconClose + '</span>'
+ '<span id="pip-chatbot-badge" style="display:none" aria-label="1 unread message">1</span>';
var win=document.createElement('div');
win.id='pip-chatbot-window';
win.setAttribute('aria-label', 'PIP chat window');
win.style.display='none';
var logoHtml;
if(cfg.logoUrl){
logoHtml='<img id="pip-chatbot-header-logo" src="' + cfg.logoUrl + '" alt="' + (cfg.botName||'PIP') + '">';
}else{
logoHtml='<div id="pip-chatbot-header-logo pip-no-logo" aria-hidden="true">P</div>';
}
win.innerHTML =
'<div id="pip-chatbot-header">'
+   logoHtml
+   '<div id="pip-chatbot-header-info">'
+     '<div id="pip-chatbot-header-name">' + esc(cfg.botName||'PIP Assistant') + '</div>'
+     '<div id="pip-chatbot-header-status">Online</div>'
+   '</div>'
+   '<button id="pip-chatbot-header-close" aria-label="Close chat">' + iconClose + '</button>'
+ '</div>'
+ '<div id="pip-chatbot-messages" role="log" aria-live="polite"></div>'
+ '<div id="pip-chatbot-lead-form" style="display:none">'
+   '<p>Could I grab your name and email to get started?</p>'
+   '<input id="pip-lead-name"  class="pip-lead-input" type="text"  placeholder="Your name"  autocomplete="given-name">'
+   '<input id="pip-lead-email" class="pip-lead-input" type="email" placeholder="Your email" autocomplete="email">'
+   '<div id="pip-lead-error" class="pip-lead-error"></div>'
+   '<div class="pip-lead-buttons">'
+     '<button id="pip-lead-submit" class="pip-btn-primary">Start Chatting</button>'
+     '<button id="pip-lead-skip"   class="pip-btn-skip"    style="display:none">Skip</button>'
+   '</div>'
+ '</div>'
+ '<div id="pip-chatbot-input-area" style="display:none">'
+   '<textarea id="pip-chatbot-input" placeholder="Type a message…" rows="1" aria-label="Message input"></textarea>'
+   '<button id="pip-chatbot-send" aria-label="Send message">' + iconSend + '</button>'
+ '</div>'
+ (cfg.teamsEnabled
? '<div id="pip-chatbot-human" style="display:none">'
+   '<button id="pip-human-btn">Talk to a Human</button>'
+ '</div>'
+ '<div id="pip-chatbot-handoff-form" style="display:none">'
+   '<p>Please provide some details before I connect you.</p>'
+   '<input id="pip-handoff-name"  class="pip-lead-input" type="text"  placeholder="Your name">'
+   '<input id="pip-handoff-email" class="pip-lead-input" type="email" placeholder="Email address">'
+   '<input id="pip-handoff-phone" class="pip-lead-input" type="tel"   placeholder="Or phone number">'
+   '<div id="pip-handoff-error" class="pip-lead-error"></div>'
+   '<div class="pip-lead-buttons">'
+     '<button id="pip-handoff-submit" class="pip-btn-primary">Connect Me</button>'
+     '<button id="pip-handoff-cancel" class="pip-btn-skip">Cancel</button>'
+   '</div>'
+ '</div>'
: '');
wrapper.appendChild(toggle);
wrapper.appendChild(win);
document.body.appendChild(wrapper);
el.toggle=toggle;
el.badge=document.getElementById('pip-chatbot-badge');
el.window=win;
el.messages=document.getElementById('pip-chatbot-messages');
el.leadForm=document.getElementById('pip-chatbot-lead-form');
el.leadName=document.getElementById('pip-lead-name');
el.leadEmail=document.getElementById('pip-lead-email');
el.leadError=document.getElementById('pip-lead-error');
el.leadSubmit=document.getElementById('pip-lead-submit');
el.leadSkip=document.getElementById('pip-lead-skip');
el.inputArea=document.getElementById('pip-chatbot-input-area');
el.input=document.getElementById('pip-chatbot-input');
el.send=document.getElementById('pip-chatbot-send');
el.close=document.getElementById('pip-chatbot-header-close');
el.humanBar=document.getElementById('pip-chatbot-human');
el.humanBtn=document.getElementById('pip-human-btn');
el.handoffForm=document.getElementById('pip-chatbot-handoff-form');
el.handoffSubmit=document.getElementById('pip-handoff-submit');
el.handoffCancel=document.getElementById('pip-handoff-cancel');
el.handoffError=document.getElementById('pip-handoff-error');
if(cfg.leadMode==='skip'){
el.leadSkip.style.display='';
}}
function bindEvents(){
el.toggle.addEventListener('click', function (){
state.open ? closeChat():openChat();
});
el.close.addEventListener('click', closeChat);
el.leadSubmit.addEventListener('click', submitLead);
el.leadSkip.addEventListener('click',   skipLead);
el.leadEmail.addEventListener('keydown', function (e){
if(e.key==='Enter'){ submitLead(); }});
el.leadName.addEventListener('keydown', function (e){
if(e.key==='Enter'){ el.leadEmail.focus(); }});
el.send.addEventListener('click', handleSend);
if(el.humanBtn){ el.humanBtn.addEventListener('click',      handleHumanHandoff); }
if(el.handoffSubmit){ el.handoffSubmit.addEventListener('click', submitHandoffForm); }
if(el.handoffCancel){ el.handoffCancel.addEventListener('click', cancelHandoffForm); }
el.input.addEventListener('keydown', function (e){
if(e.key==='Enter'&&!e.shiftKey){
e.preventDefault();
handleSend();
}});
el.input.addEventListener('input', autoResizeInput);
document.addEventListener('keydown', function (e){
if(e.key==='Escape'&&state.open){ closeChat(); }});
}
function openChat(){
state.open=true;
el.toggle.classList.add('pip-is-open');
el.toggle.setAttribute('aria-expanded', 'true');
el.window.style.display='flex';
el.window.classList.add('pip-window-open');
el.badge.style.display='none';
if(!state.initialized){
state.initialized=true;
showWelcome();
}
setTimeout(function (){
if(state.leadCaptured){
el.input.focus();
}else{
el.leadName.focus();
}}, 100);
}
function closeChat(){
state.open=false;
el.toggle.classList.remove('pip-is-open');
el.toggle.setAttribute('aria-expanded', 'false');
el.window.style.display='none';
el.window.classList.remove('pip-window-open');
}
function showWelcome(){
if(state.messages.length > 0){
state.messages.forEach(function (msg){
renderMessage(msg.content, msg.role);
});
showInputArea();
return;
}
var msg=state.proactive ? getProactiveMessage():(cfg.welcomeMessage||"G'day! How can PIP help you today?");
addMessage(msg, 'bot');
if(state.leadCaptured){
showInputArea();
}else{
el.leadForm.style.display='';
}}
function submitLead(){
var name=el.leadName.value.trim();
var email=el.leadEmail.value.trim();
clearLeadError();
if(!name){
showLeadError('Please enter your name.');
el.leadName.classList.add('pip-error');
el.leadName.focus();
return;
}
if(!email||!isValidEmail(email)){
showLeadError('Please enter a valid email address.');
el.leadEmail.classList.add('pip-error');
el.leadEmail.focus();
return;
}
el.leadSubmit.disabled=true;
el.leadSubmit.textContent='Saving…';
var pending=el.input.value.trim()||state.pendingMessage||'';
fetch(cfg.apiBase + 'lead', {
method:  'POST',
headers: {
'Content-Type': 'application/json',
'X-PIP-Nonce':  cfg.nonce,
},
body: JSON.stringify({
name:            name,
email:           email,
initial_message: pending,
session_id:      sessionId,
}),
})
.then(function (r){ return r.json(); })
.then(function (data){
if(data.error){
showLeadError(data.error);
el.leadSubmit.disabled=false;
el.leadSubmit.textContent='Start Chatting';
return;
}
state.leadCaptured=true;
state.leadId=data.lead_id;
state.leadName=name;
state.leadEmail=email;
sessionStorage.setItem('pip_lead_id',    data.lead_id);
sessionStorage.setItem('pip_lead_name',  name);
sessionStorage.setItem('pip_lead_email', email);
el.leadForm.style.display='none';
addMessage('Thanks ' + esc(name) + '! How can I help you today?', 'bot');
showInputArea();
if(pending){
el.input.value='';
sendMessage(pending);
}})
.catch(function (){
showLeadError('Something went wrong. Please try again.');
el.leadSubmit.disabled=false;
el.leadSubmit.textContent='Start Chatting';
});
}
function skipLead(){
state.leadCaptured=true;
state.skipped=true;
el.leadForm.style.display='none';
showInputArea();
el.input.focus();
}
function showLeadError(msg){
el.leadError.textContent=msg;
el.leadError.classList.add('pip-visible');
}
function clearLeadError(){
el.leadError.classList.remove('pip-visible');
el.leadName.classList.remove('pip-error');
el.leadEmail.classList.remove('pip-error');
}
function showInputArea(){
el.inputArea.style.display='';
if(el.humanBar){ el.humanBar.style.display=''; }
el.input.focus();
}
function handleHumanHandoff(){
if(el.humanBtn.disabled){ return; }
if(state.leadId){
fireHandoff(state.leadName, state.leadEmail, '');
return;
}
el.humanBar.style.display='none';
el.inputArea.style.display='none';
el.handoffForm.style.display='';
document.getElementById('pip-handoff-name').focus();
}
function submitHandoffForm(){
var name=document.getElementById('pip-handoff-name').value.trim();
var email=document.getElementById('pip-handoff-email').value.trim();
var phone=document.getElementById('pip-handoff-phone').value.trim();
el.handoffError.textContent='';
el.handoffError.classList.remove('pip-visible');
if(!name){
el.handoffError.textContent='Please enter your name.';
el.handoffError.classList.add('pip-visible');
document.getElementById('pip-handoff-name').focus();
return;
}
if(!email&&!phone){
el.handoffError.textContent='Please enter an email address or phone number.';
el.handoffError.classList.add('pip-visible');
return;
}
if(email&&!isValidEmail(email)){
el.handoffError.textContent='Please enter a valid email address.';
el.handoffError.classList.add('pip-visible');
return;
}
el.handoffSubmit.disabled=true;
el.handoffSubmit.textContent='Connecting\u2026';
fetch(cfg.apiBase + 'lead', {
method:  'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name:            name,
email:           email,
phone:           phone,
initial_message: 'Requested human handoff',
session_id:      sessionId,
}),
})
.then(function (r){ return r.json(); })
.then(function (data){
if(data.lead_id){
state.leadId=data.lead_id;
state.leadName=name;
state.leadEmail=email;
sessionStorage.setItem('pip_lead_id',    data.lead_id);
sessionStorage.setItem('pip_lead_name',  name);
sessionStorage.setItem('pip_lead_email', email);
}
return fireHandoff(name, email, phone);
})
.catch(function (){
el.handoffSubmit.disabled=false;
el.handoffSubmit.textContent='Connect Me';
el.handoffError.textContent='Something went wrong. Please try again.';
el.handoffError.classList.add('pip-visible');
});
}
function cancelHandoffForm(){
el.handoffForm.style.display='none';
el.inputArea.style.display='';
el.humanBar.style.display='';
}
function fireHandoff(name, email, phone){
el.humanBtn&&(el.humanBtn.disabled=true);
var history=state.messages.map(function (m){
return { role: m.role==='bot' ? 'assistant':'user', content: m.content };});
return fetch(cfg.apiBase + 'handoff', {
method:  'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: sessionId,
lead_name:  name||state.leadName||'',
lead_email: email||state.leadEmail||'',
lead_phone: phone||'',
history:    history,
}),
})
.then(function (r){ return r.json(); })
.then(function (){
el.handoffForm&&(el.handoffForm.style.display='none');
el.humanBar&&(el.humanBar.style.display='none');
el.inputArea.style.display='';
addMessage(
"No worries" + (name ? ", " + esc(name):"") + "! I\u2019ve notified our team with your details "
+ "and someone will be in touch shortly. Feel free to keep chatting in the meantime or "
+ "[send us a message](https://pip.com.au/contact-pip/).",
'bot'
);
});
}
function handleSend(){
var text=el.input.value.trim();
if(!text||state.loading){ return; }
if(!state.leadCaptured){
state.pendingMessage=text;
el.leadForm.style.display='';
el.leadName.focus();
return;
}
el.input.value='';
resetInputHeight();
sendMessage(text);
}
function sendMessage(text){
addMessage(text, 'user');
state.loading=true;
el.send.disabled=true;
showTyping();
var history=state.messages.slice(0, -1).map(function (m){
return { role: m.role==='bot' ? 'assistant':'user', content: m.content };});
while (history.length > 0&&history[0].role==='assistant'){
history.shift();
}
fetch(cfg.apiBase + 'message', {
method:  'POST',
headers: {
'Content-Type': 'application/json',
'X-PIP-Nonce':  cfg.nonce,
},
body: JSON.stringify({
message:    text,
history:    history,
lead_id:    state.leadId ? parseInt(state.leadId, 10):null,
session_id: sessionId,
skipped:    state.skipped,
}),
})
.then(function (r){ return r.json(); })
.then(function (data){
hideTyping();
state.loading=false;
el.send.disabled=false;
if(data.reply){
addMessage(data.reply, 'bot');
}else{
console.error('PIP Chatbot API error:', data);
addMessage("Sorry, I'm having trouble right now. Please try again or [contact PIP](https://pip.com.au/contact-pip/).", 'bot');
}
el.input.focus();
})
.catch(function (){
hideTyping();
state.loading=false;
el.send.disabled=false;
addMessage("I lost connection there. Please check your internet and try again.", 'bot');
});
}
function addMessage(content, role){
state.messages.push({ role: role, content: content });
sessionStorage.setItem('pip_messages', JSON.stringify(state.messages));
sessionStorage.setItem('pip_chat_time', Date.now().toString());
renderMessage(content, role);
}
function renderMessage(content, role){
var wrap=document.createElement('div');
wrap.className='pip-msg pip-msg-' + role;
var avatar=document.createElement('div');
avatar.className='pip-msg-avatar';
avatar.textContent=role==='bot' ? 'P':'You';
avatar.setAttribute('aria-hidden', 'true');
var bubble=document.createElement('div');
bubble.className='pip-msg-bubble';
if(role==='bot'){
bubble.innerHTML=renderMarkdown(content);
}else{
bubble.textContent=content;
}
var time=document.createElement('div');
time.className='pip-msg-time';
time.textContent=formatTime(new Date());
var inner=document.createElement('div');
inner.style.maxWidth='100%';
inner.appendChild(bubble);
inner.appendChild(time);
wrap.appendChild(avatar);
wrap.appendChild(inner);
el.messages.appendChild(wrap);
scrollBottom();
}
function showTyping(){
var div=document.createElement('div');
div.id='pip-chatbot-typing';
div.innerHTML =
'<div class="pip-typing-avatar" aria-hidden="true">P</div>'
+ '<div class="pip-typing-bubble">'
+   '<div class="pip-dot"></div><div class="pip-dot"></div><div class="pip-dot"></div>'
+ '</div>';
el.messages.appendChild(div);
scrollBottom();
}
function hideTyping(){
var t=document.getElementById('pip-chatbot-typing');
if(t){ t.remove(); }}
function scrollBottom(){
el.messages.scrollTop=el.messages.scrollHeight;
}
function autoResizeInput(){
el.input.style.height='auto';
el.input.style.height=Math.min(el.input.scrollHeight, 100) + 'px';
}
function resetInputHeight(){
el.input.style.height='38px';
}
function formatTime(d){
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function isValidEmail(e){
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
}
function esc(str){
var d=document.createElement('div');
d.textContent=str;
return d.innerHTML;
}
function getProactiveMessage(){
var path=window.location.pathname.toLowerCase();
if(/nbn|internet|broadband/.test(path))      return "G\u2019day! Looking for a fast, reliable internet connection? I can help you find the right NBN plan.";
if(/managed-it|msp|it-support|helpdesk/.test(path)) return "Need reliable IT support for your business? I can walk you through what PIP\u2019s managed IT service covers.";
if(/medical|health/.test(path))               return "Looking for IT solutions tailored to your medical practice? I\u2019d love to help point you in the right direction.";
if(/ai|artificial-intelligence/.test(path))   return "Curious about AI for your business? PIP can help you get started \u2014 ask me anything!";
if(/cloud/.test(path))                        return "Exploring cloud solutions? I can help match you with the right setup for your business.";
if(/proxmox/.test(path))                      return "Interested in Proxmox infrastructure? I can connect you with our team to discuss your options.";
if(/contact/.test(path))                      return "G\u2019day! Got a question for PIP? I\u2019m here to help right now.";
return cfg.proactiveMessage||"G\u2019day! Can I help you find the right internet or IT solution today?";
}
function schedulePopup(){
var delay=typeof cfg.popupDelay==='number' ? cfg.popupDelay:5000;
if(delay < 0){ return; }
setTimeout(function (){
el.toggle.classList.add('pip-animate-in');
if(!state.initialized&&!sessionStorage.getItem('pip_auto_opened')){
sessionStorage.setItem('pip_auto_opened', '1');
state.proactive=true;
openChat();
}else{
el.badge.style.display='';
}}, delay);
}
function init(){
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded', init);
return;
}
build();
bindEvents();
schedulePopup();
}
init();
})();
(function ($){
("use strict");
$(document).ready(function (){
initYouTubeGallery();
});
function initYouTubeGallery(){
function parseMaybeJSON(val, fallback){
if(typeof val==="string"){
try {
return JSON.parse(val);
} catch (e){
return fallback;
}}
return typeof val==="object"&&val!==null ? val:fallback;
}
function truncateText(text, length){
if(!text) return "";
const width=$(window).width();
let maxLength;
if(width < 600){
maxLength=length.sm||length.lg;
}else if(width < 900){
maxLength=length.md||length.lg;
}else{
maxLength=length.lg;
}
return text.length > maxLength
? text.substring(0, maxLength) + "..."
: text;
}
function sortVideos(videos, sortBy){
const sorted=[...videos];
switch (sortBy){
case "title":
return sorted.sort((a, b)=>
a.title.localeCompare(b.title, undefined, {
sensitivity: "base",
})
);
case "latest":
return sorted.sort((a, b)=>
new Date(b.publishedAt).getTime() -
new Date(a.publishedAt).getTime()
);
case "date":
return sorted.sort((a, b)=>
new Date(a.publishedAt).getTime() -
new Date(b.publishedAt).getTime()
);
case "popular":
return sorted.sort((a, b)=> (b.viewCount||0) - (a.viewCount||0));
default:
return videos;
}}
function getPlaylistId(input){
if(!input) return "";
try {
const url=new URL(input);
if(url.hostname==="www.youtube.com"){
if(url.pathname.startsWith("/channel/")){
return url.pathname.split("/channel/")[1];
}else if(url.pathname.startsWith("/@")){
return url.pathname.substring(2);
}else if(url.searchParams.get("list")){
return url.searchParams.get("list");
}}
return input;
} catch (e){
return input;
}}
function resolveHandleToChannelId(handle, apiKey, callback){
$.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(
handle
)}&type=channel&key=${apiKey}`
)
.done(function (data){
if(data.items&&data.items.length > 0){
callback(data.items[0].snippet.channelId);
}else{
callback(null);
}})
.fail(function (){
callback(null);
});
}
function generatePlayerIframe(videoId, config){
const params=[
`autoplay=${config.autoplay ? "1":"0"}`,
`loop=${config.loop ? "1":"0"}`,
`mute=${config.mute ? "1":"0"}`,
`controls=${config.showPlayerControl ? "1":"0"}`,
`modestbranding=${config.hideYoutubeLogo ? "1":"0"}`,
config.loop ? `playlist=${videoId}`:null,
]
.filter(Boolean)
.join("&");
return `
<div class="ultp-ytg-video-wrapper">
<iframe
src="https://www.youtube.com/embed/${videoId}?${params}"
title="YouTube Video"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
`;
}
function getYoutubeTextContent(
enableTitle,
title,
titleLength,
enableDesc,
description,
descriptionLength,
videoId
){
let html='<div class="ultp-ytg-content">';
if(enableTitle){
html +=`<div class="ultp-ytg-title"><a href="https://www.youtube.com/watch?v=${videoId}" target="_blank" rel="noopener noreferrer">${truncateText(
title,
titleLength
)}</a></div>`;
}
if(enableDesc){
html +=`<div class="ultp-ytg-description">${truncateText(
description,
descriptionLength
)}</div>`;
}
html +="</div>";
return html;
}
$(".wp-block-ultimate-post-youtube-gallery").each(function (){
const $block=$(this);
const $wrapper=$block.find(".ultp-block-wrapper");
let $container=$block.find(".ultp-ytg-view-grid, .ultp-ytg-container");
const $loadMoreBtn=$block.find(".ultp-ytg-loadmore-btn");
const config={
playlistIdOrUrl: $block.data("playlist")||"",
apiKey: $block.data("api-key")||"",
cacheDuration: parseInt($block.data("cache-duration"))||0,
sortBy: $block.data("sort-by")||"date",
galleryLayout: $block.data("gallery-layout")||"grid",
videosPerPage: parseMaybeJSON($block.data("videos-per-page"), {
lg: 9,
md: 6,
sm: 3,
}),
showVideoTitle: $block.data("show-video-title")=="1",
videoTitleLength: parseMaybeJSON($block.data("video-title-length"), {
lg: 50,
md: 50,
sm: 50,
}),
loadMoreEnable: $block.data("load-more-enable")=="1",
moreButtonLabel: $block.data("more-button-label")||"More Videos",
autoplay: $block.data("autoplay")=="1",
loop: $block.data("loop")=="1",
mute: $block.data("mute")=="1",
showPlayerControl: $block.data("show-player-control")=="1",
hideYoutubeLogo: $block.data("hide-youtube-logo")=="1",
showDescription: $block.data("show-description")=="1",
videoDescriptionLength: parseMaybeJSON(
$block.data("video-description-length"),
{
lg: 100,
md: 100,
sm: 100,
}
),
imageHeightRatio: $block.data("image-height-ratio")||"16-9",
galleryColumn: parseMaybeJSON($block.data("gallery-column"), {
lg: 3,
md: 2,
sm: 1,
}),
displayType: $block.data("display-type")||"grid",
enableListView: $block.data("enable-list-view")=="1",
enableIconAnimation: $block.data("enable-icon-animation")=="1",
defaultYoutubeIcon: $block.data("enable-youtube-icon")=="1",
imgHeight: $block.data("img-height"),
};
let playlistId=getPlaylistId(config.playlistIdOrUrl);
if(playlistId.startsWith("@")){
const handle=playlistId.substring(1);
resolveHandleToChannelId(handle, config.apiKey, function (channelId){
if(channelId){
playlistId=channelId;
proceedWithPlaylist(playlistId);
}else{
$wrapper.html('<p style="color:#888">Invalid handle or API key.</p>'
);
}});
}else{
proceedWithPlaylist(playlistId);
}
function proceedWithPlaylist(playlistId){
if(playlistId.startsWith("UC")){
playlistId="UU" + playlistId.substring(2);
}
if(!playlistId||!config.apiKey){
$wrapper.html('<p style="color:#888">Please provide both YouTube playlist ID/URL and API key.</p>'
);
return;
}
let allVideos=[];
let shownCount=config.videosPerPage.lg||9;
let activeVideo=null;
let playingId=null;
function updateResponsiveCounts(){
const width=$(window).width();
if(width < 600){
shownCount=Math.max(shownCount, config.videosPerPage.sm||3);
}else if(width < 900){
shownCount=Math.max(shownCount, config.videosPerPage.md||6);
}else{
shownCount=Math.max(shownCount, config.videosPerPage.lg||9);
}}
function renderPlaylistLayout(videos){
if(!videos.length){
$container.html("<p>No videos found in this playlist.</p>");
return;
}
if(!activeVideo){
activeVideo=videos[0];
}
let html='<div class="ultp-ytg-main">';
const playerWrapper=`
<div class="ultp-ytg-video-wrapper">
<iframe
src="https://www.youtube.com/embed/${activeVideo.videoId}?${[
`autoplay=${config.autoplay ? "1":"0"}`,
`loop=${config.loop ? "1":"0"}`,
`mute=${config.mute ? "1":"0"}`,
`controls=${config.showPlayerControl ? "1":"0"}`,
`modestbranding=${config.hideYoutubeLogo ? "1":"0"}`,
config.loop ? `playlist=${activeVideo.videoId}`:null,
]
.filter(Boolean)
.join("&")}"
title="YouTube Video"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
${getYoutubeTextContent(
config.showVideoTitle,
activeVideo.title,
config.videoTitleLength,
config.showDescription,
activeVideo.description,
config.videoDescriptionLength,
activeVideo.videoId
)}
</div>
`;
html +=playerWrapper;
html +="</div>";
html +='<div class="ultp-ytg-playlist-sidebar">';
html +='<div class="ultp-ytg-playlist-items">';
videos.forEach(function (video){
const isActive=video.videoId===activeVideo.videoId;
html +=`
<div class="ultp-ytg-playlist-item ${
isActive ? "active":""
}" data-video-id="${video.videoId}">
<img src="${video.thumbnail}" alt="${video.title}" loading="lazy" />
<div class="ultp-ytg-playlist-item-content">
<div class="ultp-ytg-playlist-item-title">
${truncateText(video.title, config.videoTitleLength)}
</div>
</div>
</div>
`;
});
html +="</div></div>";
$container.html(html);
}
function renderGridLayout(videos, count){
if(!videos.length){
$container.html("<p>No videos found in this playlist.</p>");
return;
}
const displayedVideos=videos.slice(0, count);
let html="";
displayedVideos.forEach(function (video){
const isPlaying=playingId===video.videoId;
html +=`<div class="ultp-ytg-item${isPlaying ? " active":""}">`;
html +=`<div class="ultp-ytg-video">`;
if(isPlaying){
html +=generatePlayerIframe(video.videoId, config);
}else{
const getSvgIcon=$(".ultp-ytg-play__icon").html();
html +=`
<img src="${video.thumbnail}" alt="${
video.title
}" loading="lazy" data-video-id="${
video.videoId
}" style="cursor:pointer;" />
<div class="ultp-ytg-play__icon${
config.enableIconAnimation ? " ytg-icon-animation":""
}">
${getSvgIcon}
</div>
`;
}
html +=`</div>`;
html +=`<div class="ultp-ytg-inside">`;
html +=getYoutubeTextContent(
config.showVideoTitle,
video.title,
config.videoTitleLength,
config.showDescription,
video.description,
config.videoDescriptionLength,
video.videoId
);
html +=`</div></div>`;
});
$container.html(html);
if(config.loadMoreEnable&&count < videos.length){
$loadMoreBtn.show();
}else{
$loadMoreBtn.hide();
}}
function renderVideos(videos, count){
if(config.galleryLayout==="playlist"){
renderPlaylistLayout(videos);
}else{
renderGridLayout(videos, count);
}}
const cacheKey=`ultp_youtube_gallery_${playlistId}_${config.apiKey}_${config.sortBy}_${config.imgHeight}`;
const duration=config.cacheDuration;
let cached=null;
try {
cached=JSON.parse(localStorage.getItem(cacheKey));
} catch (e){
cached=null;
}
const now=Date.now();
if(cached &&
cached.data &&
cached.timestamp &&
duration > 0 &&
now - cached.timestamp < duration * 1000
){
allVideos=sortVideos(cached.data, config.sortBy);
renderVideos(allVideos, shownCount);
}else{
if(config.galleryLayout!=="playlist"){
$container.html(`
<div class="ultp-ytg-loading gallery-postx gallery-active">
<div class="skeleton-box"></div>
<div class="skeleton-box"></div>
<div class="skeleton-box"></div>
<div class="skeleton-box"></div>
<div class="skeleton-box"></div>
<div class="skeleton-box"></div>
</div>
`);
}else{
$container.html(`
<div class="ultp-ytg-loading ultp-ytg-playlist-loading">
<div class="ytg-loader"></div>
</div>`);
}
$.get("https://www.googleapis.com/youtube/v3/playlistItems", {
part: "snippet",
maxResults: 50,
playlistId: playlistId,
key: config.apiKey,
})
.done(function (data){
setTimeout(function (){
$container.empty();
if(data.error){
$container.html(`<div class="ultp-ytg-error">${
data.error.message||"Failed to fetch playlist."
}</div>`
);
return;
}
const videos=(data.items||[])
.filter(function (item){
return (
item.snippet.title!=="Private video" &&
item.snippet.title!=="Deleted video"
);
})
.map(function (item){
return {
videoId: item.snippet.resourceId.videoId,
title: item.snippet.title,
thumbnail:
(item.snippet.thumbnails &&
item.snippet.thumbnails[config.imgHeight] &&
item.snippet.thumbnails[config.imgHeight].url) ||
item.snippet.thumbnails[config.imgHeight].url ||
item.snippet.thumbnails?.medium?.url ||
"",
publishedAt: item.snippet.publishedAt||"",
description: item.snippet.description||"",
viewCount: 0,
};});
if(config.sortBy==="popular"){
const videoIds=videos.map((v)=> v.videoId).join(",");
$.get(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=${videoIds}&key=${config.apiKey}`
)
.done(function (statsData){
if(statsData.items){
const statsMap={};
statsData.items.forEach(function (item){
statsMap[item.id]=item.statistics.viewCount;
});
videos.forEach(function (v){
v.viewCount=parseInt(statsMap[v.videoId]||0);
});
}
allVideos=sortVideos(videos, config.sortBy);
if(duration > 0){
try {
localStorage.setItem(cacheKey,
JSON.stringify({
data: videos,
timestamp: now,
})
);
} catch (e){
console.warn("Failed to cache videos:", e);
}}
renderVideos(allVideos, shownCount);
})
.fail(function (){
console.warn("Failed to fetch video statistics for popular sorting."
);
allVideos=sortVideos(videos, config.sortBy);
renderVideos(allVideos, shownCount);
});
}else{
allVideos=sortVideos(videos, config.sortBy);
if(duration > 0){
try {
localStorage.setItem(cacheKey,
JSON.stringify({
data: videos,
timestamp: now,
})
);
} catch (e){
console.warn("Failed to cache videos:", e);
}}
renderVideos(allVideos, shownCount);
}}, 2000);
})
.fail(function (){
setTimeout(function (){
$container.empty();
$container.html('<div class="ultp-ytg-error">Failed to fetch videos. Please try again.</div>'
);
}, 3000);
});
}
$block.on("click", ".ultp-ytg-playlist-item", function (){
const videoId=$(this).data("video-id");
if(!videoId) return;
activeVideo=allVideos.find(function (v){
return v.videoId===videoId;
});
if(activeVideo){
renderPlaylistLayout(allVideos);
}});
$block.on("click", ".ultp-ytg-play__icon", function (){
const $img=$(this).siblings("img[data-video-id]");
const videoId=$img.data("video-id");
if(!videoId) return;
const $item=$(this).closest(".ultp-ytg-item");
const $videoDiv=$item.find(".ultp-ytg-video");
$videoDiv.html('<div class="ultp-ytg-loading"><div class="ytg-loader"></div></div>'
);
$item
.addClass("active")
.siblings(".ultp-ytg-item")
.removeClass("active");
setTimeout(function (){
playingId=videoId;
renderGridLayout(allVideos, shownCount);
}, 1000);
});
$block.on("click", ".ultp-ytg-video img[data-video-id]", function (){
const videoId=$(this).data("video-id");
if(!videoId) return;
playingId=videoId;
renderGridLayout(allVideos, shownCount);
});
$loadMoreBtn.on("click", function (){
shownCount +=config.videosPerPage.lg;
renderGridLayout(allVideos, shownCount);
});
$(window).on("resize", function (){
if(allVideos.length){
updateResponsiveCounts();
renderVideos(allVideos, shownCount);
}});
}});
}})(jQuery);
function scrollToQueryId(queryId){
const targetElement=document.getElementById(`uagb-block-queryid-${queryId}`);
if(targetElement){
const rect=targetElement.getBoundingClientRect();
const adminBar=document.querySelector('#wpadminbar');
const adminBarOffSetHeight=adminBar?.offsetHeight||0;
const scrollTop=window?.pageYOffset||document?.documentElement?.scrollTop;
const targetOffset=(rect?.top + scrollTop) - adminBarOffSetHeight;
window.scrollTo({
top: targetOffset,
behavior: 'smooth'
});
}}
function findAncestorWithClass(element, className){
while(element&&! element.classList.contains(className) ){
element=element.parentNode;
}
return element;
}
document.addEventListener('DOMContentLoaded', function (){
function debounce(func, wait){
let timeout;
return function executedFunction(...args){
const context=this;
const later=()=> {
timeout=null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout=setTimeout(later, wait);
};};
function storeActiveFilter(loopBuilder, filterData, filterType){
if(loopBuilder&&filterData){
loopBuilder.setAttribute(`data-active-filter-${filterType}`, filterData);
}}
function getActiveFilter(loopBuilder, filterType){
return loopBuilder?.getAttribute(`data-active-filter-${filterType}`)||null;
}
async function updateContent(event, paged=null, buttonFilter=null, loopParentContainer){
try {
const loopBuilder=loopParentContainer;
const formData=new FormData();
const search=loopBuilder?.querySelector('.uagb-loop-search' )?.value||'';
const sorting=loopBuilder?.querySelector('.uagb-loop-sort' )?.value||'';
const categorySelect=loopBuilder?.querySelector('.uagb-loop-category');
if(categorySelect?.value){
formData.append('category', categorySelect.value);
storeActiveFilter(loopBuilder, categorySelect.value, 'select');
}else{
const storedSelectFilter=getActiveFilter(loopBuilder, 'select');
if(storedSelectFilter){
formData.append('category', storedSelectFilter);
}}
const checkBoxValues=loopBuilder?.querySelectorAll('.uagb-cat-checkbox');
const checkedValues=[];
checkBoxValues?.forEach(checkBox=> {
if(checkBox.checked&&checkBox.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
checkedValues.push(checkBox.value);
}});
let activeButtonData=getActiveFilter(loopBuilder, 'button');
if(! activeButtonData&&buttonFilter?.type){
activeButtonData=buttonFilter.type;
storeActiveFilter(loopBuilder, activeButtonData, 'button');
}
formData.delete('buttonFilter');
formData.delete('checkbox');
formData.delete('category');
loopBuilder.removeAttribute('data-active-filter-checkbox');
loopBuilder.removeAttribute('data-active-filter-select');
loopBuilder.removeAttribute('data-active-filter-button');
if(event.target.classList.contains('uagb-cat-checkbox') ){
if(categorySelect) categorySelect.value='';
formData.append('checkbox', checkedValues);
storeActiveFilter(loopBuilder, JSON.stringify(checkedValues), 'checkbox');
}else if(event.target.classList.contains('uagb-loop-category') ){
checkBoxValues?.forEach(checkBox=> {
if(checkBox.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
checkBox.checked=false;
}});
formData.append('category', categorySelect.value);
storeActiveFilter(loopBuilder, categorySelect.value, 'select');
}else if(buttonFilter?.type){
if(categorySelect) categorySelect.value='';
checkBoxValues?.forEach(checkBox=> {
if(checkBox.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
checkBox.checked=false;
}});
formData.append('buttonFilter', buttonFilter.type);
storeActiveFilter(loopBuilder, buttonFilter.type, 'button');
}
if(search){
formData.append('search', search);
}
if(sorting){
formData.append('sorting', sorting);
}
if(paged){
formData.append('paged', paged);
}
let queryId=null;
if(buttonFilter?.type==='all'){
const el=document.querySelector('[data-query-id]');
if(el){
queryId=el.getAttribute('data-query-id');
}else{
queryId=0;
}}else{
queryId=event.target?.dataset?.uagbBlockQueryId ||
event.target?.parentElement?.dataset?.uagbBlockQueryId ||
event?.dataset?.uagbBlockQueryId ||
event.target.closest('a' )?.getAttribute('data-uagb-block-query-id')||0;
}
scrollToQueryId(queryId);
formData.append('queryId', queryId);
formData.append('block_id', loopBuilder?.getAttribute('data-block_id') );
formData.append('action', 'uagb_update_loop_builder_content');
formData.append('postId', uagb_loop_builder.post_id);
formData.append('postType', uagb_loop_builder.post_type);
formData.append('security', uagb_loop_builder.nonce);
const formDataObj={};
formData.forEach(( value, key)=> {
formDataObj[key]=value;
});
const output=await getUpdatedLoopWrapperContent(formData);
if(output?.content?.wrapper){
const loopElement=loopBuilder?.querySelector('#uagb-block-queryid-' + queryId);
if(loopElement){
loopElement.innerHTML=output.content.wrapper;
}}
if(output?.content?.pagination){
const paginationElements=loopBuilder?.querySelectorAll('#uagb-block-pagination-queryid-' + queryId);
paginationElements?.forEach(element=> {
element.innerHTML=output.content.pagination;
});
}} catch(error){
throw error;
}}
function handleInput(event){
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
const searchInputs=loopParentContainer.querySelectorAll('.uagb-loop-search');
searchInputs.forEach(searchInput=> {
if(searchInput.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
searchInput.value=event.target.value;
}});
updateContent(event, null, null, loopParentContainer);
}
function handleCheckBoxVal(event){
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
const checkBoxValues=loopParentContainer.querySelectorAll('.uagb-cat-checkbox');
const checkedValues=[];
checkBoxValues.forEach(checkBoxVal=> {
const isChecked=checkBoxVal.checked;
if(isChecked&&checkBoxVal.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
checkedValues.push(checkBoxVal.value);
}});
updateContent(event, null, null, loopParentContainer);
}
function handleSelect(event){
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
const sortSelects=loopParentContainer.querySelectorAll('.uagb-loop-sort');
sortSelects.forEach(sortSelect=> {
if(sortSelect.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
sortSelect.value=event.target.value;
}});
updateContent(event, null, null, loopParentContainer);
}
function handleCatSelect(event){
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
const categorySelects=loopParentContainer.querySelectorAll('.uagb-loop-category');
categorySelects.forEach(categorySelect=> {
if(categorySelect.getAttribute('data-uagb-block-query-id')===event.target.dataset.uagbBlockQueryId){
categorySelect.value=event.target.value;
}});
if(!event.target.value||event.target.value===''||event.target.value==='all'){
loopParentContainer.removeAttribute('data-active-filter-select');
}
updateContent(event, null, null, loopParentContainer);
}
function resetValues(container, selector, queryId, resetCallback){
const elements=container.querySelectorAll(selector);
elements.forEach(element=> {
const elementQueryId=element.dataset.uagbBlockQueryId;
if(elementQueryId===queryId){
resetCallback(element);
}});
}
function handleReset(event){
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
let queryId=event.target.parentElement.dataset.uagbBlockQueryId;
if(event.target.tagName.toLowerCase()==='a'){
queryId=event.target.dataset.uagbBlockQueryId;
}else if(event.target.tagName.toLowerCase()==='svg'||event.target.tagName.toLowerCase()==='path'){
queryId=event.target.closest('a' )?.getAttribute('data-uagb-block-query-id');
}
const loopBuilder=findAncestorWithClass(event.target.parentNode, 'wp-block-uagb-loop-builder');
resetValues(loopBuilder, '.uagb-loop-search', queryId, element=> {
element.value='';
});
resetValues(loopBuilder, '.uagb-loop-sort', queryId, element=> {
element.value='';
});
resetValues(loopBuilder, '.uagb-loop-category', queryId, element=> {
element.value='';
});
resetValues(loopBuilder, '.uagb-cat-checkbox', queryId, element=> {
element.checked=false;
});
if(loopBuilder){
loopBuilder.removeAttribute('data-active-filter-select');
loopBuilder.removeAttribute('data-active-filter-checkbox');
loopBuilder.removeAttribute('data-active-filter-button');
}
updateContent(event, null, null, loopParentContainer);
}
const resetButtons=document.querySelectorAll('.uagb-loop-reset');
const searchInputs=document.querySelectorAll('.uagb-loop-search');
searchInputs.forEach(searchInput=> {
const debouncedHandleInput=debounce(handleInput, 250);
searchInput.addEventListener('input', debouncedHandleInput);
});
const sortSelects=document.querySelectorAll('.uagb-loop-sort');
sortSelects.forEach(sortSelect=> {
const debouncedHandleInput=debounce(handleSelect, 250);
sortSelect.addEventListener('change', debouncedHandleInput);
});
const categorySelects=document.querySelectorAll('.uagb-loop-category');
categorySelects.forEach(categorySelect=> {
const debouncedHandleInput=debounce(handleCatSelect, 250);
categorySelect.addEventListener('change', debouncedHandleInput);
});
const checkBoxValues=document.querySelectorAll('.uagb-cat-checkbox');
checkBoxValues.forEach(checkBoxVal=> {
const debouncedHandleInput=debounce(handleCheckBoxVal, 250);
checkBoxVal.addEventListener('click', debouncedHandleInput);
});
resetButtons.forEach(resetButton=> {
const debouncedHandleReset=debounce(handleReset, 250);
resetButton.addEventListener('click', debouncedHandleReset);
});
const oldPaginations=document.querySelectorAll('.wp-block-uagb-loop-builder > :not(.uagb-loop-pagination).wp-block-uagb-buttons');
oldPaginations?.forEach(function(container){
const parentContainer=document.createElement('div');
parentContainer.classList.add('uagb-loop-pagination');
const queryIdPAginationLink=container.querySelector('a').getAttribute('data-uagb-block-query-id');
parentContainer.id='uagb-block-pagination-queryid-'+queryIdPAginationLink;
parentContainer.innerHTML=container.outerHTML;
container.parentNode.insertBefore(parentContainer, container.nextSibling);
container.parentNode.removeChild(container);
});
const paginationContainer=document.querySelectorAll('.uagb-loop-pagination');
paginationContainer.forEach(pagination=> {
pagination.addEventListener('click', function(event){
event.preventDefault();
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
const paged=event.target.dataset.uagbBlockQueryPaged ||
event.target.parentElement.dataset.uagbBlockQueryPaged ||
event?.target?.closest('a' )?.getAttribute('data-uagb-block-query-paged');
const activeButtonData=getActiveFilter(loopParentContainer, 'button');
const activeSelectData=getActiveFilter(loopParentContainer, 'select');
const activeCheckboxData=getActiveFilter(loopParentContainer, 'checkbox');
const formData=new FormData();
if(paged){
formData.append('paged', paged);
}
if(activeButtonData){
formData.append('buttonFilter', activeButtonData);
}else if(activeSelectData){
formData.append('category', activeSelectData);
}else if(activeCheckboxData){
formData.append('checkbox', activeCheckboxData);
}
formData.append('queryId', event.target.dataset.uagbBlockQueryId ||
event.target.parentElement.dataset.uagbBlockQueryId ||
event?.target?.closest('a' )?.getAttribute('data-uagb-block-query-id')||0);
formData.append('block_id', loopParentContainer?.getAttribute('data-block_id') );
formData.append('action', 'uagb_update_loop_builder_content');
formData.append('postId', uagb_loop_builder.post_id);
formData.append('postType', uagb_loop_builder.post_type);
formData.append('security', uagb_loop_builder.nonce);
const search=loopParentContainer?.querySelector('.uagb-loop-search' )?.value||'';
const sorting=loopParentContainer?.querySelector('.uagb-loop-sort' )?.value||'';
if(search){
formData.append('search', search);
}
if(sorting){
formData.append('sorting', sorting);
}
getUpdatedLoopWrapperContent(formData)
.then(output=> {
if(output?.content?.wrapper){
const loopElement=loopParentContainer?.querySelector('#uagb-block-queryid-' + formData.get('queryId') );
if(loopElement){
loopElement.innerHTML=output.content.wrapper;
}}
if(output?.content?.pagination){
const paginationElements=loopParentContainer?.querySelectorAll('#uagb-block-pagination-queryid-' + formData.get('queryId') );
paginationElements?.forEach(element=> {
element.innerHTML=output.content.pagination;
});
}})
.catch(error=> {
throw error;
});
});
});
const categoryButtonFilterContainer=document.querySelectorAll('.uagb-loop-category-inner a');
categoryButtonFilterContainer.forEach(( buttons)=> {
buttons.addEventListener('click', function(event){
event.preventDefault();
const loopParentContainer=this.closest('.wp-block-uagb-loop-builder');
let buttonData=null;
if(event.target.tagName.toLowerCase()==='a'){
buttonData=event.target.children[0].dataset.type;
}else if(event.target.tagName.toLowerCase()==='div'&&event.target.parentElement.tagName.toLowerCase()==='a'){
buttonData=event.target.dataset.type;
}
checkBoxValues?.forEach(checkBox=> {
checkBox.checked=false;
});
if(buttonData==='all'||buttonData===undefined){
loopParentContainer.removeAttribute('data-active-filter-button');
updateContent(event, null, { type: 'all' }, loopParentContainer);
}else if(buttonData){
storeActiveFilter(loopParentContainer, buttonData, 'button');
updateContent(event, null, { type: buttonData }, loopParentContainer);
}});
});
});
function getUpdatedLoopWrapperContent(data){
data.append('action', 'uagb_update_loop_builder_content');
data.append('postId', uagb_loop_builder?.post_id);
data.append('postType', uagb_loop_builder?.what_post_type);
data.append('security', uagb_loop_builder?.nonce)
return fetch(uagb_loop_builder?.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: data,
})
.then(response=> {
if(! response.ok){
throw new Error('Network response was not ok');
}
return response.json();
})
.then(output=> {
if(output.success){
return output.data;
}
throw new Error(output.data.message);
})
.catch(error=> {
throw error;
});
};
const UAGBBlockPositioning={init(t,e){const s=document.querySelector(e);s?.classList.contains("uagb-position__sticky")&&UAGBBlockPositioning.handleSticky(s,t)},handleSticky(t,e){var s=()=>{return document.querySelector("#wpadminbar")?.offsetHeight||0},p=()=>{"undefined"!=typeof AOS&&e?.UAGAnimationType&&(t.dataset.aos=e?.UAGAnimationType,t.dataset.aosDuration=e?.UAGAnimationTime,t.dataset.aosDelay=e?.UAGAnimationDelay,t.dataset.aosEasing=e?.UAGAnimationEasing,t.dataset.aosOnce=!0,setTimeout(()=>{AOS.refreshHard()},100))};const o=t.getBoundingClientRect(),y=e?.isBlockRootParent?null:t.parentElement,i=((t,e,s)=>{const o=document.createElement("div"),i=(o.style.height=e.height+"px",o.style.boxSizing="border-box",window.getComputedStyle(t));return s?(o.style.width="100%",o.style.maxWidth=i.getPropertyValue("max-width")||e.width+"px",o.style.padding=i.getPropertyValue("padding")||0,o.style.margin=i.getPropertyValue("margin")||0,o.style.border=i.getPropertyValue("border")||0,o.style.borderColor="transparent"):(o.style.width=e.width+"px",o.style.margin=i.getPropertyValue("margin")||0),o})(t,o,y);let n,a,l,r;const c={top:0,bottom:0},d={top:0,right:0,bottom:0,left:0};if(e?.UAGStickyRestricted){r=y.getBoundingClientRect();const g=window.getComputedStyle(y);d.top=parseInt(g.getPropertyValue("padding-top")||0,10),d.bottom=parseInt(g.getPropertyValue("padding-bottom")||0,10),c.top=r.top+(window.pageYOffset||0)+d.top,c.bottom=r.bottom+(window.pageYOffset||0)-d.bottom-o.height-s()-(e?.UAGStickyOffset||0)}"bottom"===e?.UAGStickyLocation?(n=o.top+(window.pageYOffset||0)-window.innerHeight+o.height+(e?.UAGStickyOffset||0),a=`${e?.UAGStickyOffset||0}px`,(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)<=n&&!t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.bottom=`calc(${a} - ${window.innerHeight}px)`,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999",setTimeout(()=>{t.style.bottom=a},50)),p(),window.addEventListener("scroll",()=>{(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)<=n?t.classList.contains("uagb-position__sticky--stuck")||(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.bottom=a,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):l>n&&t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.removeChild(i),t.classList.remove("uagb-position__sticky--stuck"),t.style.bottom="",t.style.left="",t.style.width="",t.style.zIndex="")})):(n=o.top+(window.pageYOffset||0)-s()-(e?.UAGStickyOffset||0),a=s()+(e?.UAGStickyOffset||0)+"px",(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)>=n&&!t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),e?.UAGStickyRestricted&&l>=c.bottom?(t.classList.remove("uagb-position__sticky--stuck"),t.classList.add("uagb-position__sticky--restricted"),t.style.top="",t.style.bottom=d.bottom+"px",t.style.left=`${i?.offsetLeft||0}px`):(t.style.top=`calc(${a} - ${window.innerHeight}px)`,t.style.left=o.left+"px",t.style.top=a),t.style.width=o.width+"px",t.style.zIndex="999"),p(),window.addEventListener("scroll",()=>{(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)>=n?t.classList.contains("uagb-position__sticky--stuck")||t.classList.contains("uagb-position__sticky--restricted")?e?.UAGStickyRestricted&&!t.classList.contains("uagb-position__sticky--restricted")&&l>=c.bottom?(t.classList.remove("uagb-position__sticky--stuck"),t.classList.add("uagb-position__sticky--restricted"),t.style.top="",t.style.bottom=d.bottom+"px",t.style.left=`${i?.offsetLeft||0}px`):t.classList.contains("uagb-position__sticky--restricted")&&l<c.bottom&&(t.classList.remove("uagb-position__sticky--restricted"),t.classList.add("uagb-position__sticky--stuck"),t.style.top=a,t.style.bottom="",t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.top=a,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):l<n&&t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.removeChild(i),t.classList.remove("uagb-position__sticky--stuck"),t.style.top="",t.style.left="",t.style.width="",t.style.zIndex="")}))}};
UAGBButtonChild={
init($selector){
const block=document.querySelector($selector);
if(! block){
return;
}
block.addEventListener('focusin', ()=> {
document.addEventListener('keydown', this.handleKeyDown);
});
block.addEventListener('focusout', ()=> {
document.removeEventListener('keydown', this.handleKeyDown);
});
},
handleKeyDown(e){
if(e.key===' '||e.key==='Spacebar'){
if(e.target.tagName==='A'&&e.target.classList.contains('uagb-buttons-repeater') ){
e.preventDefault();
e.target.click();
}}
},
};
document.addEventListener("DOMContentLoaded", function(){ window.addEventListener('load', function(){
UAGBButtonChild.init('.uagb-block-e70a6b71');
});
window.addEventListener('load', function(){
UAGBButtonChild.init('.uagb-block-ed919316');
});
});
astraToggleSetupPro=function(e,t,o){var a,s,n,l=!1;if(0<(a="off-canvas"===e||"full-width"===e?(s=document.querySelectorAll("#ast-mobile-popup, #ast-mobile-header"),(n=t.classList.contains("ast-header-break-point")?document.querySelectorAll("#ast-mobile-header .main-header-menu-toggle"):document.querySelectorAll("#ast-desktop-header .main-header-menu-toggle")).length):t.classList.contains("ast-header-break-point")?(s=document.querySelectorAll("#ast-mobile-header"),(l=!(0<(a=(n=document.querySelectorAll("#ast-mobile-header .main-header-menu-toggle")).length)))?1:a):(s=document.querySelectorAll("#ast-desktop-header"),(n=document.querySelectorAll("#ast-desktop-header .main-header-menu-toggle")).length))||l)for(var r=0;r<a;r++)if(l||(n[r].setAttribute("data-index",r),o[r])||(o[r]=n[r],n[r].removeEventListener("click",astraNavMenuToggle),n[r].addEventListener("click",astraNavMenuToggle,!1)),void 0!==s[r])for(var i,c=0;c<s.length;c++)if(0<(i=document.querySelector("header.site-header").classList.contains("ast-builder-menu-toggle-link")?s[c].querySelectorAll("ul.main-header-menu .menu-item-has-children > .menu-link, ul.main-header-menu .ast-menu-toggle"):s[c].querySelectorAll("ul.main-header-menu .ast-menu-toggle")).length)for(var d=0;d<i.length;d++)i[d].removeEventListener("click",AstraToggleSubMenu),i[d].addEventListener("click",AstraToggleSubMenu,!1)},astraNavMenuTogglePro=function(e,t,o,a){e.preventDefault();var s=e.target.closest("#ast-desktop-header"),n=document.querySelector("#masthead > #ast-desktop-header .ast-desktop-header-content"),l=(s=null!=s&&""!==s?s.querySelector(".main-header-menu-toggle"):document.querySelector("#masthead > #ast-desktop-header .main-header-menu-toggle"),document.querySelector("#masthead > #ast-desktop-header .ast-desktop-header-content .main-header-bar-navigation"));if("desktop"===e.currentTarget.trigger_type)null!==l&&""!==l&&void 0!==l&&(astraToggleClass(l,"toggle-on"),l.classList.contains("toggle-on")?l.style.display="block":l.style.display=""),astraToggleClass(s,"toggled"),s.classList.contains("toggled")?(t.classList.add("ast-main-header-nav-open"),"dropdown"===o&&(n.style.display="block")):(t.classList.remove("ast-main-header-nav-open"),n.style.display="none");else{e=document.querySelectorAll("#masthead > #ast-mobile-header .main-header-bar-navigation"),l=(menu_toggle_all=document.querySelectorAll("#masthead > #ast-mobile-header .main-header-menu-toggle"),"0"),s=!1;if(null!==a.closest("#ast-fixed-header")&&(e=document.querySelectorAll("#ast-fixed-header > #ast-mobile-header .main-header-bar-navigation"),menu_toggle_all=document.querySelectorAll("#ast-fixed-header .main-header-menu-toggle"),l="0",s=!0),void 0===e[l])return!1;for(var r=e[l].querySelectorAll(".menu-item-has-children"),i=0;i<r.length;i++){r[i].classList.remove("ast-submenu-expanded");for(var c=r[i].querySelectorAll(".sub-menu"),d=0;d<c.length;d++)c[d].style.display="none"}-1!==(a.getAttribute("class")||"").indexOf("main-header-menu-toggle")&&(astraToggleClass(e[l],"toggle-on"),astraToggleClass(menu_toggle_all[l],"toggled"),s&&1<menu_toggle_all.length&&astraToggleClass(menu_toggle_all[1],"toggled"),e[l].classList.contains("toggle-on")?(e[l].style.display="block",t.classList.add("ast-main-header-nav-open")):(e[l].style.display="",t.classList.remove("ast-main-header-nav-open")))}};let accountMenuToggle=function(){let n=astraAddon.hf_account_action_type&&"menu"===astraAddon.hf_account_action_type,l=n&&astraAddon.hf_account_show_menu_on&&"click"===astraAddon.hf_account_show_menu_on;var e=document.querySelectorAll(".ast-header-account-wrap");e&&e.forEach(t=>{let o=t.querySelector(".ast-account-nav-menu");function e(e){(l||n&&document.querySelector("body").classList.contains("ast-header-break-point"))&&o&&!t.contains(e.target)&&(o.style.right="",o.style.left="")}t._accountPointerUpHandler||(t._accountPointerUpHandler=e,document.addEventListener("pointerup",e));var a,s=t.querySelector(".ast-header-account-link");s&&(a=function(e){(l||n&&document.querySelector("body").classList.contains("ast-header-break-point"))&&(headerSelectionPosition=e.target.closest(".site-header-section"))&&(headerSelectionPosition.classList.contains("site-header-section-left")?(o.style.left=""===o.style.left?"-100%":"",o.style.right=""===o.style.right?"auto":""):(o.style.right=""===o.style.right?"-100%":"",o.style.left=""===o.style.left?"auto":""))},s._accountClickHandler||(s._accountClickHandler=a,s.addEventListener("click",a)))})},astraColorSwitcher={...astraAddon?.colorSwitcher,init:function(){this?.isInit&&(this.switcherButtons=document.querySelectorAll(".ast-builder-color-switcher .ast-switcher-button"),this.switcherButtons?.length)&&(this.switcherButtons?.forEach(e=>{e?.addEventListener("click",this.toggle)}),this.isDarkPalette&&"system"===this.defaultMode&&this.detectSystemColorScheme(),this.isSwitched)&&this.switchLogo()},detectSystemColorScheme:function(){null===this.getCookie("astraColorSwitcherState")&&window.matchMedia("(prefers-color-scheme: dark)").matches&&!this.isSwitched&&this.toggle()},toggle:function(e){e?.preventDefault();e=astraColorSwitcher;e.isSwitched=!e.isSwitched,e.setCookie("astraColorSwitcherState",e.isSwitched,90),e?.forceReload?window.location.reload():(e.switchPaletteColors(),e.switchIcon(),e.switchLogo(),e.isDarkPalette&&e.handleDarkModeCompatibility())},switchPaletteColors:function(){(this.isSwitched?this?.palettes?.switched:this?.palettes?.default)?.forEach((e,t)=>{document.documentElement.style.setProperty("--ast-global-color-"+t,e),astraAddon?.is_elementor_active&&document.documentElement.style.setProperty("--e-global-color-astglobalcolor"+t,e)})},switchIcon:function(){this.switcherButtons?.forEach(o=>{var[a,s]=o?.querySelectorAll(".ast-switcher-icon");if(a&&s){let[e,t]=this.isSwitched?[s,a]:[a,s];o?.classList.add("ast-animate"),setTimeout(()=>{e?.classList.add("ast-current"),t?.classList.remove("ast-current")},100),setTimeout(()=>o?.classList.remove("ast-animate"),200)}a=this.isSwitched?"defaultText":"switchedText";o?.setAttribute("aria-label",o?.dataset?.[a]||"Switch color palette.")})},switchLogo:function(){this.isDarkPalette&&this?.logos?.switched&&this?.logos?.default&&this.switchColorSwitcherLogo()},switchColorSwitcherLogo:function(){var e,t;let o=[];for(e of[".custom-logo-link:not(.sticky-custom-logo):not(.transparent-custom-logo) .custom-logo",".site-branding .site-logo-img img:not(.ast-sticky-header-logo)",".ast-site-identity .site-logo-img img:not(.ast-sticky-header-logo)"]){var a=document.querySelectorAll(e);if(0<a.length&&0<(o=Array.from(a).filter(e=>!(e.closest(".ast-sticky-header-logo")||e.closest(".sticky-custom-logo")||e.closest(".transparent-custom-logo")||e.classList.contains("ast-sticky-header-logo")))).length)break}o.length&&(t=this.isSwitched?this.logos.switched:this.logos.default)&&this.updateLogoImages(o,t)},updateLogoImages:function(e,o){e.forEach(e=>{var t;e&&e.src!==o&&((t=new Image).onload=function(){e.src=o,e.hasAttribute("srcset")&&e.removeAttribute("srcset"),e.hasAttribute("data-src")&&e.setAttribute("data-src",o)},t.onerror=function(){e.src=o},t.src=o)})},handleDarkModeCompatibility:function(){document.body.classList.toggle("astra-dark-mode-enable")},setCookie:(e,t,o)=>{var a=new Date;a.setTime(a.getTime()+24*o*60*60*1e3),document.cookie=`${e}=${t}; expires=${a.toUTCString()}; path=/`},getCookie:e=>{var t;for(t of document.cookie.split("; ")){var[o,a]=t.split("=");if(o===e)return a}return null}};var accountPopupTrigger=function(){if("undefined"!=typeof astraAddon&&"login"===astraAddon.hf_account_logout_action){var e,o=document.querySelectorAll(".ast-account-action-login");if(o.length){let t=document.querySelector("#ast-hb-account-login-wrap");t&&(e=document.querySelector("#ast-hb-login-close"),o.forEach(function(e){e.addEventListener("click",function(e){e.preventDefault(),t.classList.add("show")})}),e)&&e.addEventListener("click",function(e){e.preventDefault(),t.classList.remove("show")})}}};document.addEventListener("astPartialContentRendered",function(){accountMenuToggle(),accountPopupTrigger()}),window.addEventListener("load",function(){accountMenuToggle(),accountPopupTrigger(),astraColorSwitcher.init()}),document.addEventListener("astLayoutWidthChanged",function(){accountMenuToggle(),accountPopupTrigger()}),document.addEventListener("click",function(e){var e=e.target.closest("a"),t=e&&e.getAttribute("href");t&&-1!==t.indexOf("#")&&(e.closest(".main-header-bar-navigation")||e.closest(".ast-mobile-header-content")||e.closest(".ast-desktop-header-content"))&&setTimeout(function(){var e=document.querySelectorAll(".menu-toggle"),t=document.querySelector(".main-header-bar-navigation");t&&!t.classList.contains("toggle-on")&&e.forEach(function(e){e.classList.remove("toggled"),e.setAttribute("aria-expanded","false")})},10)});((o,r)=>{var s="astHookExtSticky",i=r.document,a=(jQuery(r).outerWidth(),jQuery(r).width()),n={dependent:[],max_width:"",site_layout:"",break_point:920,admin_bar_height_lg:32,admin_bar_height_sm:46,admin_bar_height_xs:0,stick_upto_scroll:0,gutter:0,wrap:"<div></div>",body_padding_support:!0,html_padding_support:!0,active_shrink:!1,shrink:{padding_top:"",padding_bottom:""},sticky_on_device:"desktop",header_style:"none",hide_on_scroll:"no"};function e(t,e){this.element=t,this.options=o.extend({},n,e),this._defaults=n,this._name=s,"1"==this.options.hide_on_scroll&&(this.navbarHeight=o(t).outerHeight()),this.lastScrollTop=0,this.delta=5,this.should_stick=!0,this.hideScrollInterval="",this.init()}e.prototype.stick_me=function(t,e){var o=jQuery(t.element),s=jQuery(r).outerWidth(),i=parseInt(t.options.stick_upto_scroll),a=parseInt(o.parent().attr("data-stick-maxwidth")),n=parseInt(o.parent().attr("data-stick-gutter"));"enabled"==(astraAddon.hook_sticky_header||"")&&(!("desktop"==t.options.sticky_on_device&&astraAddon.hook_custom_header_break_point>s||"mobile"==t.options.sticky_on_device&&astraAddon.hook_custom_header_break_point<=s)&&jQuery(r).scrollTop()>i?"none"==t.options.header_style&&("enabled"==t.options.active_shrink?(t.hasShrink(t,"stick"),i="none",o.hasClass("ast-custom-header")||(i=n),o.parent().css("min-height",o.outerHeight()),o.addClass("ast-header-sticky-active").stop().css({"max-width":a,top:i,"padding-top":t.options.shrink.padding_top,"padding-bottom":t.options.shrink.padding_bottom})):(t.hasShrink(t,"stick"),o.parent().css("min-height",o.outerHeight()),o.addClass("ast-header-sticky-active").stop().css({"max-width":a,top:n,"padding-top":t.options.shrink.padding_top,"padding-bottom":t.options.shrink.padding_bottom})),o.addClass("ast-sticky-shrunk").stop()):t.stickRelease(t)),"enabled"==(astraAddon.hook_sticky_footer||"")&&("desktop"==t.options.sticky_on_device&&astraAddon.hook_custom_footer_break_point>s||"mobile"==t.options.sticky_on_device&&astraAddon.hook_custom_footer_break_point<=s?t.stickRelease(t):(jQuery("body").addClass("ast-footer-sticky-active"),o.parent().css("min-height",o.outerHeight()),o.stop().css({"max-width":a})))},e.prototype.update_attrs=function(){var o,t=this,e=jQuery(t.element),s=parseInt(t.options.gutter),i=t.options.max_width;"none"==t.options.header_style&&(o=e.offset().top||0),"ast-box-layout"!=t.options.site_layout&&(i=jQuery("body").width()),t.options.dependent&&jQuery.each(t.options.dependent,function(t,e){jQuery(e).length&&"on"==jQuery(e).parent().attr("data-stick-support")&&(dependent_height=jQuery(e).outerHeight(),s+=parseInt(dependent_height),o-=parseInt(dependent_height))}),t.options.admin_bar_height_lg&&jQuery("#wpadminbar").length&&782<a&&(s+=parseInt(t.options.admin_bar_height_lg),o-=parseInt(t.options.admin_bar_height_lg)),t.options.admin_bar_height_sm&&jQuery("#wpadminbar").length&&600<=a&&a<=782&&(s+=parseInt(t.options.admin_bar_height_sm),o-=parseInt(t.options.admin_bar_height_sm)),t.options.admin_bar_height_xs&&jQuery("#wpadminbar").length&&(s+=parseInt(t.options.admin_bar_height_xs),o-=parseInt(t.options.admin_bar_height_xs)),t.options.body_padding_support&&(s+=parseInt(jQuery("body").css("padding-top"),10),o-=parseInt(jQuery("body").css("padding-top"),10)),t.options.html_padding_support&&(s+=parseInt(jQuery("html").css("padding-top"),10),o-=parseInt(jQuery("html").css("padding-top"),10)),t.options.stick_upto_scroll=o,"none"==t.options.header_style&&e.parent().css("min-height",e.outerHeight()).attr("data-stick-gutter",parseInt(s)).attr("data-stick-maxwidth",parseInt(i))},e.prototype.hasShrink=function(t,e){o(r).scrollTop()>jQuery(t.element).outerHeight()?jQuery("body").addClass("ast-shrink-custom-header"):jQuery("body").removeClass("ast-shrink-custom-header")},e.prototype.stickRelease=function(t){var e=jQuery(t.element);"enabled"==(astraAddon.hook_sticky_header||"")&&"none"==t.options.header_style&&(e.removeClass("ast-header-sticky-active").stop().css({"max-width":"",top:"",padding:""}),e.parent().css("min-height",""),e.removeClass("ast-sticky-shrunk").stop()),"enabled"==(astraAddon.hook_sticky_footer||"")&&jQuery("body").removeClass("ast-footer-sticky-active")},e.prototype.init=function(){var e,t;jQuery(this.element)&&(e=this,t=jQuery(e.element),parseInt(e.options.gutter),t.position().top,"none"==e.options.header_style&&t.wrap(e.options.wrap).parent().css("min-height",t.outerHeight()).attr("data-stick-support","on").attr("data-stick-maxwidth",parseInt(e.options.max_width)),e.update_attrs(),jQuery(r).on("resize",function(){e.stickRelease(e),e.update_attrs(),e.stick_me(e)}),jQuery(r).on("scroll",function(){e.stick_me(e,"scroll")}),jQuery(i).ready(function(t){e.stick_me(e)}))},o.fn[s]=function(t){return this.each(function(){o.data(this,"plugin_"+s)||o.data(this,"plugin_"+s,new e(this,t))})};var d=jQuery("body").width(),_=astraAddon.site_layout||"",h=astraAddon.hook_sticky_header||"",p=astraAddon.hook_shrink_header||"";sticky_header_on_devices=astraAddon.hook_sticky_header_on_devices||"desktop",site_layout_box_width=astraAddon.site_layout_box_width||1200,hook_sticky_footer=astraAddon.hook_sticky_footer||"",sticky_footer_on_devices=astraAddon.hook_sticky_footer_on_devices||"desktop","ast-box-layout"===_&&(d=parseInt(site_layout_box_width)),jQuery(i).ready(function(t){"enabled"==h&&jQuery(".ast-custom-header").astHookExtSticky({sticky_on_device:sticky_header_on_devices,header_style:"none",site_layout:_,max_width:d,active_shrink:p}),"enabled"==hook_sticky_footer&&jQuery(".ast-custom-footer").astHookExtSticky({sticky_on_device:sticky_footer_on_devices,max_width:d,site_layout:_,header_style:"none"})})})(jQuery,window);(()=>{var e;function o(e){var t=(t=document.body.className).replace(e,"");document.body.className=t}function d(e){e.style.display="block",setTimeout(function(){e.style.opacity=1},1)}function n(e){e.style.opacity="",setTimeout(function(){e.style.display=""},200)}r="iPhone"==navigator.userAgent.match(/iPhone/i)?"iphone":"",e="iPod"==navigator.userAgent.match(/iPod/i)?"ipod":"",document.body.className+=" "+r,document.body.className+=" "+e;for(var t=document.querySelectorAll("a.astra-search-icon:not(.slide-search)"),a=0;t.length>a;a++)t[a].onclick=function(e){var t,a,o,n;if(e.preventDefault(),e=e||window.event,this.classList.contains("header-cover"))for(var s=document.querySelectorAll(".ast-search-box.header-cover"),c=astraAddon.is_header_builder_active||!1,r=0;r<s.length;r++)for(var l=s[r].parentNode.querySelectorAll("a.astra-search-icon"),i=0;i<l.length;i++)l[i]==this&&(d(s[r]),s[r].querySelector("input.search-field").focus(),c?(t=s[r],n=o=a=void 0,document.body.classList.contains("ast-header-break-point")&&(n=document.querySelector(".main-navigation"),a=document.querySelector(".main-header-bar"),o=document.querySelector(".ast-mobile-header-wrap"),null!==a)&&null!==n&&(n=n.offsetHeight,a=a.offsetHeight,o=o.offsetHeight,n=n&&!document.body.classList.contains("ast-no-toggle-menu-enable")?parseFloat(n)-parseFloat(a):parseFloat(a),t.parentNode.classList.contains("ast-mobile-header-wrap")&&(n=parseFloat(o)),t.style.maxHeight=Math.abs(n)+"px")):(a=s[r],t=o=void 0,document.body.classList.contains("ast-header-break-point")&&(t=document.querySelector(".main-navigation"),null!==(o=document.querySelector(".main-header-bar")))&&null!==t&&(t=t.offsetHeight,o=o.offsetHeight,t=t&&!document.body.classList.contains("ast-no-toggle-menu-enable")?parseFloat(t)-parseFloat(o):parseFloat(o),a.style.maxHeight=Math.abs(t)+"px")));else this.classList.contains("full-screen")&&(e=document.getElementById("ast-seach-full-screen-form")).classList.contains("full-screen")&&(d(e),document.body.className+=" full-screen",e.querySelector("input.search-field").focus())};for(var s=document.querySelectorAll(".ast-search-box .close"),a=0,c=s.length;a<c;++a)s[a].onclick=function(e){e=e||window.event;for(var t=this;;){if(t.parentNode.classList.contains("ast-search-box")){n(t.parentNode),o("full-screen");break}if(t.parentNode.classList.contains("site-header"))break;t=t.parentNode}};document.onkeydown=function(e){if(27==e.keyCode)for(var e=document.getElementById("ast-seach-full-screen-form"),t=(null!=e&&(n(e),o("full-screen")),document.querySelectorAll(".ast-search-box.header-cover")),a=0;a<t.length;a++)n(t[a])},window.addEventListener("resize",function(){if("BODY"===document.activeElement.tagName&&"INPUT"!=document.activeElement.tagName){var e=document.querySelectorAll(".ast-search-box.header-cover");if(!document.body.classList.contains("ast-header-break-point"))for(var t=0;t<e.length;t++)e[t].style.maxHeight="",e[t].style.opacity="",e[t].style.display=""}});var r=document.getElementById("close");r&&r.addEventListener("keydown",function(e){"Enter"===e.key?(e.preventDefault(),this.click()):"Tab"===e.key&&e.preventDefault()})})();
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).DOMPurify=t()}(this,(function(){"use strict";const{entries:e,setPrototypeOf:t,isFrozen:n,getPrototypeOf:o,getOwnPropertyDescriptor:r}=Object;let{freeze:i,seal:a,create:l}=Object,{apply:c,construct:s}="undefined"!=typeof Reflect&&Reflect;i||(i=function(e){return e}),a||(a=function(e){return e}),c||(c=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return e.apply(t,o)}),s||(s=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return new e(...n)});const u=D(Array.prototype.forEach),m=D(Array.prototype.lastIndexOf),p=D(Array.prototype.pop),f=D(Array.prototype.push),d=D(Array.prototype.splice),h=D(String.prototype.toLowerCase),g=D(String.prototype.toString),T=D(String.prototype.match),y=D(String.prototype.replace),E=D(String.prototype.indexOf),A=D(String.prototype.trim),_=D(Object.prototype.hasOwnProperty),b=D(RegExp.prototype.test),S=(N=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return s(N,t)});var N;function D(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return c(e,t,o)}}function R(e,o){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h;t&&t(e,null);let i=o.length;for(;i--;){let t=o[i];if("string"==typeof t){const e=r(t);e!==t&&(n(o)||(o[i]=e),t=e)}e[t]=!0}return e}function w(e){for(let t=0;t<e.length;t++){_(e,t)||(e[t]=null)}return e}function C(t){const n=l(null);for(const[o,r]of e(t)){_(t,o)&&(Array.isArray(r)?n[o]=w(r):r&&"object"==typeof r&&r.constructor===Object?n[o]=C(r):n[o]=r)}return n}function O(e,t){for(;null!==e;){const n=r(e,t);if(n){if(n.get)return D(n.get);if("function"==typeof n.value)return D(n.value)}e=o(e)}return function(){return null}}const v=i(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),k=i(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),x=i(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),L=i(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),I=i(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),M=i(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),U=i(["#text"]),z=i(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),P=i(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),F=i(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),H=i(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),B=a(/\{\{[\w\W]*|[\w\W]*\}\}/gm),G=a(/<%[\w\W]*|[\w\W]*%>/gm),W=a(/\$\{[\w\W]*/gm),Y=a(/^data-[\-\w.\u00B7-\uFFFF]+$/),j=a(/^aria-[\-\w]+$/),X=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),q=a(/^(?:\w+script|data):/i),$=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),K=a(/^html$/i),V=a(/^[a-z][.\w]*(-[.\w]+)+$/i);var Z=Object.freeze({__proto__:null,ARIA_ATTR:j,ATTR_WHITESPACE:$,CUSTOM_ELEMENT:V,DATA_ATTR:Y,DOCTYPE_NAME:K,ERB_EXPR:G,IS_ALLOWED_URI:X,IS_SCRIPT_OR_DATA:q,MUSTACHE_EXPR:B,TMPLIT_EXPR:W});const J=1,Q=3,ee=7,te=8,ne=9,oe=function(){return"undefined"==typeof window?null:window};var re=function t(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oe();const o=e=>t(e);if(o.version="3.3.2",o.removed=[],!n||!n.document||n.document.nodeType!==ne||!n.Element)return o.isSupported=!1,o;let{document:r}=n;const a=r,c=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:N,Node:D,Element:w,NodeFilter:B,NamedNodeMap:G=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:W,DOMParser:Y,trustedTypes:j}=n,q=w.prototype,$=O(q,"cloneNode"),V=O(q,"remove"),re=O(q,"nextSibling"),ie=O(q,"childNodes"),ae=O(q,"parentNode");if("function"==typeof N){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let le,ce="";const{implementation:se,createNodeIterator:ue,createDocumentFragment:me,getElementsByTagName:pe}=r,{importNode:fe}=a;let de={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};o.isSupported="function"==typeof e&&"function"==typeof ae&&se&&void 0!==se.createHTMLDocument;const{MUSTACHE_EXPR:he,ERB_EXPR:ge,TMPLIT_EXPR:Te,DATA_ATTR:ye,ARIA_ATTR:Ee,IS_SCRIPT_OR_DATA:Ae,ATTR_WHITESPACE:_e,CUSTOM_ELEMENT:be}=Z;let{IS_ALLOWED_URI:Se}=Z,Ne=null;const De=R({},[...v,...k,...x,...I,...U]);let Re=null;const we=R({},[...z,...P,...F,...H]);let Ce=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Oe=null,ve=null;const ke=Object.seal(l(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let xe=!0,Le=!0,Ie=!1,Me=!0,Ue=!1,ze=!0,Pe=!1,Fe=!1,He=!1,Be=!1,Ge=!1,We=!1,Ye=!0,je=!1,Xe=!0,qe=!1,$e={},Ke=null;const Ve=R({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ze=null;const Je=R({},["audio","video","img","source","image","track"]);let Qe=null;const et=R({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),tt="http://www.w3.org/1998/Math/MathML",nt="http://www.w3.org/2000/svg",ot="http://www.w3.org/1999/xhtml";let rt=ot,it=!1,at=null;const lt=R({},[tt,nt,ot],g);let ct=R({},["mi","mo","mn","ms","mtext"]),st=R({},["annotation-xml"]);const ut=R({},["title","style","font","a","script"]);let mt=null;const pt=["application/xhtml+xml","text/html"];let ft=null,dt=null;const ht=r.createElement("form"),gt=function(e){return e instanceof RegExp||e instanceof Function},Tt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!dt||dt!==e){if(e&&"object"==typeof e||(e={}),e=C(e),mt=-1===pt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ft="application/xhtml+xml"===mt?g:h,Ne=_(e,"ALLOWED_TAGS")?R({},e.ALLOWED_TAGS,ft):De,Re=_(e,"ALLOWED_ATTR")?R({},e.ALLOWED_ATTR,ft):we,at=_(e,"ALLOWED_NAMESPACES")?R({},e.ALLOWED_NAMESPACES,g):lt,Qe=_(e,"ADD_URI_SAFE_ATTR")?R(C(et),e.ADD_URI_SAFE_ATTR,ft):et,Ze=_(e,"ADD_DATA_URI_TAGS")?R(C(Je),e.ADD_DATA_URI_TAGS,ft):Je,Ke=_(e,"FORBID_CONTENTS")?R({},e.FORBID_CONTENTS,ft):Ve,Oe=_(e,"FORBID_TAGS")?R({},e.FORBID_TAGS,ft):C({}),ve=_(e,"FORBID_ATTR")?R({},e.FORBID_ATTR,ft):C({}),$e=!!_(e,"USE_PROFILES")&&e.USE_PROFILES,xe=!1!==e.ALLOW_ARIA_ATTR,Le=!1!==e.ALLOW_DATA_ATTR,Ie=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Me=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Ue=e.SAFE_FOR_TEMPLATES||!1,ze=!1!==e.SAFE_FOR_XML,Pe=e.WHOLE_DOCUMENT||!1,Be=e.RETURN_DOM||!1,Ge=e.RETURN_DOM_FRAGMENT||!1,We=e.RETURN_TRUSTED_TYPE||!1,He=e.FORCE_BODY||!1,Ye=!1!==e.SANITIZE_DOM,je=e.SANITIZE_NAMED_PROPS||!1,Xe=!1!==e.KEEP_CONTENT,qe=e.IN_PLACE||!1,Se=e.ALLOWED_URI_REGEXP||X,rt=e.NAMESPACE||ot,ct=e.MATHML_TEXT_INTEGRATION_POINTS||ct,st=e.HTML_INTEGRATION_POINTS||st,Ce=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&gt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ce.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&gt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ce.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Ce.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ue&&(Le=!1),Ge&&(Be=!0),$e&&(Ne=R({},U),Re=l(null),!0===$e.html&&(R(Ne,v),R(Re,z)),!0===$e.svg&&(R(Ne,k),R(Re,P),R(Re,H)),!0===$e.svgFilters&&(R(Ne,x),R(Re,P),R(Re,H)),!0===$e.mathMl&&(R(Ne,I),R(Re,F),R(Re,H))),_(e,"ADD_TAGS")||(ke.tagCheck=null),_(e,"ADD_ATTR")||(ke.attributeCheck=null),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?ke.tagCheck=e.ADD_TAGS:(Ne===De&&(Ne=C(Ne)),R(Ne,e.ADD_TAGS,ft))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?ke.attributeCheck=e.ADD_ATTR:(Re===we&&(Re=C(Re)),R(Re,e.ADD_ATTR,ft))),e.ADD_URI_SAFE_ATTR&&R(Qe,e.ADD_URI_SAFE_ATTR,ft),e.FORBID_CONTENTS&&(Ke===Ve&&(Ke=C(Ke)),R(Ke,e.FORBID_CONTENTS,ft)),e.ADD_FORBID_CONTENTS&&(Ke===Ve&&(Ke=C(Ke)),R(Ke,e.ADD_FORBID_CONTENTS,ft)),Xe&&(Ne["#text"]=!0),Pe&&R(Ne,["html","head","body"]),Ne.table&&(R(Ne,["tbody"]),delete Oe.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw S('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw S('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');le=e.TRUSTED_TYPES_POLICY,ce=le.createHTML("")}else void 0===le&&(le=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(j,c)),null!==le&&"string"==typeof ce&&(ce=le.createHTML(""));i&&i(e),dt=e}},yt=R({},[...k,...x,...L]),Et=R({},[...I,...M]),At=function(e){f(o.removed,{element:e});try{ae(e).removeChild(e)}catch(t){V(e)}},_t=function(e,t){try{f(o.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){f(o.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Be||Ge)try{At(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},bt=function(e){let t=null,n=null;if(He)e="<remove></remove>"+e;else{const t=T(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===mt&&rt===ot&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=le?le.createHTML(e):e;if(rt===ot)try{t=(new Y).parseFromString(o,mt)}catch(e){}if(!t||!t.documentElement){t=se.createDocument(rt,"template",null);try{t.documentElement.innerHTML=it?ce:o}catch(e){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),rt===ot?pe.call(t,Pe?"html":"body")[0]:Pe?t.documentElement:i},St=function(e){return ue.call(e.ownerDocument||e,e,B.SHOW_ELEMENT|B.SHOW_COMMENT|B.SHOW_TEXT|B.SHOW_PROCESSING_INSTRUCTION|B.SHOW_CDATA_SECTION,null)},Nt=function(e){return e instanceof W&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof G)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Dt=function(e){return"function"==typeof D&&e instanceof D};function Rt(e,t,n){u(e,(e=>{e.call(o,t,n,dt)}))}const wt=function(e){let t=null;if(Rt(de.beforeSanitizeElements,e,null),Nt(e))return At(e),!0;const n=ft(e.nodeName);if(Rt(de.uponSanitizeElement,e,{tagName:n,allowedTags:Ne}),ze&&e.hasChildNodes()&&!Dt(e.firstElementChild)&&b(/<[/\w!]/g,e.innerHTML)&&b(/<[/\w!]/g,e.textContent))return At(e),!0;if(e.nodeType===ee)return At(e),!0;if(ze&&e.nodeType===te&&b(/<[/\w]/g,e.data))return At(e),!0;if(!(ke.tagCheck instanceof Function&&ke.tagCheck(n))&&(!Ne[n]||Oe[n])){if(!Oe[n]&&Ot(n)){if(Ce.tagNameCheck instanceof RegExp&&b(Ce.tagNameCheck,n))return!1;if(Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(n))return!1}if(Xe&&!Ke[n]){const t=ae(e)||e.parentNode,n=ie(e)||e.childNodes;if(n&&t){for(let o=n.length-1;o>=0;--o){const r=$(n[o],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,re(e))}}}return At(e),!0}return e instanceof w&&!function(e){let t=ae(e);t&&t.tagName||(t={namespaceURI:rt,tagName:"template"});const n=h(e.tagName),o=h(t.tagName);return!!at[e.namespaceURI]&&(e.namespaceURI===nt?t.namespaceURI===ot?"svg"===n:t.namespaceURI===tt?"svg"===n&&("annotation-xml"===o||ct[o]):Boolean(yt[n]):e.namespaceURI===tt?t.namespaceURI===ot?"math"===n:t.namespaceURI===nt?"math"===n&&st[o]:Boolean(Et[n]):e.namespaceURI===ot?!(t.namespaceURI===nt&&!st[o])&&!(t.namespaceURI===tt&&!ct[o])&&!Et[n]&&(ut[n]||!yt[n]):!("application/xhtml+xml"!==mt||!at[e.namespaceURI]))}(e)?(At(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!b(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ue&&e.nodeType===Q&&(t=e.textContent,u([he,ge,Te],(e=>{t=y(t,e," ")})),e.textContent!==t&&(f(o.removed,{element:e.cloneNode()}),e.textContent=t)),Rt(de.afterSanitizeElements,e,null),!1):(At(e),!0)},Ct=function(e,t,n){if(ve[t])return!1;if(Ye&&("id"===t||"name"===t)&&(n in r||n in ht))return!1;if(Le&&!ve[t]&&b(ye,t));else if(xe&&b(Ee,t));else if(ke.attributeCheck instanceof Function&&ke.attributeCheck(t,e));else if(!Re[t]||ve[t]){if(!(Ot(e)&&(Ce.tagNameCheck instanceof RegExp&&b(Ce.tagNameCheck,e)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(e))&&(Ce.attributeNameCheck instanceof RegExp&&b(Ce.attributeNameCheck,t)||Ce.attributeNameCheck instanceof Function&&Ce.attributeNameCheck(t,e))||"is"===t&&Ce.allowCustomizedBuiltInElements&&(Ce.tagNameCheck instanceof RegExp&&b(Ce.tagNameCheck,n)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(n))))return!1}else if(Qe[t]);else if(b(Se,y(n,_e,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==E(n,"data:")||!Ze[e]){if(Ie&&!b(Ae,y(n,_e,"")));else if(n)return!1}else;return!0},Ot=function(e){return"annotation-xml"!==e&&T(e,be)},vt=function(e){Rt(de.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||Nt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Re,forceKeepAttr:void 0};let r=t.length;for(;r--;){const i=t[r],{name:a,namespaceURI:l,value:c}=i,s=ft(a),m=c;let f="value"===a?m:A(m);if(n.attrName=s,n.attrValue=f,n.keepAttr=!0,n.forceKeepAttr=void 0,Rt(de.uponSanitizeAttribute,e,n),f=n.attrValue,!je||"id"!==s&&"name"!==s||(_t(a,e),f="user-content-"+f),ze&&b(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,f)){_t(a,e);continue}if("attributename"===s&&T(f,"href")){_t(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){_t(a,e);continue}if(!Me&&b(/\/>/i,f)){_t(a,e);continue}Ue&&u([he,ge,Te],(e=>{f=y(f,e," ")}));const d=ft(e.nodeName);if(Ct(d,s,f)){if(le&&"object"==typeof j&&"function"==typeof j.getAttributeType)if(l);else switch(j.getAttributeType(d,s)){case"TrustedHTML":f=le.createHTML(f);break;case"TrustedScriptURL":f=le.createScriptURL(f)}if(f!==m)try{l?e.setAttributeNS(l,a,f):e.setAttribute(a,f),Nt(e)?At(e):p(o.removed)}catch(t){_t(a,e)}}else _t(a,e)}Rt(de.afterSanitizeAttributes,e,null)},kt=function e(t){let n=null;const o=St(t);for(Rt(de.beforeSanitizeShadowDOM,t,null);n=o.nextNode();)Rt(de.uponSanitizeShadowNode,n,null),wt(n),vt(n),n.content instanceof s&&e(n.content);Rt(de.afterSanitizeShadowDOM,t,null)};return o.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,i=null,l=null;if(it=!e,it&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Dt(e)){if("function"!=typeof e.toString)throw S("toString is not a function");if("string"!=typeof(e=e.toString()))throw S("dirty is not a string, aborting")}if(!o.isSupported)return e;if(Fe||Tt(t),o.removed=[],"string"==typeof e&&(qe=!1),qe){if(e.nodeName){const t=ft(e.nodeName);if(!Ne[t]||Oe[t])throw S("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof D)n=bt("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),r.nodeType===J&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!Be&&!Ue&&!Pe&&-1===e.indexOf("<"))return le&&We?le.createHTML(e):e;if(n=bt(e),!n)return Be?null:We?ce:""}n&&He&&At(n.firstChild);const c=St(qe?e:n);for(;i=c.nextNode();)wt(i),vt(i),i.content instanceof s&&kt(i.content);if(qe)return e;if(Be){if(Ge)for(l=me.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(Re.shadowroot||Re.shadowrootmode)&&(l=fe.call(a,l,!0)),l}let m=Pe?n.outerHTML:n.innerHTML;return Pe&&Ne["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&b(K,n.ownerDocument.doctype.name)&&(m="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+m),Ue&&u([he,ge,Te],(e=>{m=y(m,e," ")})),le&&We?le.createHTML(m):m},o.setConfig=function(){Tt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Fe=!0},o.clearConfig=function(){dt=null,Fe=!1},o.isValidAttribute=function(e,t,n){dt||Tt({});const o=ft(e),r=ft(t);return Ct(o,r,n)},o.addHook=function(e,t){"function"==typeof t&&f(de[e],t)},o.removeHook=function(e,t){if(void 0!==t){const n=m(de[e],t);return-1===n?void 0:d(de[e],n,1)[0]}return p(de[e])},o.removeHooks=function(e){de[e]=[]},o.removeAllHooks=function(){de={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},o}();return re}));