1function brfInitProForms(e=!1){document.querySelectorAll(".brxe-brf-pro-forms").forEach((t=>{setTimeout((()=>{t.classList.contains("form-loading")&&t.classList.remove("form-loading")}),100),("true"!==t.getAttribute("data-initialized")||e)&&(new BrfProForms(t),t.setAttribute("data-initialized","true"),t.style.visibility="visible")}))}function brfScrollVideoInstance(){if(document.querySelector(".brf-scroll-video")){document.querySelectorAll(".brf-scroll-video").forEach((e=>{new BrfScrollVideo(e)}))}}function brfAddToCalenderButton(){document.querySelectorAll(".brxe-brf-add-to-calender-button").forEach((e=>{const t=e.querySelector(".brf-add-to-calendar-button");t&&brfInitCalendarButton(t,e)}))}function brfInitCalendarButton(e,t){const r=e.dataset.calendarType;e.removeEventListener("click",brfHandleCalendarButtonClick),e.addEventListener("click",brfHandleCalendarButtonClick),"multiple"===r&&brfInitMultipleCalendarOptions(e,t)}function brfHandleCalendarButtonClick(e){const t=e.currentTarget,r=t.dataset.calendarType;"ics"===r||"apple"===r?(e.preventDefault(),brfDownloadICSFile(t)):"multiple"===r&&(e.preventDefault(),brfToggleCalendarOptions(t))}function brfInitMultipleCalendarOptions(e,t){const r=t.querySelector(".brf-calendar-options");if(!r)return;const a=r.querySelector(".brf-calendar-dropdown");if(!a)return;const i=a.querySelectorAll(".brf-calendar-option");i.forEach(((t,n)=>{t.addEventListener("click",(i=>{const n=t.dataset.type;"ics"!==n&&"apple"!==n||(i.preventDefault(),brfDownloadICSFile(e)),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"),e.focus()})),t.addEventListener("keydown",(s=>{switch(s.key){case"Enter":case" ":s.preventDefault(),t.click();break;case"Escape":s.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"),e.focus();break;case"ArrowDown":s.preventDefault();(i[n+1]||i[0]).focus();break;case"ArrowUp":s.preventDefault();(i[n-1]||i[i.length-1]).focus()}}))})),e.addEventListener("keydown",(t=>{"Escape"===t.key&&a.classList.contains("show")&&(t.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"))})),e.addEventListener("keydown",(t=>{if("Escape"===t.key&&a.classList.contains("show")){const i=option.dataset.type;"ics"!==i&&"apple"!==i||t.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false")}}))}function brfToggleCalendarOptions(e){const t=e.closest(".brxe-brf-add-to-calender-button"),r=t?t.querySelector(".brf-calendar-options"):null;if(!r)return;const a=r.querySelector(".brf-calendar-dropdown");if(!a)return;if(a.classList.contains("show"))a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false");else{r.setAttribute("aria-hidden","false"),e.setAttribute("aria-expanded","true");const t=e.getBoundingClientRect();a.style.minWidth=Math.max(200,t.width)+"px",a.style.maxWidth="300px",requestAnimationFrame((()=>{requestAnimationFrame((()=>{a.classList.add("show")}))}));const i=a.querySelector(".brf-calendar-option");i&&setTimeout((()=>{i.focus()}),160)}document.addEventListener("click",(function t(i){e.contains(i.target)||r.contains(i.target)||(a.classList.contains("show")&&(a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false")),document.removeEventListener("click",t))}))}function brfDownloadICSFile(e){const t=brfExtractCalendarData(e);if(!t.title)return void console.error("Bricksforge: Missing title in calendar data");const r=brfGenerateICSContent(t),a=new Blob([r],{type:"text/calendar;charset=utf-8"}),i=window.URL.createObjectURL(a),n=document.createElement("a");n.href=i,n.download=(t.filename||"event")+".ics",document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(i)}function brfExtractCalendarData(e){let t=[];if(e.dataset.events)try{t=JSON.parse(e.dataset.events)}catch(e){console.error("Bricksforge: Failed to parse events data:",e)}return{title:e.dataset.title||"",description:e.dataset.description||"",location:e.dataset.location||"",url:e.dataset.url||"",start:e.dataset.start||"",end:e.dataset.end||"",timezone:e.dataset.timezone||"UTC",allDay:"true"===e.dataset.allDay,reminder:e.dataset.reminder||"",filename:e.dataset.f
1ilename||"event",events:t,multipleEvents:"true"===e.dataset.multipleEvents}}function brfGenerateICSContent(e){let t="BEGIN:VCALENDAR\r\n";t+="VERSION:2.0\r\n",t+="PRODID:-//Bricksforge//Add to Calendar Button//EN\r\n",t+="CALSCALE:GREGORIAN\r\n",t+="METHOD:PUBLISH\r\n";const r=e.timezone||"UTC";if("UTC"!==r){t+="X-WR-TIMEZONE:"+r+"\r\n";const e=brfGenerateVTimezoneBlock(r);e&&(t+=e)}return e.events&&e.events.length>0?e.events.forEach(((e,a)=>{!e.timezone&&r&&(e.timezone=r);const i=brfGenerateSingleEventICS(e);t+=i})):(!e.timezone&&r&&(e.timezone=r),t+=brfGenerateSingleEventICS(e)),t+="END:VCALENDAR\r\n",t}function brfGenerateSingleEventICS(e){let t="BEGIN:VEVENT\r\n";t+="UID:"+brfGenerateUID()+"\r\n";const r=new Date,a=brfFormatDateForICS(r,!0);t+="DTSTAMP:"+a+"\r\n",t+="CREATED:"+a+"\r\n",t+="LAST-MODIFIED:"+a+"\r\n",t+="SUMMARY:"+brfEscapeICSText(e.title||e.eventTitle||"")+"\r\n";const i=e.description||e.eventDescription||"";i&&(t+="DESCRIPTION:"+brfEscapeICSText(i)+"\r\n");const n=e.location||e.eventLocation||"";n&&(t+="LOCATION:"+brfEscapeICSText(n)+"\r\n");const s=e.url||e.eventUrl||"";s&&(t+="URL:"+brfEscapeICSText(s)+"\r\n"),t+="STATUS:CONFIRMED\r\n",t+="TRANSP:OPAQUE\r\n";const o=e.timezone||"UTC",l=e.start||e.startDate||"",c=e.end||e.endDate||"";let d=e.startTime||"",u=e.endTime||"";if(!d&&l&&l.includes("T")){const e=l.split("T")[1];e&&(d=e.substring(0,5))}if(!u&&c&&c.includes("T")){const e=c.split("T")[1];e&&(u=e.substring(0,5))}const f=!0===e.allDay||"true"===e.allDay||"true"===e["all-day"]||!0===e["all-day"];if(l)if(f){const e=brfParseDate(l);if(e){if(t+="DTSTART;VALUE=DATE:"+brfFormatDateForICS(e,!1,!0)+"\r\n",c){const e=brfParseDate(c);if(e){t+="DTEND;VALUE=DATE:"+brfFormatDateForICS(e,!1,!0)+"\r\n"}}else{const r=new Date(e);r.setDate(r.getDate()+1);t+="DTEND;VALUE=DATE:"+brfFormatDateForICS(r,!1,!0)+"\r\n"}}}else{let e=null,r=null;if(d){const t=l.includes("T")?l.split("T")[0]+"T"+d+":00":l+"T"+d+":00";e=brfParseDateTime(t)}else e=brfParseDateTime(l+"T09:00:00");if(e){if("UTC"===o){t+="DTSTART:"+brfFormatDateForICS(e,!0)+"\r\n"}else{t+="DTSTART;TZID="+o+":"+brfFormatDateForICS(e,!1,!1,o)+"\r\n"}if(c&&u){const e=c.includes("T")?c.split("T")[0]+"T"+u+":00":c+"T"+u+":00";r=brfParseDateTime(e)}else if(u){const e=l.includes("T")?l.split("T")[0]+"T"+u+":00":l+"T"+u+":00";r=brfParseDateTime(e)}else r=c?brfParseDateTime(c+"T17:00:00"):new Date(e.getTime()+36e5);if(r)if("UTC"===o){t+="DTEND:"+brfFormatDateForICS(r,!0)+"\r\n"}else{t+="DTEND;TZID="+o+":"+brfFormatDateForICS(r,!1,!1,o)+"\r\n"}}}if(!t.includes("DTSTART")){t+="DTSTART:"+brfFormatDateForICS(r,!0)+"\r\n",t+="DTEND:"+brfFormatDateForICS(new Date(r.getTime()+36e5),!0)+"\r\n"}const m=e.reminder||e.reminderMinutes||"";return m&&e.enableReminder&&(t+="BEGIN:VALARM\r\n",t+="TRIGGER:-PT"+parseInt(m)+"M\r\n",t+="ACTION:DISPLAY\r\n",t+="DESCRIPTION:Reminder\r\n",t+="END:VALARM\r\n"),t+="END:VEVENT\r\n",t}function brfGenerateUID(){return"brf-"+Date.now()+"-"+Math.random().toString(36).substr(2,9)+"@"+window.location.hostname}function brfFormatDateForICS(e,t=!1,r=!1,a=null){return r?e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0"):a&&"UTC"!==a&&!t?e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0")+"T"+String(e.getHours()).padStart(2,"0")+String(e.getMinutes()).padStart(2,"0")+String(e.getSeconds()).padStart(2,"0"):t?e.getUTCFullYear()+String(e.getUTCMonth()+1).padStart(2,"0")+String(e.getUTCDate()).padStart(2,"0")+"T"+String(e.getUTCHours()).padStart(2,"0")+String(e.getUTCMinutes()).padStart(2,"0")+String(e.getUTCSeconds()).padStart(2,"0")+"Z":e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0")+"T"+String(e.getHours()).padStart(2,"0")+String(e.getMinutes()).padStart(2,"0")+String(e.getSeconds()).padStart(2,"0")}function brfEscapeICSText(e){return e?e.replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n").replace(/\r/g,""):""}function brfGenerateVTimezoneBlock(e){const t={"America/New_York":"BEGIN:VTIMEZONE\r\nTZID:America/Ne
1w_York\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nTZNAME:EDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nTZNAME:EST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Chicago":"BEGIN:VTIMEZONE\r\nTZID:America/Chicago\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0600\r\nTZOFFSETTO:-0500\r\nTZNAME:CDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0600\r\nTZNAME:CST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Denver":"BEGIN:VTIMEZONE\r\nTZID:America/Denver\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0600\r\nTZNAME:MDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0600\r\nTZOFFSETTO:-0700\r\nTZNAME:MST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Los_Angeles":"BEGIN:VTIMEZONE\r\nTZID:America/Los_Angeles\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0800\r\nTZOFFSETTO:-0700\r\nTZNAME:PDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0800\r\nTZNAME:PST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Phoenix":"BEGIN:VTIMEZONE\r\nTZID:America/Phoenix\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0700\r\nTZNAME:MST\r\nDTSTART:19700101T000000\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","Europe/Berlin":"BEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nTZNAME:CEST\r\nDTSTART:19700329T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nTZNAME:CET\r\nDTSTART:19701025T030000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","Europe/London":"BEGIN:VTIMEZONE\r\nTZID:Europe/London\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:+0000\r\nTZOFFSETTO:+0100\r\nTZNAME:BST\r\nDTSTART:19700329T010000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0000\r\nTZNAME:GMT\r\nDTSTART:19701025T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n"},r={"America/Toronto":"America/New_York","America/Montreal":"America/New_York","America/Vancouver":"America/Los_Angeles","Europe/Paris":"Europe/Berlin","Europe/Rome":"Europe/Berlin","Europe/Madrid":"Europe/Berlin","Europe/Amsterdam":"Europe/Berlin","Europe/Vienna":"Europe/Berlin","Europe/Zurich":"Europe/Berlin","Europe/Stockholm":"Europe/Berlin","Europe/Oslo":"Europe/Berlin","Europe/Copenhagen":"Europe/Berlin","Europe/Warsaw":"Europe/Berlin","Europe/Prague":"Europe/Berlin","Europe/Budapest":"Europe/Berlin","Europe/Brussels":"Europe/Berlin"};if(t[e])return t[e];if(r[e]){const a=t[r[e]];if(a)return a.replace("TZID:"+r[e],"TZID:"+e)}return""}function brfParseDate(e){if(!e)return null;const t=e.split("-");if(3===t.length){const e=parseInt(t[0]),r=parseInt(t[1])-1,a=parseInt(t[2]);if(!isNaN(e)&&!isNaN(r)&&!isNaN(a)){return new Date(e,r,a)}}const r=new Date(e);return isNaN(r.getTime())?null:r}function brfParseDateTime(e,t=null){if(!e)return null;const r=e.split("T");if(2===r.length){const e=r[0],t=r[1].replace(/Z$/,""),a=e.split("-"),i=t.split(":");if(3===a.length&&i.length>=2){const e=new Date(parseInt(a[0]),parseInt(a[1])-1,parseInt(a[2]),parseInt(i[0]),parseInt(i[1]),i[2]?parseInt(i[2]):0);if(!isNaN(e.getTime()))return e}}const a=new Date(e);return isNaN(a.getTime())?null:a}function brfThreeJsHandler(){document.querySelectorAll(".brf-three-js").forEach((e=>{new BrfThreeJs(e)}))}function brfTourHandler(){let e=document.querySelectorAll("[data-brf-tour]");e&&e.forEach((e=>{new BrfTour(e).init()}))}function brfInitProForms(e=!1){document.querySelectorAll(".brxe-brf-pro-forms").forEach((t=>{setTimeout((()=>{t.classList.contains("form-loading")&&t.classList.remove("form-loading")}),100),("true"!==t.getAttribute("data-initialized")||e)&&(new BrfProForms(t),t.setAttribute("data-initialized","true"),t.style.visibility="visible")}))}function brfScrollVideoInstance(){if(document.querySelector(".brf-scroll-video")){document.querySelectorAll(".brf-scroll-video").forEach((e=>{new BrfScrollVideo(e)}))}}function brfAddToCalenderButton(){document.querySelectorAll(".brxe-brf-add-to-calender-button").forEach((e=>{const t=e.querySelector(".brf-add-to-calendar-button");t&&brfInitCalendarButton(t,e)}))}function brfInitCalendarButton(e,t){const r=e.dataset.calendarType;e.removeEventListener("click",brfHandleCalendarButtonClick),e.addEventListener("click",brfHandleCalendarButtonClick),"multiple"===r&&brfInitMultipleCalendarOptions(e,t)}function brfHandleCalendarButtonClick(e){const t=e.currentTarget,r=t.dataset.calendarType;"ics"===r||"apple"===r?(e.preventDefault(),brfDownloadICSFile(t)):"multiple"===r&&(e.preventDefault(),brfToggleCalendarOptions(t))}function brfInitMultipleCalendarOptions(e,t){const r=t.querySelector(".brf-calendar-options");
1if(!r)return;const a=r.querySelector(".brf-calendar-dropdown");if(!a)return;const i=a.querySelectorAll(".brf-calendar-option");i.forEach(((t,n)=>{t.addEventListener("click",(i=>{const n=t.dataset.type;"ics"!==n&&"apple"!==n||(i.preventDefault(),brfDownloadICSFile(e)),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"),e.focus()})),t.addEventListener("keydown",(s=>{switch(s.key){case"Enter":case" ":s.preventDefault(),t.click();break;case"Escape":s.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"),e.focus();break;case"ArrowDown":s.preventDefault();(i[n+1]||i[0]).focus();break;case"ArrowUp":s.preventDefault();(i[n-1]||i[i.length-1]).focus()}}))})),e.addEventListener("keydown",(t=>{"Escape"===t.key&&a.classList.contains("show")&&(t.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"))})),e.addEventListener("keydown",(t=>{if("Escape"===t.key&&a.classList.contains("show")){const i=option.dataset.type;"ics"!==i&&"apple"!==i||t.preventDefault(),a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false")}}))}function brfToggleCalendarOptions(e){const t=e.closest(".brxe-brf-add-to-calender-button"),r=t?t.querySelector(".brf-calendar-options"):null;if(!r)return;const a=r.querySelector(".brf-calendar-dropdown");if(!a)return;if(a.classList.contains("show"))a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false");else{r.setAttribute("aria-hidden","false"),e.setAttribute("aria-expanded","true");const t=e.getBoundingClientRect();a.style.minWidth=Math.max(200,t.width)+"px",a.style.maxWidth="300px",requestAnimationFrame((()=>{requestAnimationFrame((()=>{a.classList.add("show")}))}));const i=a.querySelector(".brf-calendar-option");i&&setTimeout((()=>{i.focus()}),160)}document.addEventListener("click",(function t(i){e.contains(i.target)||r.contains(i.target)||(a.classList.contains("show")&&(a.classList.remove("show"),r.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false")),document.removeEventListener("click",t))}))}function brfDownloadICSFile(e){const t=brfExtractCalendarData(e);if(!t.title)return void console.error("Bricksforge: Missing title in calendar data");const r=brfGenerateICSContent(t),a=new Blob([r],{type:"text/calendar;charset=utf-8"}),i=window.URL.createObjectURL(a),n=document.createElement("a");n.href=i,n.download=(t.filename||"event")+".ics",document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(i)}function brfExtractCalendarData(e){let t=[];if(e.dataset.events)try{t=JSON.parse(e.dataset.events)}catch(e){console.error("Bricksforge: Failed to parse events data:",e)}return{title:e.dataset.title||"",description:e.dataset.description||"",location:e.dataset.location||"",url:e.dataset.url||"",start:e.dataset.start||"",end:e.dataset.end||"",timezone:e.dataset.timezone||"UTC",allDay:"true"===e.dataset.allDay,reminder:e.dataset.reminder||"",filename:e.dataset.filename||"event",events:t,multipleEvents:"true"===e.dataset.multipleEvents}}function brfGenerateICSContent(e){let t="BEGIN:VCALENDAR\r\n";t+="VERSION:2.0\r\n",t+="PRODID:-//Bricksforge//Add to Calendar Button//EN\r\n",t+="CALSCALE:GREGORIAN\r\n",t+="METHOD:PUBLISH\r\n";const r=e.timezone||"UTC";if("UTC"!==r){t+="X-WR-TIMEZONE:"+r+"\r\n";const e=brfGenerateVTimezoneBlock(r);e&&(t+=e)}return e.events&&e.events.length>0?e.events.forEach(((e,a)=>{!e.timezone&&r&&(e.timezone=r);const i=brfGenerateSingleEventICS(e);t+=i})):(!e.timezone&&r&&(e.timezone=r),t+=brfGenerateSingleEventICS(e)),t+="END:VCALENDAR\r\n",t}function brfGenerateSingleEventICS(e){let t="BEGIN:VEVENT\r\n";t+="UID:"+brfGenerateUID()+"\r\n";const r=new Date,a=brfFormatDateForICS(r,!0);t+="DTSTAMP:"+a+"\r\n",t+="CREATED:"+a+"\r\n",t+="LAST-MODIFIED:"+a+"\r\n",t+="SUMMARY:"+brfEscapeICSText(e.title||e.eventTitle||"")+"\r\n";const i=e.description||e.eventDescription||"";i&&(t+="DESCRIPTION:"+brfEscapeICSText(i)+"\r\n");const n=e.location||e.eventLocation||"";n&&(t+="LOCATION:"+brfEscapeICSText(n)+"\r\n");const s=e.url||e.eventUrl||"";s&&(t+="URL:"+brfEscapeICSText(s)+"\r\n"),t+="STATUS:CONFIRMED\r\n",t+="TRANSP:OPAQUE\r\n";
1const o=e.timezone||"UTC",l=e.start||e.startDate||"",c=e.end||e.endDate||"";let d=e.startTime||"",u=e.endTime||"";if(!d&&l&&l.includes("T")){const e=l.split("T")[1];e&&(d=e.substring(0,5))}if(!u&&c&&c.includes("T")){const e=c.split("T")[1];e&&(u=e.substring(0,5))}const f=!0===e.allDay||"true"===e.allDay||"true"===e["all-day"]||!0===e["all-day"];if(l)if(f){const e=brfParseDate(l);if(e){if(t+="DTSTART;VALUE=DATE:"+brfFormatDateForICS(e,!1,!0)+"\r\n",c){const e=brfParseDate(c);if(e){t+="DTEND;VALUE=DATE:"+brfFormatDateForICS(e,!1,!0)+"\r\n"}}else{const r=new Date(e);r.setDate(r.getDate()+1);t+="DTEND;VALUE=DATE:"+brfFormatDateForICS(r,!1,!0)+"\r\n"}}}else{let e=null,r=null;if(d){const t=l.includes("T")?l.split("T")[0]+"T"+d+":00":l+"T"+d+":00";e=brfParseDateTime(t)}else e=brfParseDateTime(l+"T09:00:00");if(e){if("UTC"===o){t+="DTSTART:"+brfFormatDateForICS(e,!0)+"\r\n"}else{t+="DTSTART;TZID="+o+":"+brfFormatDateForICS(e,!1,!1,o)+"\r\n"}if(c&&u){const e=c.includes("T")?c.split("T")[0]+"T"+u+":00":c+"T"+u+":00";r=brfParseDateTime(e)}else if(u){const e=l.includes("T")?l.split("T")[0]+"T"+u+":00":l+"T"+u+":00";r=brfParseDateTime(e)}else r=c?brfParseDateTime(c+"T17:00:00"):new Date(e.getTime()+36e5);if(r)if("UTC"===o){t+="DTEND:"+brfFormatDateForICS(r,!0)+"\r\n"}else{t+="DTEND;TZID="+o+":"+brfFormatDateForICS(r,!1,!1,o)+"\r\n"}}}if(!t.includes("DTSTART")){t+="DTSTART:"+brfFormatDateForICS(r,!0)+"\r\n",t+="DTEND:"+brfFormatDateForICS(new Date(r.getTime()+36e5),!0)+"\r\n"}const m=e.reminder||e.reminderMinutes||"";return m&&e.enableReminder&&(t+="BEGIN:VALARM\r\n",t+="TRIGGER:-PT"+parseInt(m)+"M\r\n",t+="ACTION:DISPLAY\r\n",t+="DESCRIPTION:Reminder\r\n",t+="END:VALARM\r\n"),t+="END:VEVENT\r\n",t}function brfGenerateUID(){return"brf-"+Date.now()+"-"+Math.random().toString(36).substr(2,9)+"@"+window.location.hostname}function brfFormatDateForICS(e,t=!1,r=!1,a=null){return r?e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0"):a&&"UTC"!==a&&!t?e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0")+"T"+String(e.getHours()).padStart(2,"0")+String(e.getMinutes()).padStart(2,"0")+String(e.getSeconds()).padStart(2,"0"):t?e.getUTCFullYear()+String(e.getUTCMonth()+1).padStart(2,"0")+String(e.getUTCDate()).padStart(2,"0")+"T"+String(e.getUTCHours()).padStart(2,"0")+String(e.getUTCMinutes()).padStart(2,"0")+String(e.getUTCSeconds()).padStart(2,"0")+"Z":e.getFullYear()+String(e.getMonth()+1).padStart(2,"0")+String(e.getDate()).padStart(2,"0")+"T"+String(e.getHours()).padStart(2,"0")+String(e.getMinutes()).padStart(2,"0")+String(e.getSeconds()).padStart(2,"0")}function brfEscapeICSText(e){return e?e.replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n").replace(/\r/g,""):""}function brfGenerateVTimezoneBlock(e){const t={"America/New_York":"BEGIN:VTIMEZONE\r\nTZID:America/New_York\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nTZNAME:EDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nTZNAME:EST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Chicago":"BEGIN:VTIMEZONE\r\nTZID:America/Chicago\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0600\r\nTZOFFSETTO:-0500\r\nTZNAME:CDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0600\r\nTZNAME:CST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Denver":"BEGIN:VTIMEZONE\r\nTZID:America/Denver\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0600\r\nTZNAME:MDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0600\r\nTZOFFSETTO:-0700\r\nTZNAME:MST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Los_Angeles":"BEGIN:VTIMEZONE\r\nTZID:America/Los_Angeles\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:-0800\r\nTZOFFSETTO:-0700\r\nTZNAME:PDT\r\nDTSTART:19700308T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0800\r\nTZNAME:PST\r\nDTSTART:19701101T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","America/Phoenix":"BEGIN:VTIMEZONE\r\nTZID:America/Phoenix\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:-0700\r\nTZOFFSETTO:-0700\r\nTZNAME:MST\r\nDTSTART:19700101T000000\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","Europe/Berlin":"BEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nTZNAME:CEST\r\nDTSTART:19700329T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nTZNAME:CET\r\nDTSTART:19701025T030000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n","Europe/London":"BEGIN:VTIMEZONE\r\nTZID:Europe/London\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:+0000\r\nTZOFFSETTO:+0100\r\nTZNAME:BST\r\nDTSTART:19700329T010000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0000\r\nTZNAME:GMT\r\nDTSTART:19701025T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n"}
1,r={"America/Toronto":"America/New_York","America/Montreal":"America/New_York","America/Vancouver":"America/Los_Angeles","Europe/Paris":"Europe/Berlin","Europe/Rome":"Europe/Berlin","Europe/Madrid":"Europe/Berlin","Europe/Amsterdam":"Europe/Berlin","Europe/Vienna":"Europe/Berlin","Europe/Zurich":"Europe/Berlin","Europe/Stockholm":"Europe/Berlin","Europe/Oslo":"Europe/Berlin","Europe/Copenhagen":"Europe/Berlin","Europe/Warsaw":"Europe/Berlin","Europe/Prague":"Europe/Berlin","Europe/Budapest":"Europe/Berlin","Europe/Brussels":"Europe/Berlin"};if(t[e])return t[e];if(r[e]){const a=t[r[e]];if(a)return a.replace("TZID:"+r[e],"TZID:"+e)}return""}function brfParseDate(e){if(!e)return null;const t=e.split("-");if(3===t.length){const e=parseInt(t[0]),r=parseInt(t[1])-1,a=parseInt(t[2]);if(!isNaN(e)&&!isNaN(r)&&!isNaN(a)){return new Date(e,r,a)}}const r=new Date(e);return isNaN(r.getTime())?null:r}function brfParseDateTime(e,t=null){if(!e)return null;const r=e.split("T");if(2===r.length){const e=r[0],t=r[1].replace(/Z$/,""),a=e.split("-"),i=t.split(":");if(3===a.length&&i.length>=2){const e=new Date(parseInt(a[0]),parseInt(a[1])-1,parseInt(a[2]),parseInt(i[0]),parseInt(i[1]),i[2]?parseInt(i[2]):0);if(!isNaN(e.getTime()))return e}}const a=new Date(e);return isNaN(a.getTime())?null:a}function brfThreeJsHandler(){document.querySelectorAll(".brf-three-js").forEach((e=>{new BrfThreeJs(e)}))}function brfTourHandler(){let e=document.querySelectorAll("[data-brf-tour]");e&&e.forEach((e=>{new BrfTour(e).init()}))}function brfFlipEverything(){gsap.utils.toArray(".brf-flip-wrapper").forEach((e=>{let t=e,r=t.querySelector(".brf-flip-box"),a=t.querySelector(".brf-flip-front"),i=t.querySelector(".brf-flip-back");i.style.height=a.getBoundingClientRect().height+"px";let n=t.getAttribute("data-type"),s=t.getAttribute("data-duration"),o=t.getAttribute("data-delay"),l=t.getAttribute("data-trigger"),c=t.getAttribute("data-oncomplete"),d=t.getAttribute("data-onstart"),u=t.getAttribute("data-onreversecomplete");n=n||"flip",s=s||1,o=o||0,l=l||"hover",c=c?new Function(c):"",d=d?new Function(d):"",u=u?new Function(u):"",t.setAttribute("tabindex","0"),t.setAttribute("role","button"),"click"===l?(t.setAttribute("aria-pressed","false"),t.setAttribute("aria-label","Toggle card flip")):t.setAttribute("aria-label","Card with flip animation");const f=gsap.timeline({paused:!0,onStart:function(){"function"==typeof d&&d()},onComplete:function(){"function"==typeof c&&c(),"click"===l&&t.setAttribute("aria-pressed","true")},onReverseComplete:function(){bricksIsFrontend||gsap.set(a,{clearProps:!0}),"click"===l&&t.setAttribute("aria-pressed","false"),"function"==typeof u&&u()}});switch(gsap.set(t,{transformStyle:"preserve-3d",transformPerspective:1e3}),gsap.set(r,{transformStyle:"preserve-3d",transformOrigin:"50% 50%"}),"flip-horizontal"==n||"flip-horizontal-reverse"==n?(gsap.set(i,{rotationY:180,backfaceVisibility:"hidden"}),gsap.set(a,{backfaceVisibility:"hidden"})):gsap.set(i,{rotationY:180,rotationZ:180}),n){case"flip":f.to(a,{rotationX:180,duration:s},o),f.to(i,{rotationX:180,duration:s},o);break;case"flip-reverse":f.to(a,{rotationX:-180,duration:s},o),f.to(i,{rotationX:-180,duration:s},o);break;case"flip-horizontal":f.to(a,{rotationY:180,duration:s},o),f.to(i,{rotationY:360,duration:s},o);break;case"flip-horizontal-reverse":f.to(a,{rotationY:-180,duration:s},o),f.to(i,{rotationY:0,duration:s},o);break;case"fade":t.style.overflow="hidden",gsap.set(i,{}),gsap.set(i,{rotationX:180}),f.to(a,{autoAlpha:0,duration:s},o),f.to(i,{opacity:1,duration:s},o);break;case"fadeShrink":t.style.overflow="hidden",gsap.set(i,{width:i.getBoundingClientRect().width-1}),gsap.set(i,{rotationX:180}),f.to(a,{scale:.8,opacity:0,duration:s/2},o),f.to(i,{opacity:1,duration:s},o);break;case"fadeUp":t.style.overflow="hidden",gsap.set(i,{rotationX:180,translateY:i.offsetHeight,opacity:0}
1),f.to(a,{opacity:1,rotationX:180,duration:s},o),f.to(i,{translateY:0,opacity:1,duration:s},o);break;case"overlay":t.style.overflow="hidden",gsap.set(i,{rotationX:180,translateY:i.offsetHeight+50,zIndex:1}),f.to(i,{translateY:0,zIndex:9999999,duration:s,z:1},o);break;case"overlayShrink":t.style.overflow="hidden",gsap.set(i,{rotationX:180,translateY:i.offsetHeight+50,zIndex:1,scale:.9}),f.to(i,{translateY:0,duration:s,z:1},o)}const m=e=>{if("Enter"===e.key||" "===e.key||"Spacebar"===e.key){const r=option.dataset.type;"ics"!==r&&"apple"!==r||e.preventDefault(),t.classList.contains("active")?(f.reverse(),t.classList.remove("active"),"click"===l&&t.setAttribute("aria-pressed","false")):(f.play(),t.classList.add("active"),"click"===l&&t.setAttribute("aria-pressed","true"))}"Escape"===e.key&&"hover"===l&&(f.reverse(),t.classList.remove("active"))},h=()=>{"hover"===l&&(f.reverse(),t.classList.remove("active"))};switch(l){case"hover":e.addEventListener("mouseenter",(e=>{f.play(),t.classList.add("active")})),e.addEventListener("mouseleave",(e=>{f.reverse(),t.classList.remove("active")})),e.addEventListener("keydown",m),e.addEventListener("blur",h),e.addEventListener("focus",(()=>{}));break;case"click":e.addEventListener("click",(t=>{e.classList.contains("active")?(f.reverse(),e.classList.remove("active")):(e.classList.add("active"),f.play())})),e.addEventListener("keydown",m)}e.addEventListener("focus",(()=>{e.classList.add("brf-flip-focus")})),e.addEventListener("blur",(()=>{e.classList.remove("brf-flip-focus")}))}))}async function brfBeforeAndAfter(){for(let e of document.querySelectorAll(".brf-ba-wrapper")){let t=e.getBoundingClientRect().width,r=e.getBoundingClientRect().height;for(let a of e.querySelectorAll("img"))a.classList.remove("bricks-lazy-hidden"),a.getAttribute("data-src")&&a.setAttribute("src",a.getAttribute("data-src")),a.style.width=t+"px",a.style.height=r+"px",a.ondragstart=function(){return!1};let a=e.querySelector(".brf-ba-handle"),i=e.querySelector(".brf-ba-resize"),n=e;["mousedown","touchstart"].forEach((function(t){a.addEventListener(t,(function(t){t.preventDefault(),a.classList.add("draggable"),i.classList.add("resizable");let r=t.pageX?t.pageX:t.touches[0].pageX,s=a.getBoundingClientRect().width,o=a.offsetLeft+s-r,l=n.offsetLeft,c=n.getBoundingClientRect().width;minLeft=l+10,maxLeft=l+c-s-10,["mousemove","touchmove"].forEach((function(t){a.parentNode.addEventListener(t,(function(t){var r=t.pageX?t.pageX:t.touches[0].pageX;leftValue=r+o-s,leftValue<minLeft?leftValue=minLeft:leftValue>maxLeft&&(leftValue=maxLeft),widthValue=100*(leftValue+s/2-l)/c+"%",e.querySelector(".draggable")&&(e.querySelector(".draggable").style.left=widthValue,["mouseup","touchend"].forEach((function(t){e.querySelector(".draggable").addEventListener(t,(function(){this.classList.remove("draggable"),i.classList.remove("resizable")}))}))),e.querySelector(".resizable")&&(e.querySelector(".resizable").style.width=widthValue)}))})),a.parentNode.addEventListener("mouseup",(function(e){a.classList.remove("draggable"),i.classList.remove("resizable")})),a.parentNode.addEventListener("touchend",(function(e){a.classList.remove("draggable"),i.classList.remove("resizable")}))}))}))}}function brfMegaMenu(){if("undefined"==typeof MegaMenuSettings)return void console.warn("Bricksforge Mega Menu Warning: No Mega Menu data found.");let e=!!MegaMenuSettings&&MegaMenuSettings.data,t=MegaMenuSettings.headerData;if(!t||!t.length)return;let r=t.find((e=>"nav-menu"==e.name&&void 0!==e.settings.activateMegaMenu&&document.querySelector("#brxe-"+e.id))),a=r.settings,i=!!a.activateMegaMenu&&a.activateMegaMenu,n=!!a.menu&&a.menu,s=a.megaMenuTrigger?a.megaMenuTrigger:"hover",o=!!a.megaMenuFullWidth&&a.megaMenuFullWidth,l=a.megaMenuTopSpacing?a.megaMenuTopSpacing:0,c=a.megaMenuCloseSelector?a.megaMenuCloseSelector:"main",d=a.megaMenuCloseEvent?a.megaMenuCloseEvent:"click",u=!!a.megaMenuCloseWhenLeavingNavItem&&a.megaMenuCloseWhenLeavingNavItem,f=a.megaMenuAnimationDuration?a.megaMenuAnimationDuration:150;if(!1===i)return void console.warn("Bricksforge Mega Menu Warning: The Mega Menu is not active.");if(!1===n)return void console.warn('Bricksforge Mega Menu Warning: You have to define a menu for the Nav Item element to use the mega menu. You find the control under: "Select Nav Menu".');if(!document.querySelector("header#brx-header"))return void console.warn("Bricksforge Mega Menu Warning: On this page no header seems to exist");let m=(e,t=!1)=>{let r=e.dataset.navItem;document.querySelectorAll(".bricks-nav-menu li").forEach((e=>{e.classList.remove("megamenu-visible")})),r&&(t||document.querySelector(".bricks-nav-menu li#"+r).classList.add("megamenu-visible"))};for(let t of e){let e=document.createElement("template");e.innerHTML=t;let r=e.content.firstChild;o?document.querySelector("header#brx-header").appendChild(r):document.querySelector("header#brx-header .brxe-container").appendChild(r),(r.querySelector(".brxe-tabs-nested")||r.querySelector(".brxe-tabs"))&&bricksTabs(),(r.querySelector(".brxe-accordion-nested")||r.querySelector(".brxe-accordion"))&&bricksAccordion(),(r.querySelector(".brxe-slider-nested")||r.querySelector(".brxe-slider"))&&bricksSplide()}document.querySelectorAll(".bricks-nav-menu-wrapper li.menu-item").forEach((e=>{e.closest(".wpm-mega-menu")||(e.addEventListener("mouseenter",(()=>{if("hover"==s){let e=document.querySelectorAll(".megamenu-open");for(let t of e)m(t,!0),brfFadeOut(t,f)}})),1==u&&(e.addEventListener("mouseleave",(t=>{var r=e.getBoundingClientRect(),a=r.top+r.height;if(t.pageY>=a-2)return;let i=document.querySelectorAll(".megamenu-open");for(let e of i)m(e,!0),brfFadeOut(e,f),e.classList.remove("megamenu-open")})),document.querySelectorAll(".wpm-mega-menu").forEach((e=>{e.addEventListener("mouseleave",(e=>{let t=document.querySelectorAll(".megamenu-open");for(let e of t)m(e,!0),brfFadeOut(e,f),e.classList.remove("megamenu-open")}))}
1))))})),document.querySelector("#brxe-"+r.id).querySelectorAll(".bricks-nav-menu-wrapper li.menu-item").forEach((e=>{e.addEventListener("click"==s?"click":"mouseenter",(t=>{if(e.closest(".wpm-mega-menu"))return;let r="LI"==t.target.tagName?t.target:t.target.closest("li"),a=document.querySelectorAll(".wpm-mega-menu");for(let e of a){let a=e;if(o?a.style.top=a.closest("header").getBoundingClientRect().height+parseInt(l,10)+"px":(a.style.top=a.closest("header").getBoundingClientRect().height+parseInt(l,10)+"px",t.target.closest(".brxe-container").style.position="relative"),[...r.classList].includes(a.getAttribute("data-nav-item"))){if(t.preventDefault(),a.classList.contains("megamenu-open")&&"click"==s)return m(e,!0),brfFadeOut(e,f),void a.classList.remove("megamenu-open");e.style.opacity=0,m(e),brfFadeIn(e,f),a.classList.add("megamenu-open")}else m(a,!0),brfFadeOut(a,f),a.classList.remove("megamenu-open")}document.querySelector(c)&&document.querySelector(c).addEventListener("click"==d?"click":"mouseenter",(()=>{let e=document.querySelectorAll(".wpm-mega-menu");for(let t of e)0!=t.style.opacity&&"none"!=t.style.display&&(m(t,!0),brfFadeOut(t,f),t.classList.remove("megamenu-open"))}))}))}))}function brfFadeIn(e,t=150){if(0==t)return e.style.display="block",void(e.style.opacity=1);if("undefined"!=typeof gsap)gsap.to(e,{duration:t/1e3,opacity:1,display:"block"});else{e.style.display="block",e.style.opacity=0;let r=null;requestAnimationFrame((function a(i){r||(r=i);let n=i-r,s=n/t;e.style.opacity=Math.min(s,1),n<t&&requestAnimationFrame(a)}))}}function brfFadeOut(e,t=0){if(0==t)return e.style.display="none",void(e.style.opacity=0);if("undefined"!=typeof gsap)gsap.to(e,{duration:t/1e3,opacity:0,display:"none"});else{e.style.opacity=1;let r=null;requestAnimationFrame((function a(i){r||(r=i);let n=i-r,s=1-n/t;e.style.opacity=Math.max(s,0),n<t?requestAnimationFrame(a):e.style.display="none"}))}}function brfToc(){let e=document.querySelector(".brf-toc-content");if(document.querySelectorAll(".brf-toc-content").forEach((t=>{t.children.length>0?e=t:t.remove(),"none"==t.style.display&&t.remove()})),!e)return;if(!bricksIsFrontend)return;if(e.dataset.status&&"hidden"==e.dataset.status)return void document.querySelector("#brf-toc").closest(".brf-toc").remove();let t=document.createDocumentFragment();t.appendChild(e),document.getElementById("brf-toc").appendChild(t),e.style.display="block"}async function brfWaitForBuilder(e=500){return new Promise((async t=>{setTimeout((function(){t()}),e)}))}function brfIsParsable(e){try{JSON.parse(e)}catch(e){return!1}return!0}function brfGetParents(e,t){void 0===t&&(t=document);for(var r=[],a=e.parentNode;a!==t;){var i=a;r.push(i),a=i.parentNode}return r.push(t),r}function brfQuill(e){let t=e?[e]:document.querySelectorAll(".brf-rich-text-container");t&&t.length&&(brfInitialFields.push({type:"richText",html:t[0].outerHTML}),t.forEach((e=>{let t=e.closest(".form-group"),r=t.dataset.theme?t.dataset.theme:"snow",a=t.dataset.placeholder?t.dataset.placeholder:"",i="true"==t.dataset.readonly,n=t.dataset.formats?t.dataset.formats.split(","):["header","bold","italic","underline","link"],s=t.dataset.formatsMce?t.dataset.formatsMce:"undo redo | formatselect | bold italic | alignleft aligncenter alignright al
1ignjustify | bullist numlist outdent indent | link image",o=!!n.includes("header")&&[1,2,3,4,5,6,!1],l=!!n.includes("orderedList")&&{list:"ordered"},c=!!n.includes("bulletList")&&{list:"bullet"},d=!!n.includes("color")&&{color:[]},u=!!n.includes("background")&&{background:[]},f=!!n.includes("indent")&&{indent:"+1"},m=!!n.includes("outdent")&&{indent:"-1"},h=!!n.includes("align")&&{align:[]},p=!!n.includes("direction")&&{direction:"rtl"},b=!!t.dataset.colors&&t.dataset.colors.split(",");b&&(d&&(d={color:b}),u&&(u={background:b}));const g=t.dataset.minHeight?t.dataset.minHeight:null;if(g){const t=/[a-z%]$/i.test(g);e.style.minHeight=t?g:g+"px",setTimeout((()=>{const r=e.querySelector(".ql-editor");r&&(r.style.minHeight=t?g:g+"px")}),100)}let y=[];o&&(y.push([{header:o}]),n.splice(n.indexOf("header"),1)),l&&n.splice(n.indexOf("orderedList"),1),c&&n.splice(n.indexOf("bulletList"),1),d&&n.splice(n.indexOf("color"),1),u&&n.splice(n.indexOf("background"),1),f&&n.splice(n.indexOf("indent"),1),m&&n.splice(n.indexOf("outdent"),1),h&&n.splice(n.indexOf("align"),1),p&&n.splice(n.indexOf("direction"),1);let S=[...n,l,c,d,u,f,m,h,p].filter((e=>!1!==e));if(n&&y.push(S),"wordpress"==r)return void tinymce.init({selector:"textarea#"+e.id,toolbar:s,statusbar:!1,placeholder:a,setup:function(e){const r=()=>{let r=t.querySelector("input[type=hidden]");r.value=e.getContent(),r.dispatchEvent(new Event("input",{bubbles:!0}))};e.on("input",r),e.on("ExecCommand",r)}});class v extends Quill.import("parchment").EmbedBlot{static blotName="sbreak";static tagName="br"}Quill.register(v);const w={theme:"bubble",readOnly:i,placeholder:a,theme:r,modules:{toolbar:y,clipboard:{matchVisual:!1,matchers:[["BR",function(){const e=new(Quill.import("delta"));return e.insert({sbreak:""}),e}]]},keyboard:{bindings:{"soft break":{key:"Enter",shiftKey:!0,handler:function(e){!function(e,t){e.insertEmbed(t.index,"sbreak",!0,"user"),e.setSelection(t.index+1,Quill.sources.SILENT),e.insertEmbed(t.index+1,"sbreak",!0,"user")}(this.quill,e)}}}}}};if(!e.classList.contains("ql-container")){const r=new Quill(e,w);r.root.innerHTML&&(t.querySelector("input[type=hidden]").value=r.root.innerHTML);const a=t.querySelector("input[type=hidden]");if(a&&a.hasAttribute("required")){const t=document.createElement("input");t.type="text",t.style.position="absolute",t.style.opacity="0",t.style.pointerEvents="none",t.style.top="0",t.style.left="0",t.style.width="100%",t.style.height="100%",t.style.zIndex="-1",t.setAttribute("required","required"),t.setAttribute("data-type","rich-text-validation"),t.setAttribute("tabindex","-1");const r=!a.value||"<p><br></p>"===a.value;t.value=r?"":"has-content",e.style.position="relative",e.appendChild(t),a.removeAttribute("required"),a.dataset.validationInput="true"}r.on("text-change",(function(){let e=t.querySelector("input[type=hidden]");e.value=r.root.innerHTML;const a=t.querySelector("input[data-type='rich-text-validation']");if(a){const e=""===r.getText().trim()||"<p><br></p>"===r.root.innerHTML;a.value=e?"":"has-content"}e.dispatchEvent(new Event("input",{bubbles:!0}));let i=new CustomEvent("brfQuillChange",{detail:{quill:r,input:e}});document.dispatchEvent(i);let n=document.querySelectorAll(".brf-live-value");n&&n.forEach((t=>{let r=!!t.dataset.connection&&t.dataset.connection;if(r&&e&&e.name=="form-field-"+r){const r=t.dataset.prefix?t.dataset.prefix:"",a=t.dataset.suffix?t.dataset.suffix:"";if(e.value&&"<p><br></p>"!=e.value){let i=e.value.replace(/\n/g,"<br>");t.innerHTML=r+i+a}else if(t.dataset.fallback){let e=t.dataset.fallback.replace(/\n/g,"<br>");t.innerHTML=r+e+a}else t.innerHTML=r+e.value+a}}))})),bricksIsFrontend||e.closest(".form-group").querySelectorAll(".ql-toolbar").length>1&&e.closest(".form-group").querySelector(".ql-toolbar").remove(),bricksIsFrontend&&(e.style.visibility="visible")}})))}function brfInitFileFields(){const e=document.querySelectorAll(".brxe-brf-pro-forms input[type=file]");e&&0!=e.length&&"function"==typeof window.bricksforgeData.initFileField&&e.forEach((e=>{window.bricksforgeData.initFileField(e)}))}function brfProFormsSlider(){let e=document.querySelectorAll(".brxe-brf-pro-forms .slider:not([data-sli
1der-created])");e&&e.forEach((e=>{let t=e.dataset.settings;t&&(t=JSON.parse(t));noUiSlider.create(e,t);e.setAttribute("data-slider-created",!0)}))}function brfBricksGlobalProps(e){try{const t=(e||window).document.querySelector(".brx-body"),r=t&&t.__vue_app__;return r&&r.config&&r.config.globalProperties||null}catch(e){return null}}function brfProForms(){bricksIsFrontend||brfProFormsBuilderInit(0)}function brfProFormsBuilderInit(e){let t=null;try{t=window.parent.document.querySelector("[id^=bricks-toolbar] .save")}catch(e){t=null}if(null!==brfBricksGlobalProps(window.parent)&&t||!(e<60))try{BrfProForms.populateControlData(),BrfProForms.handleDefaultEmailContent(),t&&t.addEventListener("mouseenter",(()=>{BrfProForms.handleDefaultEmailContent()})),document.querySelectorAll(".brxe-brf-pro-forms").forEach((e=>{BrfProForms.handleGroups(e,!0),new BrfProForms(e,!0).handleSelectFields()}))}catch(e){console.warn("[Bricksforge] Pro Forms builder init skipped:",e)}else{const t=()=>brfProFormsBuilderInit(e+1);"function"==typeof window.requestAnimationFrame?requestAnimationFrame(t):setTimeout(t,50)}}function brfProFormsRating(){if(bricksIsFrontend)return;let e=document.querySelectorAll(".brxe-brf-pro-forms-field-rating");e&&0!=e.length&&e.forEach((e=>{const t=e.querySelector("input[type='hidden']");let r=t.dataset.settings?JSON.parse("{"+t.dataset.settings.match(/\{(.*)\}/)[1]+"}"):{};const a=e.querySelectorAll(".brf-pro-forms-rating-icon");let i=r.iconColorHover,n=r.defaultRating;if(i.raw?i=i.raw:i.hex&&(i=i.hex),n){const e=n-1;a.forEach(((t,r)=>{r<=e&&(t.style.color=i)}))}}))}localFrames=[],brfInitialFields=[],brfLocalFiles={},document.addEventListener("bricks/ajax/popup/loaded",(e=>{brfInitProForms(),brfQuill()})),document.addEventListener("bricks/ajax/query_result/completed",(e=>{setTimeout((()=>{brfInitProForms(),brfQuill(),brfInitFileFields(),brfBeforeAndAfter()}))})),document.addEventListener("jet-smart-filters/inited",(function(e){"undefined"!=typeof JetSmartFilters&&JetSmartFilters.events.subscribe("ajaxFilters/updated",(function(e,t,r){brfInitProForms(),brfQuill()}))})),document.addEventListener("DOMContentLoaded",(function(){brfScrollVideoInstance(),window.bricksforgeData=window.bricksforgeData||{},setTimeout((()=>{document.querySelector(".brxe-brf-pro-forms")&&bricksIsFrontend&&brfInitProForms()}),0),void 0!==window.WP_Grid_Builder&&window.WP_Grid_Builder&&WP_Grid_Builder.on("init",(function(e){e.facets.on("loaded",(function(e){setTimeout((()=>{brfInitProForms(),brfQuill()}),0)}))})),document.querySelector(".brxe-brf-add-to-calender-button")&&brfAddToCalenderButton()})),window.addEventListener("load",(()=>{setTimeout((()=>{brfQuill()}),10),bricksIsFrontend&&(document.querySelector(".brf-flip-wrapper")&&brfFlipEverything(),document.querySelector("#brf-toc")&&brfToc(),document.querySelector(".brf-three-js")&&bricksIsFrontend&&brfThreeJsHandler(),document.querySelector("[data-brf-tour]")&&brfTourHandler(),"undefined"!=typeof MegaMenuSettings&&MegaMenuSettings.megaMenuActivated&&brfMegaMenu()),document.querySelector(".brf-before-and-after")&&brfBeforeAndAfter()})),window.addEventListener("resize",(function(){if(document.querySelector(".brf-ba-wrapper"))for(let e of document.querySelectorAll(".brf-ba-wrapper")){let t=e.getBoundingClientRect().width,r=e.getBoundingClientRect().height;for(let a of e.querySelectorAll("img"))a.classList.remove("bricks-lazy-hidden"),a.getAttribute("data-src")&&a.setAttribute("src",a.getAttribute("data-src")),a.style.width=t+"px",a.style.height=r+"px",a.ondragstart=function(){return!1}}})),localFrames=[],brfInitialFields=[],brfLocalFiles={},document.addEventListener("bricks/ajax/popup/loaded",(e=>{brfInitProForms(),brfQuill()})),document.addEventListener("bricks/ajax/query_result/completed",(e=>{setTimeout((()=>{brfInitProForms(),brfQuill(),brfInitFileFields(),brfBeforeAndAfter()}))})),document.addEventListener("DOMContentLoaded",(function(){brfScrollVideoInstance(),window.bricksforgeData=window.bricksforgeData||{},setTimeout((()=>{document.querySelector(".brxe-brf-pro-forms")&&bricksIsFrontend&&brfInitProForms()}),0),void 0!==window.WP_Grid_Builder&&window.WP_Grid_Builder&&WP_Grid_Builder.on("init",(function(e){e.facets.on("loaded",(function(e){setTimeout((()=>{brfInitProForms(),brfQuill()}),0)}))})),document.querySelector(".brxe-brf-add-to-calender-button")&&brfAddToCalenderButton()})),window.addEventListener("load",(()=>{setTimeout((()=>{brfQuill()}),10),bricksIsFrontend&&(document.querySelector(".brf-flip-wrapper")&&brfFlipEverything(),document.querySelector("#brf-toc")&&brfToc(),document.querySelector(".brf-three-js")&&bricksIsFrontend&&brfThreeJsHandler(),document.querySelector("[data-brf-tour]")&&brfTourHandler(),"undefined"!=typeof MegaMenu
1Settings&&MegaMenuSettings.megaMenuActivated&&brfMegaMenu()),document.querySelector(".brf-before-and-after")&&brfBeforeAndAfter()})),window.addEventListener("resize",(function(){if(document.querySelector(".brf-ba-wrapper"))for(let e of document.querySelectorAll(".brf-ba-wrapper")){let t=e.getBoundingClientRect().width,r=e.getBoundingClientRect().height;for(let a of e.querySelectorAll("img"))a.classList.remove("bricks-lazy-hidden"),a.getAttribute("data-src")&&a.setAttribute("src",a.getAttribute("data-src")),a.style.width=t+"px",a.style.height=r+"px",a.ondragstart=function(){return!1}}}));class BrfProForms{form;structure=[];currentStep=0;hasSummary=!1;hasShowStepsActive=!1;hasClicksAllowed=!1;hasRemoteSteps=!1;hasSubmitConditions=!1;remoteSteps;stepAnimationData=null;summary;isSubmitting=!1;currentActiveElement;isNestableForm=!1;initialFormDisplay;results=[];selectInstances=[];debouncedHandleLiveValues=null;ignoreConditionallyHiddenFieldsInActions=!1;submissionPayload={};forceLiveValidation=!1;formIsValid=!1;stripePaymentPollingInterval=null;reactiveSubmitDisabled=!1;_conditionLockedSubmit=!1;get isAdminPageCanvas(){return document.body.classList.contains("brf-backend-view__admin-page")&&window.parent!==window}navigateTo(e){this.isAdminPageCanvas?window.parent.location.href=e:window.location.href=e}reloadPage(){this.isAdminPageCanvas?window.parent.location.reload():window.location.reload()}constructor(e,t=!1){if(this.form=e,this.currentActiveElement=null,!0===t)return;const r=this.form.dataset.brfLiveValueDebounce?this.form.dataset.brfLiveValueDebounce:0;this.debouncedHandleLiveValues=this.debounce(this.handleLiveValues.bind(this),r),this.init()}
1async init(){this.buildVars(),this.handleGlobalVariables(),await this.handleForm(),this.handleKeyboardEvents(),this.woocommerceSetup(),bricksIsFrontend||this.handleActiveElementChange(),this.finish(),this.updateReactiveSubmitButtonState()}buildVars(){this.hasSummary="true"==this.form.dataset.brfSummary,this.hasShowStepsActive="true"==this.form.dataset.brfShowSteps,this.hasClicksAllowed="true"==this.form.dataset.brfStepAllowClicks,this.hasRemoteSteps=this.checkForRemoteSteps(),this.remoteSteps=document.querySelectorAll(".brf-steps-remote"),this.hasSubmitConditions="true"==this.form.dataset.brfSubmitConditions,this.reactiveSubmitDisabled="true"==this.form.dataset.brfReactiveSubmitDisabled,this.isNestableForm="true"==this.form.dataset.nestable,this.ignoreConditionallyHiddenFieldsInActions="true"==this.form.dataset.ignoreConditionallyHidden}finish(){this.isMultiStepForm()&&(this.form.style.visibility="visible"),this.form.classList.contains("form-loading")&&this.form.classList.remove("form-loading")}getGlobalVariables(){return window.bricksforgeData?.globalVariables?window.bricksforgeData.globalVariables:[]}debounce(e,t){let r;return function(...a){clearTimeout(r),r=setTimeout((()=>{clearTimeout(r),e(...a)}),t)}}static syncRepeaterFields(e,t){if(!e)return;if(!Array.isArray(t)||0===t.length)return;let r=e.querySelector(".brf-repeater-item");r?(t.forEach((e=>{let t=r.cloneNode(!0);Object.entries(e).forEach((([r,a])=>{let i=t.querySelector(`[data-custom-id="${r}"]`);if(i){let e=i.querySelector("input, textarea, select");"checkbox"===e.type||"radio"===e.type?e.checked=!!a:(e.value=a,setTimeout((()=>{e.classList.contains("flatpickr")&&e._flatpickr&&e._flatpickr.setDate(a,!0)})))}t.querySelectorAll(".brf-rich-text-container").forEach((t=>{setTimeout((()=>{const a=Quill.find(t);if(a){const t=a.clipboard.convert({html:e[r]});a.setContents(t)}}),50)}))})),r.parentNode.appendChild(t),t.querySelectorAll("[data-coloris]").forEach((e=>{e.dispatchEvent(new Event("input",{bubbles:!0}))}))})),r.remove(),this.updateRepeaterItemIndexes(e)):console.error("Repeater item template not found.")}static addRepeaterField(e){if(!e||!e.target)return;this.createSilentInstance(e.target.closest(".brxe-brf-pro-forms"));let t=e.target.closest(".brf-repeater-item"),r=(Array.from(t.parentNode.children).indexOf(t),t.closest(".brf-repeater-wrapper")),a=(r.dataset.customId,t.cloneNode(!0));a.querySelectorAll("input, textarea").forEach((e=>{"checkbox"!==e.type&&"radio"!==e.type&&(e.value="")})),a.querySelectorAll("input[type=checkbox], input[type=radio]").forEach((e=>{e.checked=!1})),a.querySelectorAll(".flatpickr").forEach((e=>{e._flatpickr&&(e._flatpickr.destroy(),delete e._flatpickr),e.value="",e.classList.remove("flatpickr-input","active"),e.removeAttribute("readonly");let t=e.closest(".form-group");if(t){t.querySelectorAll("input").forEach(((e,t)=>{t>0&&e.remove()})),t.querySelectorAll(".flatpickr-calendar").forEach((e=>e.remove()))}})),a.querySelectorAll(".choices").forEach((e=>{let t=e.closest(".form-group");if(!t)return;let r=e.querySelector("select"),a=r?r.id.replace(/-\d+$/,""):null;if(!a)return;let i=brfInitialFields.find((e=>{if("select"!==e.type)return!1;let t=document.createElement("div");t.innerHTML=e.html;let r=t.querySelector("select");return r&&(r.id===a||r.dataset.originalId===a)}));if(i){let r=document.createElement("div");r.innerHTML=i.html;let a=r.querySelector("select");a&&(a.removeAttribute("data-choices-initialized"),a.removeAttribute("data-choicesInitialized"),e.parentNode.removeChild(e),t.appendChild(a))}})),a.querySelectorAll(".brxe-brf-pro-forms-field-signature").forEach((e=>{e.querySelectorAll("canvas, .brf-signature__controls").forEach((e=>e.remove()));let t=document.createElement("div");t.className="brf-signature__pad",e.appendChild(t);let r=document.createElement("div");r.className="brf-signature__controls";let a=document.createElement("button");a.className="brf-signature__clear",a.type="button",a.textContent="Clear",r.appendChild(a),e.appendChild(r)})),t.parentNode.insertBefore(a,t.nextSibling),this.updateRepeaterItemIndexes(r),a.querySelector(".brf-rich-text-container")?this.reinitRichText(a):setTimeout((()=>{this.reinitFieldIfNeeded(a)}),50)}static reinitFieldIfNeeded(e){e.querySelector(".brxe-brf-pro-forms-field-sli
1der")&&this.reinitSlider(e),e.querySelector("select[data-use-choices=true]")&&this.reinitModernSelect(e),e.querySelector(".brf-rich-text-container")&&this.reinitRichText(e),e.querySelector(".brf-signature__pad")&&this.reinitSignature(e),e.querySelector("input[type=file]")&&this.reinitFileUpload(e),e.querySelector(".flatpickr")&&this.reinitDatePicker(e)}static createSilentInstance(e){return new BrfProForms(e.closest(".brxe-brf-pro-forms"),!0)}static reinitSlider(e){let t=e.querySelector(".slider");t.querySelector(".noUi-base").remove(),this.createSilentInstance(t).handleSliders(t)}static reinitModernSelect(e){let t=this.createSilentInstance(e);e.querySelectorAll(".choices").forEach((e=>{e.querySelector("select")||e.parentNode.removeChild(e)})),e.querySelectorAll("select[data-use-choices=true]").forEach((e=>{e.removeAttribute("data-choices-initialized"),e.removeAttribute("data-choicesInitialized"),setTimeout((()=>{t.handleSelectFields(e,{force:!0})}),20)}))}static reinitRichText(e){this.createSilentInstance(e);e.querySelector(".brxe-brf-pro-forms-field-richtext").dataset.theme;let t=e.querySelector(".brf-rich-text-container");if(t){t.classList.remove("ql-container"),t.classList.remove("ql-snow"),t.classList.remove("ql-bubble");const e=t.parentNode.querySelector(".ql-toolbar");e&&e.remove();t.querySelector(".ql-editor")&&(t.innerHTML="")}brfQuill(t)}static reinitSignature(e){let t=this.createSilentInstance(e),r=e.querySelector(".brf-signature__pad");t.handleSignatures(r)}static reinitFileUpload(e){let t=this.createSilentInstance(e),r=e.querySelector(".brxe-brf-pro-forms-field-file"),a=e.querySelector("input[type=file]");window.bricksforgeData.initFileField(a),t.handleFileInputs(a,r)}static reinitDatePicker(e){e.querySelectorAll(".flatpickr").forEach((e=>{if(e._flatpickr)return;let t=e.dataset.bricksDatepickerOptions;if(t){t=JSON.parse(t),t.disableMobile=!0,t.onReady=function(e,t,r){let a=r.altInput.previousElementSibling?r.altInput.previousElementSibling.getAttribute("aria-label"):"Date";r.altInput.setAttribute("aria-label",a||"Date")};const r=flatpickr(e,t);window.bricksforgeData&&window.bricksforgeData.datepickerInstances&&window.bricksforgeData.datepickerInstances.push(r)}})),e.querySelectorAll(".flatpickr-input").forEach((e=>{if(e._flatpickr)return;let t=e.dataset.bricksDatepickerOptions,r=e.dataset.datepickerCustomOptions;if(t&&(t=JSON.parse(t)),r&&(r=JSON.parse(r)),null!=e.dataset.enableWeekdays){let r=e.dataset.enableWeekdays.split(" ");r=r.map((e=>7==(e=parseInt(e))?0:e));const a=t.enable?t.enable:[];t.enable=[function(e){if(a&&a.length>0){return a.some((t=>"function"==typeof t?t(e):t instanceof Date?e.toDateString()===t.toDateString():"string"==typeof t?e.toDateString()===new Date(t).toDateString():!(!t.from||!t.to)&&(e>=new Date(t.from)&&e<=new Date(t.to))))&&r.includes(e.getDay())}return r.includes(e.getDay())}]}if("undefined"!=typeof flatpickr){window.bricksforgeData.datepickerInstances||(window.bricksforgeData.datepickerInstances=[]);let r=flatpickr(e,t);window.bricksforgeData.datepickerInstances.push(r)}}))}static removeRepeaterField(e){if(!e||!e.target)return;let t=e.target.closest(".brf-repeater-item"),r=t.closest(".brf-repeater-wrapper");r.dataset.customId;t.parentNode.children.length>1&&t.remove(),this.updateRepeaterItemIndexes(r)}static updateRepeaterItemIndexes(e){e.querySelectorAll(".brf-repeater-item").forEach(((t,r)=>{t.querySelectorAll("[id]").forEach((e=>{const a=e.dataset.originalId||e.getAttribute("id");e.dataset.originalId=a;let i=`${a}-${r}`;e.setAttribute("id",i);let n=t.querySelector(`label[for="${a}"]`);n||(n=t.querySelector(`label[for="${a}-${r-1}"]`),i=`${a}-${r}`),n||(n=t.querySelector(`label[for="${a}-0"]`),i=`${a}-${r}`),n&&n.setAttribute("for",i),t.querySelectorAll("[aria-describedby]").forEach((e=>{const t=e.getAttribute("aria-describedby").split(/\s+/).filter(Boolean).map((e=>e===a||e.startsWith(`${a}-`)?i:e));e.setAttribute("aria-describedby",[...new Set(t)].join(" "))}))})),t.querySelectorAll("[name]").forEach((t=>{const a=t.name.endsWith("[]"),i=t.dataset.originalName||t.getAttribute("name").replace(/\[\d*\]$/,"").replace(/\[\]$/,"");t.dataset.originalName=i;const n=e.dataset.customId,s=t.closest(".form-group").dataset.customId||"field";let o;o=a?`brfr[${n}][${r}][${s}][]`:`brfr[${n}][${r}][${s}]`,t.setAttribute("name",o),void 0!==t.dataset.coloris&&Coloris({...JSON.parse(t.dataset.options)})}))}));let t=new BrfProForms(e.closest(".brxe-brf-pro-forms"),!0);t.handleDatePickers(),t.handleRichText()}fireConfetti(){const e=this.form.dataset.confettiType?this.form.dataset.confettiType:"basic";let t=this.form.dataset.confettiDuration?1e3*parseInt(this.form.dataset.confettiDuration):5e3,r=this.form.getBoundingClientRect(),a={x:(r.left+r.right)/(2*window.innerWidth),y:(r.top+r.bottom)/(2*window.innerHeight)+.15};function i(e,t){return Math.random()*(t-e)+e}switch(e){case"basic":confetti({particleCount:100,spread:70,origin:a,zIndex:99999999});break;case"random":confetti({angle:i(55,125),spread:i(50,70),particleCount:i(50,100),origin:{y:.6},zIndex:99999999});break;case"realistic":var n={origin:a,zIndex:99999999};function c(e,t){confetti({...n,...t,particleCount:Math.floor(200*e)})}c(.25,{spread:26,startVelocity:55}),c(.2,{spread:60}),c(.35,{spread:100,decay:.91,scalar:.8}),c(.1,{spread:120,startVelocity:25,decay:.92,scalar:1.2}),c(.1,{spread:120,startVelocity:45});break;case"fireworks":var s=Date.now()+t,o=(n={startVelocity:30,spread:360,ticks:60,zIndex:99999999},setInterval((function(){var e=s-Date.now();if(e<=0)return clearInterval(o);var r=e/t*50;confetti({...n,particleCount:r,origin:{x:i(.1,.3),y:Math.random()-.2}}),confetti({...n,particleCount:r,origin:{x:i(.7,.9),y:Math.random()-.2}})}),250));break;case"stars":n={spread:360,ticks:50,gravity:0,decay:.94,startVelocity:30,colors:["FFE400","FFBD00","E89400","FFCA6C","FDFFB8"],zIndex:99999999};function d(){confetti({...n,particleCount:40,scalar:1.2,shapes:["star"]}),confetti({...n,particleCount:10,scalar:.75,shapes:["circle"]})}setTimeout(d,0),setTimeout(d,100),setTimeout(d,200);break;case"snow":s=Date.now()+t;var l=1;!function e(){var r=s-Date.now(),a=Math.max(200,r/t*500);l=Math.max(.8,l-.001),confetti({particleCount:1,startVelocity:0,ticks:a,origin:{x:Math.random(),y:Math.random()*l-.2},colors:["#ffffff"],shapes:["circle"],gravity:i(.4,.6),scalar:i(.4,1),drift:i(-.4,.4),zIndex:99999999}),r>0&&requestAnimationFrame(e)}()}}woocommerceSetup(){"undefined"!=typeof wc_add_to_cart_params&&document.body.addEventListener("added_to_cart",(()=>{this.wcRefreshMiniCart()}))}handleKeyboardEvents(){this.form.addEventListener("keydown",(e=>{if(13==e.keyCode){if("TEXTAREA"==e.target.tagName)return;if(e.target.classList.contains("ql-editor"))return;if(this.isMultiStepForm()){if(e.preventDefault(),"BUTTON"==e.target.tagName){if(e.target.click(),"submit"==e.target.type)return;return void this.focusOnFirstStepInput()}this.isLastStep()||(this.jumpToNextStep(e),this.focusOnFirstStepInput())}}}))}focusOnFirstStepInput(){let e=this.form.querySelector("[data-brf-step='"+(parseInt(this.currentStep)+1)+"'] *");e&&e.focus()}handleActiveElementChange(){const e=brfBricksGlobalProps(window);if(!e||!e.$_state)return;const t=e.$_state,r=this,a=Object.getOwnPropertyDescriptor(t,"activeElement");
1if(a&&a.set&&a.set.__brfPatched)return void BrfProForms.populateControlData();const i=function(e){r.currentActiveElement=e,BrfProForms.populateControlData()};i.__brfPatched=!0;try{Object.defineProperty(t,"activeElement",{configurable:!0,get(){return r.currentActiveElement},set:i})}catch(e){return}BrfProForms.populateControlData()}static handleDefaultEmailContent(e=!1,t=!1,r=!1){const a=brfBricksGlobalProps(window.parent);if(!a||!a.$_state)return;const i=a.$_state.content,n=a.$_state.header,s=a.$_state.footer;if(!i)return;let o=[];if(o=Object.values(i).filter((e=>"brf-pro-forms"==e.name)),n&&(o=[...o,...Object.values(n).filter((e=>"brf-pro-forms"==e.name))]),s&&(o=[...o,...Object.values(s).filter((e=>"brf-pro-forms"==e.name))]),!o)return;const l=["step","divider","heading","turnstile","shortcode","file"],c=["brf-placeholder","guardian42"];o.forEach((a=>{let i=a.id,n=window.parent.document.querySelector(".brx-body").__vue_app__&&window.parent.document.querySelector(".brx-body").__vue_app__.config.globalProperties.$_state.activeElement?window.parent.document.querySelector(".brx-body").__vue_app__.config.globalProperties.$_state.activeElement.id:null;if(n&&n!=i)return;const s=null!=a.settings.emailContent&&""!=a.settings.emailContent,o=!!a.settings.refreshEmailContent,d=!!a.settings.refreshConfirmationEmailContent;let u=document.querySelector("#bricks-builder-iframe");if(u=u?u.contentWindow.document:document,(!s||e&&t||o)&&(a.settings.fields&&a.settings.fields.length>0&&(a.settings.emailContent="",a.settings.fields.forEach((e=>{if(l.includes(e.type))return;const t=e.label?e.label+": ":"",r=e.id?"{{"+e.id+"}}":"";a.settings.emailContent+=t+r+"\n"}))),a.children&&a.children.length>0&&u)){const e=u.querySelector('form[data-script-id="'+a.id+'"]');if(a.settings.emailContent="",e){let t=Array.from(e.querySelectorAll("input")),r=Array.from(e.querySelectorAll("textarea"));t.push(...r);const i=e.querySelectorAll("select");let n=Array.from(e.querySelectorAll(".brxe-brf-pro-forms-field-repeater"));t.push(...n),t.forEach((e=>{let t=e.name&&e.name.split("form-field-")[1]?e.name.split("form-field-")[1]:null;if(t||(t=e.dataset.customId),t){if(c.includes(t))return;if(e.closest(".brxe-brf-pro-forms-field-honeypot"))return;if(e.closest(".brf-repeater-item"))return;if("file"==e.type)return;if("checkbox"==e.type||"radio"==e.type){const t=e.closest(".form-group"),r=t.dataset.customId,i=t.querySelector("label").innerText+": {{"+r+"}}\n";return void(r&&!a.settings.emailContent.includes(i)&&(a.settings.emailContent+=i))}let r=e.dataset.label;r||(r=e.querySelector("label")?e.querySelector("label").innerText:null),a.settings.emailContent+=r?r+": {{"+t+"}}\n":"{{"+t+"}}\n"}})),i.forEach((e=>{const t=e.name&&e.name.split("form-field-")[1]?e.name.split("form-field-")[1]:null;if(t){const r=e.dataset.label;a.settings.emailContent+=r?r+": {{"+t+"}}\n":"{{"+t+"}}\n"}}))}}const f=null!=a.settings.confirmationEmailContent&&""!=a.settings.confirmationEmailContent,m=null!=a.settings.confirmationEmailSubject&&""!=a.settings.confirmationEmailSubject;if((!f||e&&r||d)&&m&&(a.settings.fields&&a.settings.fields.length>0&&(a.settings.confirmationEmailContent="",a.settings.fields.forEach((e=>{if(l.includes(e.type))return;const t=e.label?e.label+": ":"",r=e.id?"{{"+e.id+"}}":"";a.settings.confirmationEmailContent+=t+r+"\n"}))),a.children&&a.children.length>0&&u)){const e=u.querySelector('form[data-script-id="'+a.id+'"]');if(a.settings.confirmationEmailContent="",e){let t=Array.from(e.querySelectorAll("input")),r=Array.from(e.querySelectorAll("textarea"));t.push(...r);const i=e.querySelectorAll("select");let n=Array.from(e.querySelectorAll(".brxe-brf-pro-forms-field-repeater"));t.push(...n),t.forEach((e=>{let t=e.name&&e.name.split("form-field-")[1]?e.name.split("form-field-")[1]:null;if(t||(t=e.dataset.customId),t){if(c.includes(t))return;if(e.closest(".brxe-brf-pro-forms-field-honeypot"))return;if(e.closest(".brf-repeater-item"))return;if("file"==e.type)return;if("checkbox"==e.type||"radio"==e.type){const t=e.closest(".form-group"),r=t.dataset.customId,i=t.querySelector("label").innerText+": {{"+r+"}}\n";return void(r&&!a.settings.confirmationEmailContent.includes(i)&&(a.settings.confirmationEmailContent+=i))}let r=e.dataset.label;r||(r=e.querySelector("label")?e.querySelector("label").innerText:null),a.settings.confirmationEmailContent+=r?r+": {{"+t+"}}\n":"{{"+t+"}}\n"}}
1)),i.forEach((e=>{const t=e.name&&e.name.split("form-field-")[1]?e.name.split("form-field-")[1]:null;if(t){const r=e.dataset.label;a.settings.confirmationEmailContent+=r?r+": {{"+t+"}}\n":"{{"+t+"}}\n"}}))}}}))}static populateControlData(){const e=brfBricksGlobalProps(window),t=brfBricksGlobalProps(window.parent);if(!e||!e.$_state||!t)return;const r=e.$_state.activeElement;if(r&&r.settings&&r.settings.actions&&r.settings.actions.includes("mailchimp")&&"brf-pro-forms"==r.name){const e=t.bricks.mailchimpLists,a=t.bricks.elements["brf-pro-forms"].controls.mailchimpGroups,i=r.settings.mailchimpList;if(i){const r=structuredClone(a.options);a.options=e[i].groups,JSON.stringify(r)!==JSON.stringify(a.options)&&(t.$_state.rerenderControls=Date.now())}}}checkForRemoteSteps(){if(document.querySelectorAll(".brf-steps-remote").length>0)for(let e=0;e<document.querySelectorAll(".brf-steps-remote").length;e++){let t=document.querySelectorAll(".brf-steps-remote")[e];if(t.dataset.brfFormId==this.form.id)return this.remoteSteps=t,!0}return!1}async handleForm(e){return new Promise((async e=>{await this.buildStructure(),this.loadingSequences(),await this.showOnlyFirstStep(),this.handleRequiredFields(),this.handleBricksInitialScripts(),this.handleVisualSteps(),this.addStepIndexes(),this.handleStepConditions(),this.handleSliders(),this.handleColorPickers(),this.handleInputMasking(),this.handleTextareaMaxLength(),this.handleRepeaters(),this.handleDatePickers(),this.handleRatings(),this.handleSignatures(),this.handleMapFields(),this.handleClickActions(),this.handleLiveEventLogic(),this.handleEventListeners(),this.initializeFieldTracking(this.form),this.handleLiveValues(),this.handleNextStepTriggers(),await this.handleSelectFields(),await this.handleConditionalLogic(),await this.renderFormData(this.needsFormDataRendering()),this.handleCalculationFieldLogic(),setTimeout((()=>{this.handleFileInputs()}),150),setTimeout((()=>{this.handleCalculationFieldLogic()}),0),this.handleSubmit(),e()}))}handleTextareaMaxLength(){document.querySelectorAll("textarea[maxlength]").forEach((e=>{const t=e.closest(".pro-forms-builder-field");if(!t)return;const r=t.querySelector(".max-length-counter");if(!r)return;const a=r.dataset.counterText||"{{current}}/{{maxlength}}",i=parseInt(r.dataset.maxLength),n=e=>{const t=i-e;let n=a.replace(/{{current}}/g,`<span class="counter-current">${e}</span>`).replace(/{{maxlength}}/g,`<span class="counter-max">${i}</span>`).replace(/{{remaining}}/g,`<span class="counter-remaining">${t}</span>`);r.querySelector(".counter-text").innerHTML=n,e>=i?(r.classList.add("max-length-reached"),r.classList.remove("max-length-warning")):e>=.9*i?(r.classList.add("max-length-warning"),r.classList.remove("max-length-reached")):r.classList.remove("max-length-warning","max-length-reached")};if(n(e.value.length),e.addEventListener("input",(()=>{n(e.value.length)})),r.classList.contains("max-length-counter--inside")){const t=e.closest(".pro-forms-builder-field");t&&(t.style.position="relative")}}))}setCustomRequiredValidation(e,t){if(!e.dataset.validation){t.setAttribute("required","true");const r=t.validationMessage;t.removeAttribute("required"),e.dataset.validation=JSON.stringify([{type:"required",message:r||null}]),e.dataset.showMessageBelowField||(e.dataset.showMessageBelowField="true")}}handleRequiredFields(){setTimeout((()=>{this.form.querySelectorAll("[required]").forEach((e=>{e.removeAttribute("required"),this.setCustomRequiredValidation(e,e)})),this.form.querySelectorAll("[data-is-required='true']").forEach((e=>{const t=e.querySelector("input");t&&this.setCustomRequiredValidation(e,t)}))}),100)}needsFormDataRendering(){if(!this.hasSubmitConditions&&!this.hasWcDynamicData()&&!this.hasConditionalFieldLogic())return[];const e=[];return this.hasSubmitConditions&&e.push("submitConditions"),this.hasWcDynamicData()&&e.push("wcDynamicData"),e}handleEventListeners(){this.form.addEventListener("input",(e=>{if("INPUT"==e.target.tagName||"TEXTAREA"==e.target.tagName){if(e.target.pattern){new RegExp("^"+e.target.pattern+"$").test(e.target.value)||(e.target.value=e.target.value.slice(0,-1))}this.handleLiveValues(e)}})),this.form.addEventListener("change",(e=>{"SELECT"==e.target.tagName&&this.handleLiveValues(e),"checkbox"!=e.target.type&&"radio"!=e.target.type||(this.handleLiveValues(e),this.handleAriaChange(e))}));const e=this.form.querySelectorAll('input[type="hidden"]');if(e.length>0){const t=new MutationObserver((e=>{for(const t of e)if("attributes"===t.type&&"value"===t.attributeName){const e=t.target;this.handleLiveValues({target:e}),this.handleConditionalLogic()}}));e.forEach((e=>{t.observe(e,{attributes:!0,attributeFilter:["value"]})}))}this.handleValidationEvents()}handleAriaChange(e){"checkbox"!=e.target.type&&"radio"!=e.target.type||e.target.setAttribute("aria-checked",e.target.checked)}
1handleBricksInitialScripts(){bricksQuerySelectorAll(this.form,'input[type="checkbox"]').forEach((function(e){e.required&&e.addEventListener("click",(function(t){var r=e.getAttribute("name");if(this.form){var a=bricksQuerySelectorAll(this.form,'input[name="'.concat(r,'"]')),i=!1;a.forEach((function(e){e.checked&&(i=!0)})),i?a.forEach((function(e){e.required=!1})):a.forEach((function(e){e.required=!0}))}}))}))}async handleSelectFields(e,t={force:!1}){let r=e?[e]:document.querySelectorAll("[data-use-choices='true']");if(r&&"undefined"!=typeof Choices)return new Promise(((e,a)=>{r.forEach((e=>{if(e.choices)try{e.choices.destroy()}catch(e){console.error("Failed to destroy Choices instance",e)}brfInitialFields.push({type:"select",html:e.outerHTML});const r=e.dataset.itemSelectText?e.dataset.itemSelectText:"",a=e.dataset.noResultsText?e.dataset.noResultsText:"No results found",i=!!e.dataset.searchable&&e.dataset.searchable,n=e.dataset.searchPlaceholder||e.dataset.placeholder||"";let s=!!e.dataset.placeholder;if(!!e.multiple&&s&&e.querySelector("option")&&e.querySelector("option").remove(),e.dataset.choicesInitialized&&!t.force)return;let o=new Choices(e,{silent:!bricksIsFrontend,allowHTML:!0,searchEnabled:!1,itemSelectText:r,noResultsText:a,searchEnabled:i,searchPlaceholderValue:n,searchFields:["label","value"],searchResultLimit:99,removeItems:!0,removeItemButton:!0,placeholder:!!s,placeholderValue:e.dataset.placeholder,shouldSort:!1,labelId:e.id});this.handleCountryFlags(e,o);const l=()=>{if(e.hasAttribute("required")||"true"===e.dataset.required){const t=e.closest(".form-group").querySelector('input[data-type="choices-validation"]');if(t){const e=o.getValue(!0);if(e&&""!==e&&(!Array.isArray(e)||e.length>0))t.value=Array.isArray(e)?e.join(","):e,t.setCustomValidity("");else{t.value="";let e="";t.setCustomValidity(""),t.checkValidity()||(e=t.validationMessage);const r=e||"Please select an option.";t.setCustomValidity(r)}}}};l();let c=e.closest(".choices").querySelector(".choices__list--dropdown");c&&(c.dataset.lenisPrevent=!0),o.passedElement.element.addEventListener("showDropdown",(e=>{let t=e.target.closest(".choices");setTimeout((()=>{t.querySelector("input[type=search]")&&t.querySelector("input[type=search]").focus()}),25)})),i&&this.handleTouchSearchFocus(o),o.passedElement.element.addEventListener("change",(e=>{l(),this.handleConditionalLogic(),this.handleLiveValidation(e.target),this.handleCalculationFieldLogic(),this.handleStepConditions(),this.updateReactiveSubmitButtonState()})),this.selectInstances.push(o),bricksforgeData.choicesInstances||(bricksforgeData.choicesInstances=[]),bricksforgeData.choicesInstances.push(o),e.dataset.choicesInitialized=!0}));document.querySelectorAll(".x-modal").forEach((e=>{e.addEventListener("x_modal:open",(()=>{this.handleSelectFields(null,{force:!0})}))})),e()}))}handleTouchSearchFocus(e){const t=e.containerOuter&&e.containerOuter.element;if(!t)return;let r=!1;t.addEventListener("pointerdown",(t=>{if(r=!1,"mouse"===t.pointerType)return;if(e.containerOuter.isDisabled)return;if(e.dropdown.isActive)return;if(e.dropdown.element.contains(t.target))return;if(t.target.closest&&t.target.closest("[data-button]"))return;const a=e.input&&e.input.element;a&&(e.dropdown.show(),e.containerOuter.open(e.dropdown.distanceFromTopWindow),a.focus(),e.passedElement.triggerEvent("showDropdown",{}),r=!0)}),!0),t.addEventListener("click",(e=>{r&&(r=!1,e.stopPropagation())}),!0)}handleCountryFlags(e,t){const r=e.closest(".form-group"),a=r?.dataset.countryFlags;if(!a)return;let i={};try{i=JSON.parse(a)}catch(e){return void console.error("Error parsing country flags data:",e)}const n=()=>{let t=e.parentElement.querySelector(".choices");if(t||(t=e.closest(".form-group").querySelector(".choices")),t||(t=document.querySelector(`[data-element-id="${e.closest(".form-group").dataset.elementId}"] .choices`)),!t)return;t.querySelectorAll(".choices__list--dropdown .choices__item").forEach((e=>{const t=e.dataset.value,a=i[t];if(a&&!e.querySelector("img")){const t=this.decodeHtml(a),i="true"===r?.dataset.hiddenLabels;e.innerHTML=i?t:t+e.textContent}}));t.querySelectorAll(".choices__item--selectable").forEach((e=>{const t=e.dataset.value,a=i[t];if(a&&!e.querySelector("img")){const t=this.decodeHtml(a),i="true"===r?.dataset.hiddenLabels,n=e.textContent.replace("Remove item","").trim(),s=e.querySelector(".choices__button")?e.querySelector(".choices__button").outerHTML:"";e.innerHTML=i?t+s:t+n+s}}))};n(),t.passedElement.element.addEventListener("showDropdown",(()=>{n()})),t.passedElement.element.addEventListener("choice",(()=>{n()})),t.passedElement.element.addEventListener("change",(()=>{n()}))}decodeHtml(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}static clearLiveValue(e,t){const r=e?.name,a=e?.size;if(!r||!a)return;let i=document.querySelectorAll(`[data-brf-file-name="${r}"][data-brf-file-size="${a}"]`);
1i&&i.forEach((e=>{e.remove()}))}handleLiveValues(e,t=!1){let r=document.querySelectorAll(".brf-live-value");if(!r)return;if(!e)return void this.form.querySelectorAll("input, textarea, select").forEach((e=>{this.handleLiveValues(e,!0)}));let a=t?e:e.target;r.forEach((e=>{let t=!!e.dataset.connection&&e.dataset.connection;if(t&&a&&(a.name=="form-field-"+t||a.name=="form-field-"+t+"[]")){const t=e.dataset.prefix?e.dataset.prefix:"",r=e.dataset.suffix?e.dataset.suffix:"",i=e.dataset.fallback?e.dataset.fallback:"";if("INPUT"==a.tagName||"TEXTAREA"==a.tagName)if("file"==a.type){let n=[];if(window.bricksforgeData&&window.bricksforgeData.filePondInstances&&window.bricksforgeData.filePondInstances.length>0){const e=a.closest(".filepond--root");if(e){const t=window.bricksforgeData.filePondInstances.find((t=>t.element.closest(".filepond--root")===e));if(t){n=t.getFiles().map((e=>e.file))}}}if(0===n.length&&a.files&&a.files.length>0&&(n=Array.from(a.files)),n.length>0){const a=n.filter((e=>e.type.startsWith("image/"))),i=n.filter((e=>!e.type.startsWith("image/")));let s="";if(a.length>0){let n=0;const o=a.length,l=[];a.forEach(((a,c)=>{const d=new FileReader;d.onload=function(d){if(l[c]=`<img data-brf-file-name="${a.name}" data-brf-file-size="${a.size}" src="${d.target.result}" style="width: 100%; object-fit: contain;" alt="Preview" />`,n++,n===o){if(s=l.join(""),i.length>0){const e=i.map((e=>e.name)).join(", ");s+=(s?", ":"")+e}e.innerHTML=t+s+r}},d.readAsDataURL(a)}))}else{const a=i.map((e=>e.name)).join(", ");e.innerHTML=t+a+r}}else e.innerHTML=i?t+i+r:t+""+r}else if("radio"==a.type){let n=document.querySelector('input[name="'+a.name+'"]:checked');e.innerHTML=n?t+n.value+r:i?t+i+r:t+""+r}else if("checkbox"==a.type){let i=document.querySelectorAll('input[name="'+a.name+'"]:checked'),n=[];i.forEach((e=>{n.push(e.value)})),n.length>0?e.innerHTML=t+n.join(", ")+r:e.dataset.fallback?e.innerHTML=t+e.dataset.fallback+r:e.innerHTML=t+""+r}else if(a.value&&""!=a.value){let i=a.value.replace(/\n/g,"<br>");e.innerHTML=t+i+r}else if(e.dataset.fallback){let a=e.dataset.fallback.replace(/\n/g,"<br>");e.innerHTML=t+a+r}else{let i=a.value.replace(/\n/g,"<br>");e.innerHTML=t+i+r}else if("SELECT"==a.tagName)if(a.classList.contains("choices__input")&&a.multiple){let i=a.querySelectorAll("option:checked"),n=[];i.forEach((e=>{n.push(e.value)})),e.innerHTML=t+n.join(", ")+r}else a.value&&""!=a.value?e.innerHTML=t+a.value+r:e.innerHTML=i?t+i+r:t+a.value+r}})),this.handleLiveVariables()}initializeFieldTracking(e){e.querySelectorAll("input, textarea").forEach((e=>{e.addEventListener("input",(()=>{e.dataset.programmingUpdate||(e.dataset.touched=!0)}))}))}handleLiveVariables(){let e=this.form.querySelectorAll("input:not([type='hidden']), textarea");if(!e)return;if(e.forEach((e=>{if((e.value&&e.value.includes("{{")||e.dataset.originalContent&&e.dataset.originalContent.includes("{{"))&&!e.dataset.touched){e.dataset.originalContent||(e.dataset.originalContent=e.value);let t=e.dataset.originalContent,r=t.match(/{{(.*?)}}/g);if(r){let a=t;r.forEach((e=>{let t=e.slice(2,-2).trim(),r=this.form.querySelector(`input[name="form-field-${t}"], textarea[name="form-field-${t}"], select[name="form-field-${t}"], input[name="form-field-${t}[]"]`);if(r){let i="";if("radio"===r.type){let e=this.form.querySelector(`input[name="form-field-${t}"]:checked, input[name="form-field-${t}[]"]:checked`);i=e?e.dataset.label||e.value:""}else if("checkbox"===r.type){let e=this.form.querySelectorAll(`input[name="form-field-${t}"]:checked, input[name="form-field-${t}[]"]:checked`),r=[];e.forEach((e=>{r.push(e.dataset.label||e.value)})),i=r.join(", ")}else i=r.value;a=a.replace(e,i)}else a=a.replace(e,"")})),e.dataset.programmingUpdate="true",e.tagName,e.value=a,setTimeout((()=>{delete e.dataset.programmingUpdate}),0)}}})),!this.form.dataset.variablesInitialized){const e=new Set;let t=document.createTreeWalker(this.form,NodeFilter.SHOW_TEXT,null,!1);for(;t.nextNode();){let r=t.currentNode;if(r.nodeType===Node.TEXT_NODE&&r.textContent.includes("{{")){let t=r.parentElement;for(;t&&!["P","DIV","SPAN","LABEL","LI","TD","TH","H1","H2","H3","H4","H5","H6"].includes(t.tagName);)t=t.parentElement;t&&!t.dataset.originalHtml&&(t.dataset.originalHtml=t.innerHTML,e.add(t))}}this.form.dataset.variablesInitialized="true"}this.form.querySelectorAll("[data-original-html]").forEach((e=>{let t=e.dataset.originalHtml,r=t;const a=t.match(/{{(.*?)}}/g);
1a&&(a.forEach((t=>{const a=this.maybeParseVariable(t);if(null!==a){r=r.replace(t,a);const i=e.querySelector("input");i&&i.dataset.label&&(i.dataset.label=r),i&&i.getAttribute("aria-label")&&i.setAttribute("aria-label",r)}})),e.innerHTML!==r&&(e.innerHTML=r))})),this.form.querySelectorAll("[data-brf-var]").forEach((e=>{let t={};const r=e.getAttribute("data-brf-original-attributes");if(r)try{t=JSON.parse(r)}catch(e){t={}}for(const r in t){const a=t[r],i=this.maybeParseVariable(a);e.setAttribute(r,i)}e.getAttributeNames().forEach((r=>{if("data-brf-original-attributes"!==r&&!t.hasOwnProperty(r)){const a=e.getAttribute(r);if(a&&a.includes("{{")){t[r]=a;const i=this.maybeParseVariable(a);e.setAttribute(r,i)}}})),e.setAttribute("data-brf-original-attributes",JSON.stringify(t))}))}handleNextStepTriggers(){let e=this.form.querySelectorAll("[data-next-step-trigger]");e&&e.forEach((e=>{"radio"===e.type&&e.addEventListener("keydown",(t=>{if("ArrowUp"===t.key||"ArrowDown"===t.key||"ArrowLeft"===t.key||"ArrowRight"===t.key){t.preventDefault();const r=this.form.querySelectorAll(`input[name="${e.name}"]`),a=Array.from(r).indexOf(e);let i;return i="ArrowDown"===t.key||"ArrowRight"===t.key?(a+1)%r.length:(a-1+r.length)%r.length,void r[i].focus()}"Enter"===t.key?(t.preventDefault(),e.checked=!0,e.dispatchEvent(new Event("change",{bubbles:!0}))):" "!==t.key&&"Spacebar"!==t.key||(e.checked=!0,this.jumpToNextStep(t))})),e.addEventListener("click",(e=>{this.jumpToNextStep(e)}))}))}handleValidationEvents(e=!1){this.form.querySelectorAll("input, textarea").forEach((t=>{t.addEventListener("blur",(()=>{this.handleLiveValidation(t,e),this.updateReactiveSubmitButtonState()})),"checkbox"!=t.type&&"radio"!=t.type||t.addEventListener("change",(()=>{this.handleLiveValidation(t,e),this.updateReactiveSubmitButtonState()})),this.reactiveSubmitDisabled&&"checkbox"!==t.type&&"radio"!==t.type&&t.addEventListener("input",(()=>{this.updateReactiveSubmitButtonState()}))})),this.form.querySelectorAll("select").forEach((t=>{t.addEventListener("change",(()=>{this.handleLiveValidation(t,e),this.updateReactiveSubmitButtonState()}))}))}isCheckboxOrRadioChild(e){return e.closest(".brxe-brf-pro-forms-field-checkbox-wrapper")||e.closest(".brxe-brf-pro-forms-field-radio-wrapper")}handleLiveValidation(e,t=!1){if(this.ignoreValidation(e))return!0;this.forceLiveValidation&&(t=!0);let r=!!e.dataset.validation&&e.dataset.validation,a=!!e.dataset.liveValidation;if(!r&&this.isCheckboxOrRadioChild(e)){let t=e.closest(".form-group");r=t.dataset.validation,a=!!t.dataset.liveValidation}if(!r)return;if(!(r&&a||t))return;r=JSON.parse(r);let i=[];for(let t=0;t<r.length;t++){let a=r[t],n=a.type;if(a.value){let e=a.value;if(e.includes("{{")){let t=e.split("{{")[1].split("}}")[0],r=this.form.querySelector('input[name="form-field-'+t+'"]');r&&(e=r.value),a.value=e}}switch(n){case"required":if("rich-text"==e.dataset.type){if("<p><br></p>"==e.value){i.push({field:e,rule:a});continue}this.markFieldAsValid(e,a);continue}if("true"===e.dataset.useChoices){const t=e.closest(".form-group").querySelector('input[data-type="choices-validation"]');if(t){t.value&&""!==t.value?this.markFieldAsValid(e,a):i.push({field:e,rule:a});continue}}const t=e.closest(".brxe-brf-pro-forms-field-checkbox-wrapper"),r=e.closest(".brxe-brf-pro-forms-field-radio-wrapper");if(t){const r=t.querySelectorAll("input[type='checkbox']:checked"),n=t.dataset.isRequiredCount||1;r.length<n?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break}if(r){0==r.querySelectorAll("input[type='radio']:checked").length?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break}if(e.closest(".brxe-brf-pro-forms-field-file")){let t=e.closest(".brxe-brf-pro-forms-field-file").querySelector("input[name='fileCount']");t=parseInt(t.value),t&&0!=t?this.markFieldAsValid(e,a):i.push({field:e,rule:a});break}if(!e.value){i.push({field:e,rule:a});continue}""==e.value.replace(/\s/g,"")?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"email":let n=new RegExp("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$");
1e.value&&!n.test(e.value)?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"number":let s=new RegExp("^[0-9]+$");e.value&&!s.test(e.value)?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"url":let o=new RegExp("^(http|https)://");e.value&&!o.test(e.value)?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"minChars":if(!a.charsCount)break;a.minChars=parseInt(a.charsCount),e.value&&e.value.length<a.charsCount?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"maxChars":if(!a.charsCount)break;a.charsCount=parseInt(a.charsCount),e.value&&e.value.length>a.charsCount?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"value":if(!a.value)break;e.value&&e.value!=a.value?i.push({field:e,rule:a}):this.markFieldAsValid(e,a);break;case"custom":if(!a.regex)break;new RegExp(a.regex).test(e.value)?this.markFieldAsValid(e,a):i.push({field:e,rule:a})}}return i.length>0?(i.forEach((e=>{this.markFieldAsInvalid(e.field,e.rule)})),!1):(this.markFieldAsValid(e),!0)}isRequiredFieldFilled(e){if(!e||this.ignoreValidation(e))return!0;const t=e.closest(".brf-field-rich-text");if(t){const e=t.querySelector("input[data-type='rich-text']");return!!e&&(!!e.value&&"<p><br></p>"!==e.value)}const r=e.closest(".brxe-brf-pro-forms-field-checkbox-wrapper");if(r){const e=parseInt(r.dataset.isRequiredCount||1);return r.querySelectorAll("input[type='checkbox']:checked").length>=e}const a=e.closest(".brxe-brf-pro-forms-field-radio-wrapper");if(a)return!!a.querySelector("input[type='radio']:checked");const i=e.closest(".brxe-brf-pro-forms-field-file");if(i){const e=i.querySelector("input[name='fileCount']");return!!(e&&parseInt(e.value)>0)}if(e.closest(".brxe-brf-pro-forms-field-rating")){const t=parseInt(e.value,10);return!isNaN(t)&&t>0}return e.classList.contains("brf-map-value")?"true"===e.dataset.userSelected:"checkbox"===e.type||"radio"===e.type?!!e.checked:!!e.value&&""!==String(e.value).trim()}getReactiveRequiredFields(){const e=new Set,t=t=>{const r=t.querySelector("input[type='checkbox'], input[type='radio']")||t.querySelector("input, select, textarea");r&&e.add(r)};return this.form.querySelectorAll("input[required], select[required], textarea[required]").forEach((t=>e.add(t))),this.form.querySelectorAll("[data-validation]").forEach((r=>{let a;try{a=JSON.parse(r.dataset.validation)}catch(e){return}Array.isArray(a)&&a.some((e=>"required"===e?.type))&&(r.classList.contains("form-group")?t(r):e.add(r))})),this.form.querySelectorAll(".form-group[data-is-required='true']").forEach(t),[...e]}updateReactiveSubmitButtonState(){if(!this.reactiveSubmitDisabled||this._conditionLockedSubmit)return;const e=this.form.querySelector('button[type="submit"]');if(!e)return;const t=this.getReactiveRequiredFields();0===t.length||t.every((e=>this.isRequiredFieldFilled(e)))?e.removeAttribute("disabled"):e.setAttribute("disabled","disabled")}getValidationDefaultMessage(e,t){let r=e.dataset.label?e.dataset.label:"This field";switch(t.type){case"required":return r+" is required";case"email":return r+" is not a valid email address.";case"number":return r+" is not a valid number.";case"url":return r+" is not a valid URL.";case"minChars":return r+" must be at least "+t.charsCount+" characters long.";case"maxChars":return r+" must be at most "+t.charsCount+" characters long.";case"value":return r+" must be equal to "+t.value;case"custom":return r+" is not valid."}return"This field is not valid."}getInputElementsForAccessibility(e){const t=[];if(e.tagName&&["INPUT","TEXTAREA","SELECT"].includes(e.tagName))t.push(e);else{const r=e.querySelectorAll("input, textarea, select");if(e.classList.contains("brxe-brf-pro-forms-field-checkbox-wrapper")||e.classList.contains("brxe-brf-pro-forms-field-radio-wrapper"))r.forEach((e=>t.push(e)));else if("true"===e.dataset.useChoices){const r=e.querySelector("select");r&&t.push(r)}else r.length>0&&t.push(r[0])}return t}generateValidationMessageId(e){return`brf-validation-${e.name||e.dataset.customId||"field"}-${Date.now()}-${Math.floor(1e3*Math.random())}`}cleanupAriaAttributes(e,t){this.getInputElementsForAccessibility(e).forEach((e=>{if(e.setAttribute("aria-invalid","false"),t&&t.id){const r=e.getAttribute("aria-describedby");if(r){const a=r.split(" ").filter((e=>e!==t.id));a.length>0?e.setAttribute("aria-describedby",a.join(" ")):e.removeAttribute("aria-describedby")}}}))}markFieldAsInvalid(e,t){const r=e.closest(".form-group");r.classList.add("brf-invalid");const a=!(!e.dataset.showValidationMessage&&!e.dataset.showMessageBelowField||!e.dataset.showMessageBelowField),i=t.message?a?t.message:"":this.getValidationDefaultMessage(e,t);let n=r.querySelector(".brf-validation-message");n||(n=document.createElement("div"),n.classList.add("brf-validation-message"),n.id=this.generateValidationMessageId(e),n.setAttribute("role","alert"),n.setAttribute("aria-live","polite"),r.appendChild(n)),n.innerHTML=i;this.getInputElementsForAccessibility(e).forEach((e=>{if(e.setAttribute("aria-invalid","true"),i&&n.id){const t=e.getAttribute("aria-describedby");
1t?t.includes(n.id)||e.setAttribute("aria-describedby",`${t} ${n.id}`):e.setAttribute("aria-describedby",n.id)}}))}markFieldAsValid(e,t){const r=e.closest(".form-group"),a=e.closest(".brf-invalid");if(a&&a.classList.remove("brf-invalid"),this.isCheckboxOrRadioChild(e)&&"true"===r.getAttribute("data-has-validation-message")){const t=r.querySelectorAll("input[type='checkbox']:checked"),a=parseInt(r.dataset.isRequiredCount)||1;if(t.length>=a){r.removeAttribute("data-has-validation-message");const t=r.querySelector(".brf-validation-message");t&&(this.cleanupAriaAttributes(e,t),t.remove())}return}let i=r.querySelector(".brf-validation-message");i&&(this.cleanupAriaAttributes(e,i),i.remove())}handleSliders(e){if("undefined"==typeof noUiSlider)return;let t=e?[e]:this.form.querySelectorAll(".slider");t&&t.forEach((e=>{let t=e.dataset.settings,r=e.dataset.roundTo,a=e.dataset.bindings,i=e.dataset.singleBindings,n=e.dataset.staticValues;t&&(t=JSON.parse(t)),a&&(a=JSON.parse(a)),i&&(i=JSON.parse(i)),n&&(n=JSON.parse(n)),r&&(r=parseInt(r),t.format={to:e=>parseFloat(e).toFixed(r),from:e=>parseFloat(e).toFixed(r)}),n&&(t.format={to:function(e){return n[Math.round(e)]},from:function(e){return n.indexOf(e)}},t.pips&&(t.pips.format=t.format));let s=noUiSlider.create(e,t),o=e.closest(".form-group").querySelector("input");if(s.set(o.value),a&&a.forEach((e=>{let t=this.form.querySelector("[name='form-field-"+e.id+"']");t&&(t.value=o.value),t.addEventListener("change",(e=>{s.set(e.target.value)}))})),i)if("object"==typeof s.get())for(let e=0;e<s.get().length;e++){if(!i[e])continue;let t=this.form.querySelector("[name='form-field-"+i[e].fieldId+"']");t&&(t.value=s.get()[e]),t.addEventListener("change",(t=>{s.setHandle(e,t.target.value)}))}else if(i[0]){let e=this.form.querySelector("[name='form-field-"+i[0].fieldId+"']");e&&(e.value=s.get()),e.addEventListener("change",(e=>{s.set(e.target.value)}))}s.on("slide.one",((e,t)=>{if(o&&(o.value=s.get(),o.dispatchEvent(new Event("input",{bubbles:!0})),a&&a.forEach((e=>{let t=this.form.querySelector("[name='form-field-"+e.id+"']");t&&(t.value=o.value)})),i)){if(!i[t])return;let r=this.form.querySelector("[name='form-field-"+i[t].fieldId+"']");if(!r)return;r.value=e[t]}})),s.on("change",(t=>{(this.hasConditionalFieldLogic()||this.hasCalculationField())&&(this.handleLiveEventLogic(!0),this.handleCalculationFieldLogic(),this.handleStepConditions()),this.markFieldAsValid(e)}))}))}removeValidationErrors(){this.form.querySelectorAll(".brf-invalid").forEach((e=>{e.classList.remove("brf-invalid")})),this.form.querySelectorAll(".brf-validation-message").forEach((e=>{e.remove()})),this.form.querySelectorAll(".message.danger.error").forEach((e=>{e.remove()}))}handleDatePickers(){if(bricksQuerySelectorAll(this.form,".flatpickr").forEach((e=>{let t=e.dataset.bricksDatepickerOptions;if(t){t=JSON.parse(t),t.disableMobile=!0,t.onReady=function(e,t,r){let a=r.altInput.previousElementSibling?r.altInput.previousElementSibling.getAttribute("aria-label"):"Date";r.altInput.setAttribute("aria-label",a||"Date")};flatpickr(e,t)}})),!bricksIsFrontend)return;let e=this.form.querySelectorAll(".flatpickr-input");e&&e.forEach((e=>{let t=e.dataset.bricksDatepickerOptions,r=e.dataset.datepickerCustomOptions;if(t&&(t=JSON.parse(t)),r&&(r=JSON.parse(r)),null!=e.dataset.enableWeekdays){let r=e.dataset.enableWeekdays.split(" ");r=r.map((e=>7==(e=parseInt(e))?0:e));const a=t.enable?t.enable:[];t.enable=[function(e){let i=!1;if(a&&a.length>0)for(let t of a)if("string"==typeof t){const[r,a,n]=t.split("-").map(Number),s=e.getFullYear(),o=e.getMonth()+1,l=e.getDate();if(r===s&&a===o&&n===l){i=!0;break}}else if(t instanceof Date){if(t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()){i=!0;break}}else if("object"==typeof t&&null!==t&&"from"in t&&"to"in t){const r=t.from.split("-").map(Number),a=t.to.split("-").map(Number),n=new Date(r[0],r[1]-1,r[2],12,0,0),s=new Date(a[0],a[1]-1,a[2],12,0,0),o=new Date(e.getFullYear(),e.getMonth(),e.getDate(),12,0,0);if(o>=n&&o<=s){i=!0;break}}const n=t.disable?t.disable:[];for(let t of n)if("string"==typeof t){const[r,a,i]=t.split("-").map(Number),n=e.getFullYear(),s=e.getMonth()+1,o=e.getDate();if(r===n&&a===s&&i===o)return!1}else if(t instanceof Date){if(t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate())return!1}else if("object"==typeof t&&null!==t&&"from"in t&&"to"in t){const r=t.from.split("-").map(Number),a=t.to.split("-").map(Number),i=new Date(r[0],r[1]-1,r[2],12,0,0),n=new Date(a[0],a[1]-1,a[2],12,0,0),s=new Date(e.getFullYear(),e.getMonth(),e.getDate(),12,0,0);if(s>=i&&s<=n)return!1}return a&&a.length>0?i&&r.includes(e.getDay()):r.includes(e.getDay())}]}if("undefined"!=typeof flatpickr){if(bricksforgeData.datepickerInstances||(bricksforgeData.datepickerInstances=[]),e.closest("[data-on-day-create]")&&(t.onDayCreate=[],t.onDayCreate.push((function(t,r,a,i){let n=e.closest("[data-on-day-create]").dataset.onDayCreate;n&&(n=new Function("dObj","dStr","fp","dayElem",n),n(t,r,a,i))}))),r){let e,a=window.innerWidth;r.forEach((r=>{let i=r.breakpoint&&"default"!=r.breakpoint?parseInt(r.breakpoint):"default",n=r.options?r.options:{};"default"==i&&(i=99999),a<=i&&(e=n);let s=new Function("return "+e);"function"==typeof s&&(t=s())}))}window.innerWidth<991&&(t.disableMobile=!0);const a=!!e.dataset.bindTo&&e.dataset.bindTo,i=!!e.dataset.bindAsMinDate&&e.dataset.bindAsMinDate;t.onChange=(t,r,n)=>{if(a){let e=a.split(",");e=e.map((e=>e.trim())),e.forEach((e=>{if(!(e=this.getNodeFromFieldID(e)))return;const r=e.dataset.bricksDatepickerOptions?JSON.parse(e.dataset.bricksDatepickerOptions):{};let a=e._flatpickr;a||(a=flatpickr(e,r)),a&&(a.setDate(t[0],!0),i&&a.set("minDate",t[0]))}))}this.markFieldAsValid(e)};let n=flatpickr(e,t);bricksforgeData.datepickerInstances.push(n)}}))}handleRichText(){let e=this.form.querySelectorAll(".brf-rich-text-container");e&&0!==e.length&&e.forEach((e=>{if("TEXTAREA"!==e.tagName)return;if(window.tinymce){const t=window.tinymce.get(e.id);t&&t.save()}let t=e.closest(".form-group").querySelector("input[type='hidden'][data-type='rich-text']");t&&(t.value=e.value)}))}handleRatings(){let e=this.form.querySelectorAll(".brxe-brf-pro-forms-field-rating");e&&0!==e.length&&e.forEach((e=>{const t=e.querySelector("input[type='hidden']");let r=t.dataset.settings?JSON.parse(t.dataset.settings):{};const a=e.querySelectorAll(".brf-pro-forms-rating-icon");
1e.setAttribute("role","radiogroup");let i=r.iconColorHover,n=r.iconColorNormal,s=r.defaultRating;i&&i.raw?i=i.raw:i&&i.hex&&(i=i.hex),n&&n.raw?n=n.raw:n&&n.hex&&(n=n.hex);let o=-1;const l=e=>{a.forEach(((t,r)=>{const a=r<=e?i:n;if("svg"===t.tagName.toLowerCase())t.style.fill=a;else{t.style.color=a;const e=t.querySelector("svg");e&&(e.style.fill=a)}t.setAttribute("aria-checked",r===e?"true":"false")}))},c=r=>{t.value=r+1,o=r,l(o),this.markFieldAsValid(e),t.dispatchEvent(new Event("input",{bubbles:!0}))},d=()=>{l(o)};a.forEach(((e,r)=>{e.setAttribute("role","radio"),e.setAttribute("tabindex","0"),e.setAttribute("aria-checked","false"),e.setAttribute("aria-label",`Rating ${r+1}`),e.addEventListener("mouseover",(()=>{l(r)})),e.addEventListener("click",(()=>c(r))),e.addEventListener("keydown",(e=>{let i=!1,n=o;switch(e.key){case"ArrowRight":case"ArrowDown":n=o+1<a.length?o+1:0,i=!0;break;case"ArrowLeft":case"ArrowUp":n=o-1>=0?o-1:a.length-1,i=!0;break;case" ":case"Enter":t.value=r+1,o=r,l(o),i=!0}i&&(e.preventDefault(),n===o||"ArrowRight"!==e.key&&"ArrowDown"!==e.key&&"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(a[n].focus(),o=n,l(o)))}))})),e._hasMouseOutListener||(e._hasMouseOutListener=!0,e.addEventListener("mouseleave",d)),new MutationObserver((()=>{const e=parseInt(t.value,10);isNaN(e)||(o=e-1,l(o))})).observe(t,{attributes:!0,attributeFilter:["value"]}),s&&(t.value=s,o=s-1,l(o))}))}handleSignatures(e){let t=e?[e]:this.form.querySelectorAll(".brf-signature__pad");t&&0!=t.length&&(brfInitialFields.push({type:"signature",html:t[0].closest(".brxe-brf-pro-forms-field-signature").outerHTML}),t.forEach((e=>{let t=e.dataset.settings?JSON.parse(e.dataset.settings):{};if("undefined"==typeof SignaturePad)return;if(t.penColor&&t.penColor.includes("var")){const e=t.penColor.replace("var(","").replace(")","");t.penColor=window.getComputedStyle(document.body).getPropertyValue(e)}if(t.backgroundColor&&t.backgroundColor.includes("var")){const e=t.backgroundColor.replace("var(","").replace(")","");t.backgroundColor=window.getComputedStyle(document.body).getPropertyValue(e)}let r=new SignaturePad(e,t),a=e.closest(".brxe-brf-pro-forms-field-signature").querySelector("input");a.value&&r.fromDataURL(a.value),bricksforgeData.signaturePadInstances||(bricksforgeData.signaturePadInstances=[]),bricksforgeData.signaturePadInstances.push(r);const i=e=>{let t=Math.max(window.devicePixelRatio||1,1);e.width=e.offsetWidth*t,e.height=e.offsetHeight*t,e.getContext("2d").scale(t,t),r.clear(),a.value&&r.fromDataURL(a.value)};i(e),window.addEventListener("resize",(()=>{i(e)})),r.addEventListener("endStroke",(t=>{let i=r.toDataURL();a.value=i,this.markFieldAsValid(e),a.dispatchEvent(new Event("input",{bubbles:!0}))}))})))}static clearSignature(e){if(!e&&!e.target)return;let t=e.target.closest(".brxe-brf-pro-forms-field-signature").querySelector(".brf-signature__pad");t&&"undefined"!=typeof SignaturePad&&bricksforgeData.signaturePadInstances.forEach((e=>{if(e.canvas==t){e.clear();let r=t.closest(".brxe-brf-pro-forms-field-signature").querySelector("input");r.value="",r.dispatchEvent(new Event("input",{bubbles:!0}))}}))}handleMapFields(){const e=this.form.querySelectorAll(".brf-map-field");e&&0!==e.length&&(bricksforgeData.mapFieldInstances||(bricksforgeData.mapFieldInstances=[]),e.forEach((e=>{if("true"===e.dataset.mapInitialized)return;const t=new BrfMapField(e,this);bricksforgeData.mapFieldInstances.push(t),e.dataset.mapInitialized="true"})))}handleColorPickers(){if("undefined"==typeof Coloris)return;let e=this.form.querySelectorAll(".brxe-brf-pro-forms-field-color-picker");e&&0!=e.length&&e.forEach((e=>{let t=e.querySelector("input");if(!t)return;let r=t.dataset.options?JSON.parse(t.dataset.options):{};t.addEventListener("click",(e=>{Coloris({...r})}))}))}handleInputMasking(){let e=this.form.querySelectorAll("[data-input-mask]");e&&0!=e.length&&e.forEach((e=>{let t=e.dataset.inputMask;if(!t)return;if("undefined"==typeof IMask)return;t=JSON.parse(t);let r=!!t.method&&t.method;if(!r)return;let a=!!t.lazy&&t.lazy;if("pattern"===r){let r=!!t.maskPattern&&t.maskPattern,i=!!t.definitions&&t.definitions;if(!r)return;let n={};for(let e=0;e<i.length;e++){let t=i[e];t.mask||(t.mask="*"),t.mask.includes("/")&&(t.mask=t.mask.replace(/(^\/|\/$)/g,""),t.mask=new RegExp(t.mask)),delete t.id,n[t.n
1ame]=t,delete t.name}this.isProbablyRegex(r)&&(r=r.slice(1,-1),r=new RegExp(r)),IMask(e,{mask:r,definitions:{...n},lazy:a,overwrite:"shift"})}}))}isProbablyRegex(e){const t=e.startsWith("/"),r=e.endsWith("/");if(t&&r){const t=e.slice(1,-1);try{return new RegExp(t),!0}catch(e){return!1}}return!1}handleRepeaters(){let e=this.form.querySelectorAll(".brf-repeater-wrapper");e&&0!=e.length&&(e.forEach((e=>{this.populateRepeaterData(e),BrfProForms.updateRepeaterItemIndexes(e)})),this.form.addEventListener("click",(e=>{(e.target.classList.contains("brf-repeater-add-item")||e.target.closest(".brf-repeater-add-item"))&&this.handleInputMasking()})))}populateRepeaterData(e){let t=!!e.dataset.brfRepeaterData&&JSON.parse(e.dataset.brfRepeaterData);t&&0!=t.length&&(BrfProForms.syncRepeaterFields(e,t),this.handleInputMasking())}handleFileInputs(e,t){const r=e?[e]:this.form.querySelectorAll("input[type='file']");r&&r.forEach((e=>{let r=t||e.closest(".brxe-brf-pro-forms-field-file");r&&r.dataset&&r.dataset.theme&&(document.body.dataset.imageEditorTheme=r.dataset.theme)}))}async handleConditionalLogic(){return new Promise((e=>{const t=this.form.querySelectorAll("[data-brf-conditions]");for(let e=0;e<t.length;e++){const r=t[e],a=JSON.parse(r.dataset.brfConditions),i=r.dataset.brfConditionsRelation;this.handleConditionalFieldLogic(r,a,i)}e()}))}async buildStructure(){let e=[];for(let t=0;t<this.form.children.length;t++){let r=this.form.children[t];r.classList.contains("step")?e.length>0&&(this.structure.push(e),e=[]):e.push(r)}e.length>0&&this.structure.push(e),this.isMultiStepForm()&&this.assignStepNumbers(),this.form.querySelector(".is-group")&&await this.constructor.handleGroups(this.form),this.hasSummary&&this.handleSummaryStructure()}assignStepNumbers(){for(let e=0;e<this.structure.length;e++){const t=this.structure[e],r=e+1;t.forEach((e=>{e.classList.contains("form-group")&&(e.dataset.brfStep=r),e.classList.contains("brxe-brf-pro-forms-field-conditional-wrapper")&&(e.dataset.brfStep=r);e.querySelectorAll(".form-group").forEach((e=>{e.dataset.brfStep=r}));e.querySelectorAll("input, select, textarea, .form-group, .brxe-brf-pro-forms-field-conditional-wrapper").forEach((e=>{e.dataset.brfStep=r}))}))}}static async handleGroups(e,t=!1){if(e.querySelector(".group-end"))return new Promise((t=>{try{e.querySelectorAll(".group-start").forEach((e=>{let t=e.nextElementSibling,r=document.createElement("div");r.className=e.className;let a=[];for(;t&&!t.classList.contains("group-end");)a.push(t),t=t.nextElementSibling;a.forEach((e=>{e.classList.add("is-group-item"),r.appendChild(e)})),e.parentNode.insertBefore(r,e),r.classList.remove("group-start"),e.remove(),t&&t.remove()})),t()}catch(e){console.log(e),t()}}))}addStepIndexes(){const e=this.form.querySelectorAll(".brxe-brf-pro-forms-field-step.step");for(let t=0;t<e.length;t++)e[t].dataset.index=t+2}handleVisualSteps(){if(!this.hasShowStepsActive&&!this.hasRemoteSteps)return;let e=!1;if(this.hasRemoteSteps){let t=document.querySelector(".brf-steps-remote[data-brf-form-id='"+this.form.id+"']");e=t&&"true"===t.dataset.brfStepAllowClicks}let t=this.hasClicksAllowed||e,r=t?"button":"span",a=document.createElement("div");a.classList.add("brf-steps"),a.classList.add("form-group"),a.setAttribute("role","navigation"),a.setAttribute("aria-label","Form progress");for(let e=0;e<this.structure.length;e++){let i=document.createElement(r);i.classList.add("brf-step"),t&&(i.type="button"),i.innerHTML=e+1;let n=this.form.querySelectorAll(".step");if(e>0){if(void 0===n[e-1])continue;i.innerHTML=n[e-1].getAttribute("aria-label")?n[e-1].getAttribute("aria-label"):"Step",i.dataset.index=e}else 0==e&&(this.hasShowStepsActive&&this.form.dataset.brfFirstStep&&(i.innerHTML=this.form.dataset.brfFirstStep,i.dataset.index=e),this.hasRemoteSteps&&(this.remoteSteps=document.querySelector(".brf-steps-remote[data-brf-form-id='"+this.form.id+"']"),this.remoteSteps.dataset.brfFirstStep&&(i.innerHTML=this.remoteSteps.dataset.brfFirstStep,i.dataset.index=e)));a.appendChild(i)}if(this.hasSummary){let e=document.createElement(r);e.classList.add("brf-step"),t&&(e.type="button"),e.innerHTML=this.form.dataset.brfSummaryHeadline?this.form.dataset.brfSummaryHeadline:"Summary",e.dataset.index=this.structure.length-1,a.appendChild(e)}a.children[this.currentStep].classList.add("current"),a.children[this.currentStep].setAttribute("aria-current","step"),this.hasShowStepsActive&&this.form.prepend(a),this.checkForRemoteSteps()&&this.remoteSteps.dataset.brfFormId==this.form.id&&this.remoteSteps.append(a.cloneNode(!0))}addClassToCurrentStep(){let e,t;if(this.hasShowStepsActive&&(e=this.form.querySelectorAll(".brf-step")),this.hasRemoteSteps&&(t=this.remoteSteps.querySelectorAll(".brf-step")),e)for(let t=0;t<e.length;t++){let r=e[t];t==this.currentStep?(r.classList.add("current"),r.setAttribute("aria-current","step")):(r.classList.remove("current"),r.removeAttribute("aria-current"))}if(t)for(let e=0;e<t.length;e++){let r=t[e];e==this.currentStep?(r.classList.add("current"),r.setAttribute("aria-current","step")):(r.classList.remove("current"),r.removeAttribute("aria-current"))}}needsInitialRendering(){return"true"==this.form.dataset.brfNeedsRendering}handleSummaryStructure(){let e=this.structure[this.structure.length-1];for(let t=0;t<e.length;t++){let r=e[t];r.classList.contains("submit-button-wrapper")&&e.splice(t,1),r.classList.contains("submit-button-wrapper")&&e.splice(t,1)}let t=this.buildSummary();this.structure.push([t,this.form.querySelector(".submit-button-wrapper")]);let r=this.form.querySelector(".brf-hcaptcha-wrapper");if(r)for(let e=0;e<this.structure.length;e++){let t=this.structure[e];for(let e=0;e<t.length;e++){t[e].classList.contains("brf-hcaptcha-wrapper")&&(t.splice(e,1),this.structure[this.structure.length-1].push(r))}}}buildSummary(){this.summary=document.createElement("div"),this.summary.id="brf-summary";let e=this.form.querySelector(".submit-button-wrapper");this.isNestableForm&&(e=this.form.children[this.form.children.length-1]),e.before(this.summary);let t=this.form.querySelector(".brf-hcaptcha-wrapper");return t&&t.before(this.summary),this.summary}refreshSummary(){let e=this.summary;e.innerHTML="";let t=document.createElement("h3");t.classList.add("brf-summary-headline"),t.innerHTML=this.form.dataset.brfSummaryHeadline?this.form.dataset.brfSummaryHeadline:"Summary",e.append(t);for(let t=0;t<this.structure.length;t++){let r=this.structure[t];for(let t=0;t<r.length;t++){let a=r[t];if(!a)continue;let i=[];a.querySelector(".form-group")&&i.push(...a.querySelectorAll(".form-group")),a.classList.contains("form-group")&&i.push(a);for(let t=0;t<i.length;t++){let r=i[t];if(r.classList.contains("form-group")||null!=r.querySelector(".form-group")){let t=r.querySelector("label"),a=r.querySelector("input");if(a||(a=r.querySelector("textarea")),a||(a=r.querySelector("select")),r.querySelector("input[data-type=rich-text]")&&(a=r.querySelector("input[data-type=rich-text]")),a&&"password"==a.type)continue;if(r.querySelectorAll('input[type="checkbox"]').length>0){let e=r.querySelectorAll('input[type="checkbox"]:checked');a=Array.from(e).map((e=>e))}if(r.querySelector('input[type="radio"]')){let e=[];e.push(r.querySelector('input[type="radio"]:checked')),a=e}if(!a)continue;if(!this.form.dataset.brfSummaryEmpty&&!a.value&&"object"!=typeof a)continue;let i=document.createElement("div");i.classList.add("brf-summary-item");let n=document.createElement("h4");n.innerHTML=t?t.innerHTML:r.querySelector("*").getAttribute("aria-label"),i.append(n);let s=document.createElement("p");if(Array.isArray(a)){let e=[];for(let t=0;t<a.length;t++)a[t]&&(a[t].dataset&&a[t].dataset.label?e.push(a[t].dataset.label):e.push(a[t].innerText));s.innerHTML=e.join(", ")}else if("select"===a.tagName.toLowerCase()){let e=a.closest(".choices");if(e){let t=e.querySelector(`[data-choice][data-value="${a.value}"]`);s.innerHTML=t?t.innerText:this.form.dataset.brfSummaryEmptyText?this.form.dataset.brfSummaryEmptyText:"Empty"}else a.options[a.selectedIndex].dataset&&a.options[a.selectedIndex].dataset.label?s.innerHTML=a.options[a.selectedIndex].dataset.label:s.innerHTML=this.form.dataset.brfSummaryEmptyText?this.form.dataset.brfSummaryEmptyText:"Empty"}else"file"==a.type?s.innerText=a.files.length>0?Array.from(a.files).map((e=>e.name)).join(", "):this.form.dataset.brfSummaryEmptyText?this.form.dataset.brfSummaryEmptyText:"Empty":"rich-text"==a.dataset.type?s.innerHTML=a.value.replace(/(<([^>]+)>)/gi,"")?a.value:this.form.dataset.brfSummaryEmptyText?this.form.dataset.brfSummaryEmptyText:"Empty":(s.innerText=a.value?a.value:this.form.dataset.brfSummaryEmptyText?this.form.dataset.brfSummaryEmptyText:"Empty",s.innerText=s.innerText.replace(/(<([^>]+)>)/gi,""));i.append(s),e.append(i)}}}}this.isNestableForm&&(this.hideChild(this.form.querySelector(".brxe-brf-pro-forms-field-summary-button")),this.showChild(this.form.children[this.form.children.length-1]))}handleClickActions(){this.form.addEventListener("click",(e=>{e.target.classList.contains("next")&&(e.preventDefault(),this.jumpToNextStep(e))})),this.form.addEventListener("click",(e=>{e.target.classList.contains("prev")&&(e.preventDefault(),this.jumpToPrevStep(e))})),this.form.addEventListener("click",(e=>{e.target.classList.contains("summary")&&(e.preventDefault(),this.jumpToNextStep(e))})),(this.hasClicksAllowed||document.querySelector(".brf-steps-remote"))&&[this.form,this.remoteSteps].forEac
1h((e=>{e.classList&&e.classList.contains("brf-steps-remote")&&!e.dataset.brfStepAllowClicks||"object"==typeof e&&(NodeList.prototype.isPrototypeOf(e)||e.addEventListener("click",(e=>{this.hasRemoteSteps&&!this.isSyncSteps()||e.target.classList.contains("brf-step")&&(e.preventDefault(),this.hasSummary&&e.target.dataset.index==this.structure.length-1&&this.refreshSummary(),this.jumpToStepWithIndex(e.target.dataset.index,e).then((()=>{this.focusFirstFocusableInCurrentStep()})))})))})),this.form.querySelectorAll(".input-icon").forEach((e=>{e.addEventListener("click",(t=>{const r=e.nextElementSibling;r&&"INPUT"==r.tagName&&r.parentNode.dataset.focus&&"true"==r.parentNode.dataset.focus&&r.focus()}))}))}handleLiveEventLogic(e=!1){(this.hasSubmitConditions||this.hasCalculationField()||this.hasWcDynamicData()||this.hasConditionalFieldLogic())&&(!0===e&&this.fireFormDataRendering(),this.form.addEventListener("input",(e=>{"INPUT"!=e.target.tagName&&"TEXTAREA"!=e.target.tagName&&"SELECT"!=e.target.tagName||(this.fireFormDataRendering(),this.hasCalculationField()&&(this.handleCalculationFieldLogic(),setTimeout((()=>{this.handleCalculationFieldLogic()}),0)),this.handleStepConditions())})),document.addEventListener("brfQuillChange",(e=>{this.fireFormDataRendering(),this.markFieldAsValid(e.detail.input)})))}fireFormDataRendering(){this.needsFormDataRendering().length>0&&this.renderFormData(this.needsFormDataRendering()),this.hasConditionalFieldLogic()&&this.handleConditionalLogic()}hasConditionalFieldLogic(){return void 0!==this.form.querySelector("[data-brf-conditions]")}hasWcDynamicData(){return!!document.querySelector(".brf-form-wc-variation-price")}isSyncSteps(){return this.form.id.toLowerCase()==this.remoteSteps.dataset.brfFormId.toLowerCase()}loadingSequences(){if(!this.form.querySelector(".step-progress .next"))return;let e=this.form.querySelector(".step-progress .prev"),t=this.form.querySelector(".step-progress .next");null!=e&&(e.style.display=0==this.currentStep?"none":"inline-block"),null!=t&&(t.style.display=this.currentStep==this.structure.length-1?"none":"inline-block")}async showOnlyFirstStep(){if(this.isMultiStepForm())return new Promise(((e,t)=>{this.hideAllSteps();for(let e of this.structure[0])e&&this.showChild(e);this.handleStepButtonAdjustments(),e()}))}isSubmitStep(){return"none"!=this.form.querySelector(".submit-button-wrapper").style.display}needsAnimation(){let e=!!this.form.dataset.stepAnimation&&this.form.dataset.stepAnimation;return!!e&&(this.stepAnimationData=JSON.parse(e),"true"==this.stepAnimationData.animate)}async animationStart(e=!1){if(this.form.style.transition="all 150ms ease",!this.needsAnimation())return;if(this.isLastStep(),!this.stepAnimationData)return;let t=this.stepAnimationData.type?this.stepAnimationData.type:"fade",r=this.stepAnimationData.duration?this.stepAnimationData.duration:150;switch(window.getComputedStyle(this.form).transition&&"all 0s ease 0s"!=window.getComputedStyle(this.form).transition&&"all"!=window.getComputedStyle(this.form).transition||(this.form.style.transition="all "+r+"ms ease"),t){case"fade":default:this.form.style.opacity=0;break;case"fade-bottom":this.form.style.opacity=0,this.form.style.transform="translateY(20px)";break;case"fade-top":this.form.style.opacity=0,this.form.style.transform="translateY(-20px)";break;case"fade-left":this.form.style.opacity=0,this.form.style.transform="translateX(-20px)";break;case"fade-right":this.form.style.opacity=0,this.form.style.transform="translateX(20px)"}return new Promise((e=>{setTimeout((()=>{e()}),r)}))}animationEnd(){if(!this.needsAnimation())return;if(!this.stepAnimationData)return;let e=this.stepAnimationData.type?this.stepAnimationData.type:"fade",t=this.stepAnimationData.duration?this.stepAnimationData.duration:150;return new Promise((r=>{setTimeout((()=>{switch(e){case"fade":default:this.form.style.opacity=1;break;case"fade-bottom":case"fade-top":this.form.style.opacity=1,this.form.style.transform="translateY(0px)";break;case"fade-left":case"fade-right":this.form.style.opacity=1,this.form.style.transform="translateX(0px)"}r()}),t)}))}async _renderStep(e,t=!1){await this.animationStart(t),this.hideAllSteps();for(let t of this.structure[e])this.showChild(t);this.currentStep=e,this.refreshPrevAndNextButtons(),this.handleStepButtonAdjustments(),(this.hasShowStepsActive||this.hasRemoteSteps)&&this.addClassToCurrentStep(),this.handleConditionalLogic(),this.handleRequiredFields(),this.handleSignatures(),this.scrollToTop(),this.autoFocusField(),await this.animationEnd()}async jumpToStepWithIndex(e,t){const r=parseInt(e,10);if(this.currentStep!==r)try{if(this.currentStep>r){if(!(await this.checkStepConditions({event:t,fromStep:this.currentStep+1,toStep:r+1})).result)return;return this.removeValidationErrors(),void await this._renderStep(r,!0)}this.removeValidationErrors();for(let e=this.currentStep;e<r;e++){if(e!==this.currentStep){const r=await this.checkStepConditions({event:t,fromStep:this.currentStep+1,toStep:e+1});if(!r.result){if("hide-step"===r.method)continue;return}}if(!1===await this.validateStep(e))return void(e!==this.currentStep&&(await this._renderStep(e,!1),this.scrollToInvalidField()))}await this._renderStep(r,!1)}finally{this.forceLiveValidation=!1}}handleConditionalStepsLogic(e,t,r){if(!t)return!0;this.saveOriginalDisplayState(e);let a=!1,i=[];for(let e of t){let t;switch(e.condition){case"form_field":let r=this.form.querySelector(`[name="form-field-${e.value}"]`);r||(r=this.form.querySelector(`[name="form-field-${e.value}[]"]:checked`));let a=!1;r||(r=this.form.querySelector(`[name="form-field-${e.value}[]"]`),r&&(a=!0));let n=r?r.value:null;if(a){let e=r.selectedOptions;if(e){let t=[];for(let r of e)t.push(r.value);n=t}}if(r&&"checkbox"==r.type){let t=this.form.querySelectorAll(`[name="form-field-${e.value}[]"]:checked`);t.length>0?(n=[],t.forEach((e=>{n.push(e.value)}))):n=null}if(r&&"radio"==r.type){let t=this.form.querySelector(`[name="form-field-${e.value}[]"]:checked`);n=t?t.value:null}n||i.push(!1),t=this.startCondition(e.value2,n,e.operator,e.type),i.push(t);break;case"storage_item":const s=localStorage.getItem(e.value);t=this.startCondition(e.value2,s,e.operator,e.type),i.push(t)}}a="and"==r?i.every((e=>e)):i.some((e=>e));if(this.isMultiStepForm()){const t=this.currentStep+1;let r=e.dataset.brfStep;if(!r&&e.closest("[data-brf-step]")&&(r=e.closest("[data-brf-step]").dataset.brfStep),r&&(r=parseInt(r)),t!=r)return!0}!1===a?(e.style.setProperty("display","none"),e.classList.add("brf-hidden")):(e.dataset.originalDisplay&&"none"!=e.dataset.originalDisplay?e.style.setProperty("display",e.dataset.originalDisplay):e.style.setProperty("display","flex"),e.classList.remove("brf-hidden")),this.handleRequiredFields()}async handleStepConditions(){const e=this.isMultiStepForm(),t=this.form.querySelector(".brxe-brf-pro-forms-field-step[data-brf-conditions]");if(e&&t)for(let e=0;e<this.structure.length;e++)await this.checkStepConditions({event:null,fromStep:e+1,toStep:e+2})}async checkStepConditions({event:e,fromStep:t,toStep:r}){const a=document.querySelector(`.brxe-brf-pro-forms-field-step[data-index="${r}"]`);if(!a||!a.dataset.brfConditions)return{result:!0};const i=a.dataset.brfConditions,n=a.dataset.brfConditionsRelation,s=a.dataset.brfConditionalMethod,o=a.dataset.brfErrorMessage,l=JSON.parse(i),c=await this.evaluateConditions(l,n);if(c){if("hide-step"===s){let e=this.form.querySelector(`.brf-steps .brf-step[data-index="${r-1}"]`),t=document.querySelector(`.brf-steps-remote[data-brf-form-id="brxe-${this.form.dataset.scriptId}"] .brf-steps .brf-step[data-index="${r-1}"]`);e&&(e.style.display="flex"),t&&(t.style.display="flex")}}else switch(s){case"prevent-navigation":e&&this.fireProValidationMessage("error",o,!1);break;case"hide-step":let t=this.form.querySelector(`.brf-steps .brf-step[data-index="${r-1}"]`),a=document.querySelector(`.brf-steps-remote[data-brf-form-id="brxe-${this.form.dataset.scriptId}"] .brf-steps .brf-step[data-index="${r-1}"]`);t&&(t.style.display="none"),a&&(a.style.display="none")}return{result:c,message:o,method:s,toStep:r}}async jumpToNextStep(e){if(this.currentStep==this.structure.length-1)return;let t=this.currentStep+1,r={result:!1};for(;t<this.structure.length&&!r.result;)if(r=await this.checkStepConditions({event:e,fromStep:this.currentStep+1,toStep:t+1}),!r.result){if("hide-step"!=r.method)break;t++}if(r.result){if(0==await this.validateCurrentStep())return;await this.animationStart(),this.hideAllSteps();for(let e of this.structure[t])this.showChild(e);this.currentStep=t,this.refreshPrevAndNextButtons(),this.hasSummary&&this.isLastStep()&&this.refreshSummary(),(this.hasShowStepsActive||this.hasRemoteSteps)&&this.addClassToCurrentStep(),this.handleConditionalLogic(),this.handleRequiredFields(),this.handleStepButtonAdjustments(),this.handleSignatures(),this.scrollToTop(),this.autoFocusField(),this.removeValidationErrors(),await this.animationEnd()}this.forceLiveValidation=!1}async jumpToPrevStep(e){if(0==this.currentStep)return;let t=this.currentStep-1,r={result:!1};for(;t>=0&&!r.result;)if(r=await this.checkStepConditions({event:e,fromStep:this.currentStep+1,toStep:t+1}),!r.result){if("hide-step"!=r.method)break;t--}if(r.result){await this.animationStart(!0),this.hideAllSteps();for(let e of this.structure[t])this.showChild(e);this.currentStep=t,this.refreshPrevAndNextButtons(),(this.hasShowStepsActive||this.hasRemoteSteps)&&this.addClassToCurrentStep(),this.handleStepButtonAdjustments(),this.handleRequiredFields(),this.isNestableForm&&this.showChild(this.form.querySelector(".brxe-brf-pro-forms-field-summary-button")),this.scrollToTop(),this.autoFocusField(),await this.animationEnd(),this.forceLiveValidation=!1}}scrollToTop(){if(!!!this.form.dataset.brfJumpToTop)return;let e=this.form.dataset.brfJumpOffset?this.form.dataset.brfJumpOffset:50;requestAnimationFrame((()=>{window.scrollTo({top:this.form.getBoundingClientRect().top+window.scrollY-e,left:window.scrollX,behavior:"auto"})}))}autoFocusField(){if(!!!this.form.dataset.brfAutoFocusFirstField)return;let e=this.structure[this.currentStep].find((e=>e.querySelector("input, textarea, select")));if(e){let t=e.querySelector("input, textarea, select");t&&t.focus()}}focusFirstFocusableInCurrentStep(){if(!this.structure||!this.structure[this.currentStep])return;let e='input:not([type="hidden"]):not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled]), a[href], [tabindex]:not
1([tabindex="-1"])';for(let t of this.structure[this.currentStep]){let r=t.matches(e)?t:t.querySelector(e);if(r)return void r.focus()}}handleStepButtonAdjustments(){this.form.querySelector(".step-progress")&&(!this.isSecondLastStep()&&!this.isLastStep()||this.isFirstStep()?this.form.querySelector(".step-progress").style.width="100%":this.form.querySelector(".step-progress").style.width="auto",this.isNestableForm&&this.form.querySelectorAll(".step-progress").forEach((e=>{e.dataset.brfStep&&parseInt(e.dataset.brfStep)!=this.currentStep+1&&(this.hasSummary&&this.isLastStep()&&e.querySelector(".prev")?e.querySelector(".prev").style.display="inline-block":e.style.display="none")})))}showChild(e){if(this.isMultiStepForm()&&e&&(e.style.display=e.dataset.originalDisplay&&e.dataset.originalDisplay||"flex",e.dataset.visible=!0,e.closest(".is-group"))){let t=e.closest(".is-group");t.style.display=t.dataset.originalDisplay||"flex"}}hideChild(e){if(this.isMultiStepForm()&&e&&(window.getComputedStyle(e).display&&"none"!=window.getComputedStyle(e).display&&!e.dataset.originalDisplay&&(e.dataset.originalDisplay=window.getComputedStyle(e).display),e.style.display="none",e.dataset.visible=!1,e.closest(".is-group"))){let t=e.closest(".is-group");window.getComputedStyle(t).display&&"none"==window.getComputedStyle(t).display?t.dataset.originalDisplay=window.getComputedStyle(t).display:t.dataset.originalDisplay="flex",t.style.display="none"}}hideAllSteps(){for(let e of this.structure)for(let t of e)t&&(t.classList.contains("step-progress")||this.hideChild(t))}isFirstStep(){return 0==this.currentStep}isLastStep(){return this.currentStep==this.structure.length-1}isSecondLastStep(){return this.currentStep==this.structure.length-2}hasDisplayNoneParent(e){let t=e.parentElement;for(;t&&!t.classList.contains("brxe-brf-pro-forms");){if("none"===getComputedStyle(t).display)return!0;t=t.parentElement}return!1}needsToBeIgnored(e){const t=e.classList.contains("brf-hidden"),r=e.classList.contains("brf-hidden--conditional"),a=e.closest(".brf-hidden"),i=e.closest(".brf-hidden--conditional");if(t||r||a||i)return!0;if(this._isValidatingStep)return!1;const n="none"===e.style.display,s="none"===e.closest(".form-group")?.style?.display,o=this.hasDisplayNoneParent(e);return n||s||o}ignoreValidation(e){return!!this.needsToBeIgnored(e)}async validateCurrentStep(){return await this.validateFields({scope:"step",step:this.currentStep})}refreshPrevAndNextButtons(){const e=this.form.querySelector(".step-progress .prev"),t=this.form.querySelector(".step-progress .next");null!=e&&(e.style.display=0==this.currentStep?"none":"inline-block"),null!=t&&(t.style.display=this.currentStep==this.structure.length-1?"none":"inline-block"),this.hasSummary&&this.currentStep==this.structure.length-2&&null!=t&&(t.style.display="none")}showLoading(){this.form.querySelector("button[type='submit']").classList.add("sending")}hideLoading(){this.form.querySelector("button[type='submit']").classList.remove("sending")}resetValidationMessages(){this.form.querySelectorAll(".brf-invalid").forEach((e=>{e.classList.remove("brf-invalid")})),this.form.querySelectorAll(".brf-validation-message").forEach((e=>{e.remove()}))}async handleSubmit(){this.form.querySelector("button[type=submit]")&&(this.form.querySelector("button[type=submit]").addEventListener("mouseenter",(()=>{this.handleRequiredFields()})),this.form.addEventListener("submit",(async e=>{e.preventDefault(),this.resetValidationMessages(),this.showLoading();let t=this.form.querySelector('button[type="submit"]'),r=null;if(this.handleRequiredFields(),await this.formValid()&&(r=await this.submitForm(),this.form.dispatchEvent(new CustomEvent("brf_submit",{bubbles:!0,cancelable:!0,detail:{success:r,payload:this.submissionPayload}})),!1===r))return!1;this.showResults(t),this.afterFormSubmit(!1!==r&&null!==r),setTimeout((()=>{this.isSubmitting=!1}),1e3)}),!0))}handleGlobalVariables(){window.bricksforgeData||(window.bricksforgeData={}),window.bricksforgeData?.globalVariables||(window.bricksforgeData.globalVariables={}),window.bricksforgeData.globalVariables=new Proxy(window.bricksforgeData.globalVariables||{},{set:(e,t,r)=>(e[t]=r,this.handleConditionalLogic(),!0),get:(e,t)=>e[t]})}showResults(e){if(this.form.dataset.brfDisableReset?this.form.addEventListener("reset",(e=>{e.preventDefault()})):this.formIsValid?this.form.querySelectorAll(".ql-editor").forEach((e=>{e.innerHTML=""})):this.hideLoading(),this.isSubmitting=!0,this.results.error)return this.hideLoading(),this.results.error=this.results.error.filter(((e,t,r)=>r.findIndex((t=>t.message===e.message))===t)),void this.results.error.forEach((e=>{this.fireProValidationMessage("error",e.message,!0)}));if(this.hideLoading(),this.results.success&&this.results.success.length&&this.results.success[this.results.success.length-1].message&&(this.fireProValidationMessage("success",this.results.success[this.results.success.length-1].message),this.form.querySelectorAll(".brf-validation-message").forEach((e=>{e.remove()})),this.results.success.forEach((e=>{switch(e.action){case"show_download_info":if(!e.trigger||"automatic"==e.trigger)break;e.downloadUrl&&this.openDownloadInfo(e.downloadUrl);break;case"create_pdf":e.showPdf&&this.openDownloadInfo(e.pdfUrl)}}
1))),this.results.redirect&&this.results.redirect.length>0){const e=this.results.redirect[0].redirectTo,t=this.results.redirect[0].redirectTimeout?this.results.redirect[0].redirectTimeout:0;e&&setTimeout((()=>{this.navigateTo(e)}),t)}if(this.results.reload&&this.results.reload.length>0){const e=this.results.reload?.[0]?.delay??0;setTimeout((()=>{this.reloadPage()}),e)}}openDownloadInfo(e){let t=this.form.querySelector(".brf-pro-forms-field-file-download");if(!t)return!1;let r=t.querySelector(".file-download-btn");if(!r)return!1;r.href=e,t.classList.remove("brf-pending")}afterFormSubmit(e){if(e){if(window.bricksforgeData&&window.bricksforgeData.temporaryFileUploads&&(window.bricksforgeData.temporaryFileUploads=[]),!this.form.dataset.brfDisableReset){if(this.form.querySelectorAll(".brf-field-image-preview").forEach((e=>{e.remove()})),bricksforgeData&&bricksforgeData.signaturePadInstances)for(let e of bricksforgeData.signaturePadInstances)e.clear();if(this.form.querySelectorAll(".brf-field-image-preview-wrapper").forEach((e=>{e.innerHTML=""})),this.resetFormExceptChoices(),this.resetChoicesFields(),bricksforgeData&&bricksforgeData.filePondInstances)for(let e of bricksforgeData.filePondInstances)e.removeFiles()}this.isMultiStepForm()&&"true"===this.form.dataset.brfBackToFirstStepAfterSubmit&&this.jumpToStepWithIndex(0),this.form.dataset.confetti&&this.fireConfetti()}}resetFormExceptChoices(){this.form.querySelectorAll('input, textarea, select:not([data-use-choices="true"])').forEach((e=>{"checkbox"===e.type||"radio"===e.type?e.checked=e.defaultChecked:e.value=e.defaultValue}))}resetChoicesFields(){this.form.querySelectorAll('select[data-use-choices="true"]').forEach((e=>{if(e.choices){const t=e.querySelector("option[selected]")||e.querySelector("option:first-child");t?e.choices.setChoiceByValue(t.value):e.choices.removeActiveItems()}}))}wcRefreshMiniCart(){document.body.dispatchEvent(new CustomEvent("wc_fragment_refresh"))}async renderFormData(e=[]){const t=await this.runRequests(!0);for(let r of e)switch(r){case"submitConditions":this.handleConditionalSubmitLogic(t);break;case"wcDynamicData":this.handleWcDynamicData(t)}this.afterInitialRendering()}afterInitialRendering(){this.form.dataset.brfNeedsRendering&&(this.form.dataset.brfNeedsRendering=!1),this.form.dataset.brfSubmitConditions&&(this.form.dataset.brfSubmitConditions=!1)}async handleWcDynamicData(e){if(!document.querySelector(".brf-form-wc-variation-price"))return;const t=document.querySelectorAll(".brf-form-wc-variation-price");for(let r of t){const t=r.dataset.formId;if(e.formID==t&&e.wc&&e.wc.variation_price)return void(r.innerHTML=e.wc.variation_price);r.innerText=""}}getComponentId(){const e=this.form.dataset.componentId;if(e)return e;const t=this.form.dataset.scriptId;return t&&t.includes("-")?t.split("-")[1]:""}getHiddenFields(){let e=[];return this.form.querySelectorAll("[data-validation]").forEach((t=>{if(t.dataset.useChoices){if(t.closest(".brf-hidden")||t.closest(".brf-hidden--conditional")){const r=t.name.replace("form-field-","");e.push(r)}}else if(t.classList.contains("brf-hidden")||t.closest(".brf-hidden")||"none"==window.getComputedStyle(t).display||"none"==window.getComputedStyle(t.closest(".form-group")).display||this.hasDisplayNoneParent(t)){if(t.closest("[data-brf-step]")&&!this.ignoreValidation(t))return;let r=t.name;if(t.name&&t.name.includes("form-field-"))r=t.name.replace("form-field-",""),e.push(r);else{let r=t.querySelector("input");if(r){let t=r.name.replace("[]","");t=t.replace("form-field-",""),e.push(t)}}}})),this.form.querySelectorAll(".brxe-brf-pro-forms-field-conditional-wrapper.brf-hidden--conditional").forEach((t=>{if(!!t.dataset?.brfAlwaysSendFormData)return;t.querySelectorAll("input, select, textarea").forEach((t=>{const r=t.name.replace("form-field-","");e.push(r)}))})),this.ignoreConditionallyHiddenFieldsInActions&&this.form.querySelectorAll(".brf-hidden--conditional").forEach((t=>{t.dataset.customId&&e.push(t.dataset.customId)})),e}isWooCommerce(){return!!this.form.dataset.wc}async runRequests(e=!1,t=null,r=null){const a=[];if(e){if(!this.hasCalculationField()&&!this.hasSubmitConditions&&!this.needsInitialRendering())return;this.hasCalculationField()&&this.form.querySelectorAll(".calculation-field").forEach((e=>{a.push(e.dataset.elementId)}))}let i={};this.form.querySelectorAll(".form-group").forEach((e=>{let t=e.dataset.customId,r=e.dataset.elementId;if(e.classList.contains("brxe-brf-pro-forms-field-checkbox-wrapper")&&(r+="[]"),t&&r)i[t]=r;else if(r){const e=r.replace("[]","");i[e]=r}}));let n=this.form.dataset.brfDynamicPostId,s=BRFELEMENTS.apiurl+"form_submit";if(e&&(s=BRFELEMENTS.apiurl+"render_form_data"),!e&&this.form.querySelector('input[type="file"]')){let e=new FormData,t=this.form.querySelectorAll('input[type="file"]');for(let r=0;r<t.length;r++){let a=t[r],i=a.files,n=a.accept;
1for(let t=0;t<i.length;t++){let r=i[t];e.append(a.name+"_"+t,r),e.append("allowed_types",n)}}this.form.querySelector("button[type=submit]").classList.add("sending")}let o={};this.form.querySelectorAll("[data-custom-id]").forEach((e=>{const t=t=>{for(let r=t.parentElement;r&&r!==e;r=r.parentElement)if(r.matches("li, .options-wrapper, .filepond--root"))return!0;return!1},r=Array.from(e.querySelectorAll("label")).find((e=>!t(e)));let a=r?r.innerText:"";if(!a){const r=Array.from(e.querySelectorAll("input[data-label], textarea[data-label], select[data-label]")).find((e=>!t(e)));a=e.dataset.label||(r?r.dataset.label:"")}if(a||(a=e.dataset.customId),e.closest(".brf-repeater-item")){let t=e.closest(".brxe-brf-pro-forms-field-repeater");if(t){let e=t.dataset.customId,r=t.dataset.label?t.dataset.label:null;r&&!o["brfr_"+e]&&(o["brfr_"+e]=r)}}o[e.dataset.customId]||(o[e.dataset.customId]=a)}));let l={};this.form.querySelectorAll("input[type=checkbox]:checked, input[type=radio]:checked").forEach((e=>{if(!e)return;let t,r=e.closest("[data-custom-id]")?.dataset.customId,a=e.value;try{t=e.dataset.label?e.dataset.label:e.closest("li")?.querySelector("label")?.innerText||""}catch(e){t=""}r&&a&&t&&(l[r]||(l[r]=[]),l[r].push({value:a,label:t}))}));let c=[];this.hasCalculationField()&&this.isWooCommerce()&&(this.handleCalculationFieldLogic(),await Promise.all(Array.from(this.form.querySelectorAll(".calculation-hash")).map((async e=>{if(e.value){let t=e.parentNode.querySelector(".calculation-result").value,r=await fetch(BRFELEMENTS.ajaxurl,{method:"POST",headers:{"X-WP-Nonce":BRFELEMENTS.nonce,"Content-Type":"application/x-www-form-urlencoded"},body:"action=bricksforge_get_calculation_hash&nonce="+BRFELEMENTS.ajaxNonce+"&result="+t});if(!r)return;if("object"!=typeof r)return;let a=await r.json();if(!a.success&&!a.data&&!a.data.hash)return;let i=a.data.hash;e.value=i,c.push(i)}}))));let d={};if(this.hasCalculationField())for(let e of this.form.querySelectorAll(".calculation-field"))d[e.dataset.elementId]=e.querySelector(".calculation-result").dataset.rawResult;let u={},f=this.form.querySelectorAll("[data-context]");f.length>0&&f.forEach((e=>{let t=e.closest("[data-custom-id]")?.dataset.customId;if(t||(t=e.dataset.customId),!t)return;e.dataset.context;u[t]=e.dataset.context}));let m=new FormData(this.form);m.append("postId",window.bricksData.postId),m.append("formId",this.form.dataset.scriptId),m.append("formIdFallback",this.form.dataset.elementId),m.append("componentId",this.getComponentId()),m.append("fieldIds",JSON.stringify(i)),m.append("calculationFields",JSON.stringify(a)),m.append("action","bricksforge_form_submit"),m.append("referrer",window.location.href),m.append("fieldLabels",JSON.stringify(o)),m.append("postContext",JSON.stringify(u)),BRFELEMENTS&&BRFELEMENTS.templateIds&&m.append("templateIds",JSON.stringify(BRFELEMENTS.templateIds)),l&&m.append("checkboxRadioLabels",JSON.stringify(l)),d&&m.append("calculationFieldRawValues",JSON.stringify(d)),c.length>0&&m.append("calculationHashes",JSON.stringify(c));const h=this.getHiddenFields();m.append("hiddenFields",JSON.stringify(h)),h.forEach((e=>{let t=this.form.querySelector(`[name="form-field-${e}"]`);if(t){if(!t.classList.contains("brf-hidden--conditional")&&!t.closest(".brf-hidden--conditional"))return;m.delete(t.name)}})),this.form.querySelectorAll("input[type=checkbox]").forEach((e=>{e.checked||m.append(e.name,0)}));var p=e=>{brfLocalFiles[e].forEach((t=>{m.append("".concat(e),t,t.name)}))};for(var b in brfLocalFiles)p(b);let g=[];this.form.querySelectorAll("[data-validation]").forEach((e=>{this.ignoreValidation(e)||(e.dataset.customId?g.push(e.dataset.customId):e.name&&g.push(e.name.split("form-field-").pop()))})),m.append("fieldsToValidate",JSON.stringify(g)),n&&m.append("dynamicPostId",n),t&&m.append("captchaResult",t),r&&m.append("turnstileResult",r);let y=[];bricksforgeData.temporaryFileUploads&&bricksforgeData.temporaryFileUploads.length&&bricksforgeData.temporaryFileUploads.forEach((e=>{e.field.includes("[]")&&(e.field=e.field.replace("[]","")),y.push({file:e.file,field:e.field})})),y.length>0&&m.append("temporaryFileUploads",JSON.stringify(y));let S=window.bricksforgeData.initialFiles;S&&S.length>0&&m.append("initialFiles",JSON.stringify(S));let v=await fetch(BRFELEMENTS.ajaxurl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"action=bricksforge_regenerate_nonce"});if(v){let e=await v.json();e&&e.data&&e.data.nonce&&(BRFELEMENTS.nonce=e.data.nonce)}const w={};m.forEach(((e,t)=>{w[t]=e})),this.submissionPayload={formData:w,formId:this.form.dataset.elementId,postId:window.bricksData.postId,fieldIds:i};try{let e=await fetch(s,{method:"POST",headers:{"X-WP-Nonce":BRFELEMENTS.nonce},body:m}),t=await e.json();return t&&t.results&&(this.results=t.results),null!=t.success&&0==t.success?(this.hideLoading(),t):t}catch(e){console.log(e)}}hasCalculationField(){return this.form.querySelector(".calculation-field")}calculate(e){let t=(new exprEval.Parser).evaluate(e);return 0===t?0:!(!t||t.error)&&t}toCurrencyFormat(e){e=parseFloat(e);let t="de-DE";bricksData&&bricksData.locale&&(t=bricksData.locale,t=t.replace("_","-")),t.includes("_formal")&&(t=t.replace("_formal",""));return new Intl.NumberFormat(t,{style:"decimal",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}parseFormula(e,t,r){if(!e)return!1;let a=e.match(/{(.*?)}/g);if(!a)return e;const i=(e,r)=>{let a=e.value;if(a&&"string"==typeof a&&a.match(/^\d{1,3}(,\d{3})*(\.\d+)?$/)&&(a=a.replace(/,/g,"")),e.dataset.calculationValue&&(a=e.dataset.calculationValue),a&&a.includes(",")&&(a=a.replace(/\./g,""),a=a.replace(",",".")),!a&&t.setEmptyToZero&&(a=0),t.ignoreHiddenFields&&(e.parentNode.classList.contains("brf-hidden--conditional")||e.closest(".brxe-brf-pro-forms-field-conditional-wrapper")&&e.closest(".brxe-brf-pro-forms-field-conditional-wrapper").classList.contains("brf-hidden--conditional"))&&(a=null),e.multiple){let t=[];for(let r=0;r<e.options.length;r++)e.options[r].selected&&t.push(parseFloat(e.options[r].value));a=t.reduce(((e,t)=>parseFloat(e)+parseFloat(t)),0)}if(e&&"checkbox"===e.type){let t=this.form.querySelectorAll(`input[name="form-field-${r}[]"]`);if(t.length>0){let e=[];t.forEach((t=>{t.checked&&e.push(void 0!==t.dataset.calculationValue?t.dataset.calculationValue:t.value)})),a=e.reduce(((e,t)=>
1parseFloat(e)+parseFloat(t)),0),a&&!isNaN(a)||(a=null)}else a=e.checked?e.dataset.calculationValue||e.value:null}if(e&&"radio"===e.type){let e=this.form.querySelector(`input[name="form-field-${r}[]"]:checked`);a=e?e.dataset.calculationValue||e.value:null}if("SELECT"===e.tagName){let t=e.options[e.selectedIndex];a=t.dataset.calculationValue||t.value}if(!a||isNaN(a)){if(!t.setEmptyToZero)return null;a=0}return a};for(let t of a){let a=!1,n=t.replace(/{|}/g,"");if(n.includes("*")){n=n.replace("*","");let r=this.form.querySelectorAll(`[name^="form-field-${n}"], [name^="form-field-${n}[]"], [data-original-name^="form-field-${n}"]`),a=[];r.forEach((e=>{const t=i(e,n);null!==t&&a.push(parseFloat(t))}));let s=a.reduce(((e,t)=>e+t),0);return e=e.replace(t,s)}let s=this.form.querySelectorAll(`[name="form-field-${n}"], [name="form-field-${n}[]"], [data-original-name="form-field-${n}"]`);if(!s||0===s.length)continue;let o,l=s[s.length-1];if((l.getAttribute("name")&&l.getAttribute("name").endsWith("[]")&&l.closest(".brf-repeater-item")||l.dataset.originalName&&l.closest(".brf-repeater-item"))&&(a=!0),a){let e=[];e=r.closest(".brf-repeater-item")?r.closest(".brf-repeater-item").querySelectorAll(`[data-original-name="form-field-${n}"]`):this.form.querySelectorAll(`[data-original-name="form-field-${n}"]`);let t=[];e.forEach((e=>{let r=i(e,n);null!==r&&t.push(parseFloat(r))})),o=t.reduce(((e,t)=>e+t),0)}else o=i(l,n);if(null===o)return!1;e=e.replace(t,o)}return e.includes("{")?(console.warn("Your formula cannot be parsed. Please check your formula and if every form field really exists."),!1):e}handleRemoteCalculations(e,t,r){document.querySelectorAll(`.brf-form-calculation-value[data-calculation-id="${e.dataset.customId}"]`).forEach((e=>{t?(t=this.handleRemotePostCalculation(t,e.dataset.calculationOperator,e.dataset.calculationValue,e.dataset.calculationOperator2,e.dataset.calculationValue2,r.hasCurrencyFormat,r.roundValue),e.innerText=t):e.innerText=r.emptyMessage?r.emptyMessage:""}))}async sha256(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async hashCalculationField(e,t){let r=e.querySelector(".calculation-hash");if(r&&t){let e=await this.sha256(t.toString());r.value=e}}async handleCalculationFieldLogic(){if(!this.hasCalculationField())return;this.form.querySelectorAll(".calculation-field").forEach((e=>{let t={};e.dataset.options&&(t=JSON.parse(e.dataset.options));let r=t.formula;if(r=this.parseFormula(r,t,e),!r)return e.querySelector(".calculation-result").value=t.emptyMessage?t.emptyMessage:"",void this.handleRemoteCalculations(e,null,t);let a=this.calculate(r);if(void 0!==a&&!1!==a&&"number"==typeof a){let r=a;if(t.roundValue){const e=t.roundDecimals?t.roundDecimals:2;a=this.calculate("roundTo("+a+", "+e+")")}t.hasCurrencyFormat&&(a=this.toCurrencyFormat(a)),e.querySelector(".calculation-result").dataset.rawResult=r,e.querySelector(".calculation-result").value=a,this.handleRemoteCalculations(e,a,t),this.hashCalculationField(e,a),this.debouncedHandleLiveValues()}}))}handleRemotePostCalculation(e,t,r,a,i,n=!1,s=!1){if(!t||!r)return e;e=parseFloat(e),r=parseFloat(r);let o=this.performOperation(e,t,r);return a&&i&&(i=parseFloat(i),o=this.performOperation(o,a,i)),s&&(o=Math.round(o)),n&&(o=o.toFixed(2),o=o.replace(/\B(?=(\d{3})+(?!\d))/g,",")),o}performOperation(e,t,r){if(!["add","subtract","multiply","divide"].includes(t))return e;switch(t){case"add":return e+r;case"subtract":return e-r;case"multiply":return e*r;case"divide":return e/r;default:return e}}resetSubmitButtonText(e){if(!e){let t=this.form.querySelector('button[type="submit"]');t&&t.dataset.submitButtonText&&(e=t.dataset.submitButtonText)}if(!e)return;this.form.querySelector('button[type="submit"] .text').innerHTML=e}modifySubmitButton({action:e=null,alternativeText:t=null}={}){let r=this.form.querySelector('button[type="submit"]'),a="inline-flex";switch(e){case"hide":r.style.display="none",this._conditionLockedSubmit=!0;break;case"show":r.style.display=a,r.removeAttribute("disabled"),this._conditionLockedSubmit=!1,this.updateReactiveSubmitButtonState();break;case"disabled":r.setAttribute("disabled","disabled"),r.style.display=a,t&&(r.querySelector(".text").innerText=t),this._conditionLockedSubmit=!0;break;default:r.style.display="inline-flex",this._conditionLockedSubmit=!1}}async handleConditionalSubmitLogic(e){if(!this.form.dataset.brfSubmitConditions)return;if(!e.submitConditions)return;const t=e.submitConditionsData;let r=t.relation,a=!1,i=[];for(let r of e.submitConditions){let e;switch(r.condition){case"option":case"post_meta":case"form_field":e=this.startCondition(r.value2,r.data,r.operator,r.dataType),i.push(e);break;case"storage_item":e=this.startCondition(r.value2,window.localStorage.getItem(r.value),r.operator,r.dataType),i.push(e);break;case"submission_count_reached":e=this.startCondition(t.submissionsCount,t.submission_max?t.submission_max:null,!1,!1,!0),i.push(e);break;case"submission_field":e=this.startCondition(r.value2,r.data?r.data[0].value:null,r.operator,r.dataType),i.push(e);break;default:i.push(!1)}}a="and"==r?i.every((e=>1==e)):i.some((e=>1==e)),!0!==a?(t.submitButtonConditionsAlternativeText&&this.resetSubmitButtonText(t.submitButtonText),this.modifySubmitButton({action:"show"})):this.modifySubmitButton({action:t.submitButtonConditionAction,alternativeText:t.submitButtonConditionsAlternativeText?t.submitButtonConditionsAlternativeText:null})}getNodeFromFieldID(e){const t=this.form;if(!t)return null;let r=t.querySelector(`[name="form-field-${e}"]`);return r||(r=t.querySelector(`[name="form-field-${e}[]"]`)),r||null}getFileFieldContent(e){if(!e||"file"!==e.type)return"";let t=[];if(window.bricksforgeData&&window.bricksforgeData.filePondInstances&&window.bricksforgeData.filePondInstances.length>0){const r=e.closest(".filepond--root");
1if(r){const e=window.bricksforgeData.filePondInstances.find((e=>e.element.closest(".filepond--root")===r));if(e){t=e.getFiles().map((e=>e.file))}}}if(0===t.length&&e.files&&e.files.length>0&&(t=Array.from(e.files)),t.length>0){const e=t.filter((e=>e.type.startsWith("image/"))),r=t.filter((e=>!e.type.startsWith("image/")));let a="";if(e.length>0&&e.forEach((e=>{const t=`brf-file-placeholder-${Date.now()}-${Math.random()}`;a+=`<span id="${t}" data-file-name="${e.name}" data-file-size="${e.size}">Loading image...</span>`;const r=new FileReader;r.onload=function(r){const a=document.getElementById(t);a&&(a.outerHTML=`<img data-brf-file-name="${e.name}" data-brf-file-size="${e.size}" src="${r.target.result}" style="width: 100%; object-fit: contain;" alt="Preview" />`)},r.readAsDataURL(e)})),r.length>0){const e=r.map((e=>e.name)).join(", ");a+=e}return a}return""}maybeParseVariable(e,t=null){if(!e||"string"!=typeof e)return t||e;if(e.match(/{{.*}}/))try{const r=e,a=r.match(/{{(.*?)}}/g);if(!a)return e;let i=r;for(const e of a){let r=e.replace(/{{(.*?)}}/g,"$1"),a=null;if(r.includes("@fallback=")){const e=r.match(/@fallback=[\"\'](.*?)[\"\']/);e&&void 0!==e[1]&&(a=e[1],a.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&(a=`<img src="${a}" style="width: 100%; object-fit: contain;" alt="Fallback Image" />`)),r=r.replace(/@fallback=[\"\'](.*?)[\"\']/,"").trim()}if(!r)continue;if(r.match(/@label(?:=[\"\'](true)[\"\'])?/)){if(r=r.replace(/@label(?:=[\"\'](true)[\"\'])?/,"").trim(),!r||!this.form)continue;let n=this.form.querySelector(`[name="form-field-${r}"]`);if(n||(n=this.form.querySelector(`[name="form-field-${r}[]"]`)),n)try{let t=n.getAttribute("data-label");if("checkbox"===n.type||"radio"===n.type){const e=n.closest(".form-group");if(e){const r=e.querySelector("label");r&&r.textContent&&(t=r.textContent.trim())}}else{const e=n.closest(".form-group");if(e){const r=e.querySelector("label");r&&r.textContent&&(t=r.textContent.trim())}}if(t){i=i.replace(e,t);continue}}catch(e){continue}i=null!==a?i.replace(e,a):i.replace(e,t||"");continue}if(r.match(/@value(?:=[\"\'](true)[\"\'])?/)){r=r.replace(/@value(?:=[\"\'](true)[\"\'])?/,"").trim();let t=null;if(this.form.querySelectorAll(`[name="form-field-${r}[]"][type="radio"]`).length>0){let e=this.form.querySelector(`[name="form-field-${r}[]"][type="radio"]:checked`);t=e?e.value:null!==a?a:""}else{if(this.form.querySelectorAll(`[name="form-field-${r}[]"][type="checkbox"]`).length>0){let e=this.form.querySelectorAll(`[name="form-field-${r}[]"][type="checkbox"]:checked`);if(e.length>0){t=Array.from(e).map((e=>e.value)).join(", ")}else t=null!==a?a:""}else{let e=this.form.querySelector(`[name="form-field-${r}"]`);e&&(t="checkbox"===e.type||"radio"===e.type?e.checked?e.value:null!==a?a:"":e.value||"")}}if(null!==t){i=i.replace(e,t);continue}}if(!this.form){if(null!==a){i=i.replace(e,a);continue}i=i.replace(e,t||"");continue}let n,s=this.form.querySelectorAll(`[name="form-field-${r}[]"][type="radio"]`),o=null;if(o=s.length>0?this.form.querySelector(`[name="form-field-${r}[]"][type="radio"]:checked`):this.form.querySelector(`[name="form-field-${r}"]`),o||(o=this.form.querySelector(`[name="form-field-${r}[]"]`)),o||(o=this.form.querySelector(`[name="form-field-${r}[]"]:checked`)),o){if(o)if("checkbox"===o.type){const e=this.form.querySelectorAll(`[name="form-field-${r}[]"]:checked`);n=e.length>0?Array.from(e).map((e=>e.dataset.label?e.dataset.label:e.value)).join(", "):null!==a?a:""}else if("radio"===o.type)n=o.checked?o.dataset.label?o.dataset.label:o.value:null!==a?a:"";else if("SELECT"===o.tagName)if(o.multiple){const e=o.querySelectorAll("option:checked");n=Array.from(e).map((e=>e.dataset.label||e.textContent||e.value)).join(", ")}else{const e=o.querySelector("option:checked");n=e.dataset&&e.dataset.label?e.dataset.label:e.textContent?e.textContent:e.value}else n="file"===o.type?this.getFileFieldContent(o):o.value;i=n?i.replace(e,n):null!==a?i.replace(e,a):i.replace(e,t||"")}else i=null!==a?i.replace(e,a):i.replace(e,t||"")}return i}catch(r){return console.error("Error parsing variable:",r),t||e}return t||e}saveOriginalDisplayState(e){window.getComputedStyle(e).display&&"none"!=window.getComputedStyle(e).display&&!e.dataset.originalDisplay&&(e.dataset.originalDisplay=window.getComputedStyle(e).display)}async evaluateConditions(e,t){if(!e)return!0;let r=[];for(let t of e){let e;switch(t.condition){case"form_field":if(!t.value){r.push(!1);break}t.value.match(/{{.*}}/)&&(t.value=t.value.replace(/{{(.*?)}}/g,"$1"));let a=this.form.querySelector(`[name="form-field-${t.value}"]`);a||(a=this.form.querySelector(`[name="form-field-${t.value}[]"]:checked`));let i=!1;a||(a=this.form.querySelector(`[name="form-field-${t.value}[]"]`),a&&(i=!0)),a&&a.classList&&a.classList.contains("calculation-result")&&await new Promise((e=>setTimeout(e,50)));let n=a?a.value:null;if(i){let e=a.selectedOptions;if(e){let t=[];for(let r of e)t.push(r.value);n=t}}if(a&&"checkbox"==a.type){let e=this.form.querySelectorAll(`[name="form-field-${t.value}[]"]:checked`);e.length>0?(n=[],e.forEach((e=>{n.push(e.value)}))):n=null}if(a&&"radio"==a.type){let e=this.form.querySelector(`[name="form-field-${t.value}[]"]:checked`);n=e?e.value:null}e=this.startCondition(t.value2,n,t.operator,t.type),r.push(e);break;case"storage_item":const s=localStorage.getItem(t.value);e=this.startCondition(t.value2,s,t.operator,t.type),r.push(e);break;case"global_variable":let o=this.getGlobalVariables();e=this.startCondition(t.value2,o[t.value],t.operator,t.type),r.push(e)}}return"and"==t?r.every((e=>e)):r.some((e=>e))}async handleConditionalFieldLogic(e,t,r){if(!t)return!0;this.saveOriginalDisplayState(e);const a=await this.evaluateConditions(t,r);if(this.isMultiStepForm()){const t=this.currentStep+1;let r=e.dataset.brfStep;if(!r&&e.closest("[data-brf-step]")&&(r=e.closest("[data-brf-step]").dataset.brfStep),r&&(r=parseInt(r)),t!=r)return!0}!1===a?(e.style.setProperty("display","none"),e.classList.add("brf-hidden","brf-hidden--conditional")):(e.dataset.originalDisplay&&"none"!=e.dataset.originalDisplay?e.style.setProperty("display",e.dataset.originalDisplay):e.style.setProperty("display","flex"),e.classList.remove("brf-hidden"),e.classList.remove("brf-hidden--conditional")),this.handleRequiredFields()}
1startCondition(e,t,r,a="string",i=!1){if(i){return isNaN(e)||(e=parseFloat(e)),isNaN(t)||(t=parseFloat(t)),e>=t}if(!(e&&t||"exists"==r||"empty"==r||"not_exists"==r||"not_empty"==r))return!1;switch(e=this.maybeParseVariable(e),t=this.maybeParseVariable(t),"number"==a&&(e=parseFloat(e),t=parseFloat(t)),"string"==typeof e&&(e=e.replace(/(<([^>]+)>)/gi,"")),"string"==typeof t&&(t=t.replace(/(<([^>]+)>)/gi,"")),r){case"==":return e==t;case"!=":return e!=t;case">":return t>e;case"<":return t<e;case">=":return t>=e;case"<=":return t<=e;case"contains":return t.includes(e);case"not_contains":return!t.includes(e);case"contained_in":return e.includes(t);case"is_not_contained_in":return!e.includes(t);case"starts_with":return t.startsWith(e);case"ends_with":return t.endsWith(e);case"empty":return"array"==a?0==t.length:!t||""==t;case"not_empty":return"array"==a?t.length>0:t&&""!=t;case"exists":return t&&""!=t;case"not_exists":return!t||""==t;default:return!1}}hideSubmitButton(){this.form.querySelector("button[type=submit]").style.display="none"}showSubmitButton(){this.form.querySelector("button[type=submit]").style.display="inline-block"}scrollToInvalidField(){const e=this.form.querySelector(".brf-invalid");e&&e.scrollIntoView({behavior:"smooth"})}async validateForm(){let e=!0;return this.form.querySelectorAll("[data-validation]").forEach((t=>{if(this.ignoreValidation(t))return;t.closest(".form-group");this.handleLiveValidation(t,!0)||(this.forceLiveValidation=!0,this.scrollToInvalidField(),e=!1)})),e}sortFieldsByPosition=e=>Array.from(e).sort(((e,t)=>{const r=e.getBoundingClientRect(),a=t.getBoundingClientRect();return Math.abs(r.top-a.top)<5?r.left-a.left:r.top-a.top}));async validateStep(e){this._isValidatingStep=!0;try{let t=!0;for(let r of this.structure[e]){if(this.ignoreValidation(r))continue;let e=[];r.dataset.validation&&e.push(r);r.querySelectorAll("[data-validation]").forEach((t=>{this.ignoreValidation(t)||e.push(t)}));for(let r of e){this.forceLiveValidation=!0;this.handleLiveValidation(r,!0)||(t=!1,this.scrollToInvalidField())}}return t}finally{this._isValidatingStep=!1}}async validateFields({scope:e="form",step:t=null}){switch(e){case"form":return await this.validateForm();case"step":return await this.validateStep(t)}}async formValid(){const e=await this.validateFields({scope:"form"});return this.formIsValid=e,e}isMultiStepForm(){return this.form.classList.contains("brxe-form-multistep")||null!=this.form.querySelector(".step")}async checkForCaptchas(){return new Promise((async(e,t)=>{if(this.form.querySelector(".h-captcha")){const a=this.form.querySelector(".h-captcha iframe").dataset.hcaptchaWidgetId;
1var r=hcaptcha.getResponse(a);if(""===r)return t("hCaptcha challenge not completed"),!1;e(r)}else if(this.form.querySelector("[id^='recaptcha-']")){const r=this.form.querySelector("[id^='recaptcha-']").getAttribute("data-key");if(!r)return t("Google reCaptcha: Site key not found"),!1;if("undefined"==typeof grecaptcha||!grecaptcha.execute)return t("Google reCaptcha: Script not loaded"),!1;try{const a=await grecaptcha.execute(r,{action:"submit"});if(!a||""===a)return t("Google reCaptcha: Invalid token"),!1;e(a)}catch(e){return t("Google reCaptcha: "+e.message),!1}}else e(!0)}))}async checkForTurnstile(){return new Promise((e=>{this.form.querySelector(".cf-turnstile")?setTimeout((()=>{const t=this.form.querySelector('input[name="cf-turnstile-response"]');if(t&&t.value&&""!==t.value.trim()){const r=t.value.trim();e(r)}else{const t=this.form.querySelector(".cf-turnstile");if(window.turnstile&&t)try{const r=t.getAttribute("data-turnstile-widget-id");if(r){const t=window.turnstile.getResponse(r);if(t)return void e(t)}}catch(e){}e(!1)}}),100):e(!0)}))}async disableSubmitButton(){this.form.querySelector("button[type=submit]").setAttribute("disabled","disabled")}async enableSubmitButton(){const e=this.form.dataset?.submitDisableDelay?this.form.dataset.submitDisableDelay:.2;setTimeout((()=>{this.form.querySelector("button[type=submit]").removeAttribute("disabled")}),1e3*e)}async submitForm(){return this.disableSubmitButton(),new Promise((async(e,t)=>{let r;try{r=await this.checkForCaptchas()}catch(t){let r="Please verify that you are not a robot.";if(this.form.querySelector(".h-captcha")){let e=this.form.querySelector(".h-captcha");e&&e.dataset.info&&(r=e.dataset.info)}else this.form.querySelector("[id^='recaptcha-']")&&(r=t||"Google reCaptcha verification failed. Please try again.");return this.fireProValidationMessage("error",r,!0),this.enableSubmitButton(),e(!1),!1}if(!r){let t="Please verify that you are not a robot.",r=this.form.querySelector(".h-captcha");return r&&r.dataset.info&&(t=r.dataset.info),this.fireProValidationMessage("error",t,!0),this.enableSubmitButton(),e(!1),!1}const a=await this.checkForTurnstile();if(!a){let t="Please verify that you are not a robot.",r=this.form.querySelector("[data-turnstile-error-message]");return r&&r.dataset.turnstileErrorMessage&&(t=r.dataset.turnstileErrorMessage),this.fireProValidationMessage("error",t,!0),this.enableSubmitButton(),e(!1),!1}const i=await this.runRequests(!1,r,a);if(i&&i.webhook&&Array.isArray(i.webhook)&&i.webhook.length>0&&console.log("Webhook Result",i.webhook),i&&null!=i.success&&0==i.success){if(i.data.message&&this.fireProValidationMessage("error",i.data.message),i.data.validation){let e=null;i.data.validation.forEach((t=>{let r=this.form.querySelector('[name="'+t.field+'"]');if(!r){let e=t.field.replace("form-field-","");r=this.form.querySelector('[data-custom-id="'+e+'"]')}r||(r=this.form.querySelector('[name="'+t.field+'[]"]'),r&&(r=r.closest(".form-group"))),r&&r.dataset.validation?(r.dataset.showValidationMessage=!0,this.handleValidationEvents(!0),this.markFieldAsInvalid(r,t),e||(e=r)):this.fireProValidationMessage("error",t.message,!0)})),e&&e.scrollIntoView({behavior:"smooth",block:"center"})}return this.enableSubmitButton(),e(!1),!1}if(i&&i.data&&i.data.status)switch(i.data.status){case 401:case 403:case 500:return this.fireProValidationMessage("error",i.message),this.enableSubmitButton(),e(!1),this.hideLoading(),!1}if(i&&i.results.error)return i.results.error.forEach((e=>{this.fireProValidationMessage("error",e.message,!0)})),this.enableSubmitButton(),e(!1),!1;if(!i)return this.fireProValidationMessage("error","An error occurred. Please contact the site administrator.",!0),this.enableSubmitButton(),e(!1),!1;if(!await this.handleProValidation(i))return this.enableSubmitButton(),e(!1),!1;if(i&&i.results){let e=null,t=null;if(i.results.success&&Array.isArray(i.results.success)&&(e=i.results.success.find((e=>e&&"stripe"===e.action&&e.stripe_redirect&&e.redirect_url)),e&&(t="stripe"),e||(e=i.results.success.find((e=>e&&"mollie"===e.action&&e.mollie_redirect&&e.redirect_url)),e&&(t="mollie"))),e&&t&&e.redirect_url){const r={formId:this.form.dataset.elementId,sessionIdentifier:e.session_identifier||"",timestamp:Date.now(),formPageUrl:window.location.href};if(localStorage.setItem(`brf_${t}_payment_pending`,JSON.stringify(r)),!document.getElementById("brf-payment-overlay-styles")){const e=document.createElement("style");e.id="brf-payment-overlay-styles",e.textContent="\n .brf-payment-processing-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n }\n .brf-payment-processing-content {\n text-align: center;\n color: white;\n }\n .brf-payment-processing-content p {\n margin-top: 20px;\n font-size: 18px;\n font-weight: 500;\n }\n .brf-spinner {\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-radius: 50%;
1\n border-top: 4px solid white;\n width: 50px;\n height: 50px;\n animation: brf-spin 1s linear infinite;\n margin: 0 auto;\n }\n @keyframes brf-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(e)}const a=document.createElement("div");a.className="brf-payment-processing-overlay",a.innerHTML='\n <div class="brf-payment-processing-content">\n <div class="brf-spinner"></div>\n <p>Processing payment...</p>\n </div>\n ',document.body.appendChild(a),this.navigateTo(e.redirect_url);const i=this;return void setTimeout((()=>{document.querySelector(".brxe-brf-pro-forms")&&i.startPaymentPolling(t)}),500)}}for(let e in i)switch(e){case"update_option":case"update_post_meta":this.liveUpdateValue(i[e]),this.handleConditionalSubmitLogicIfNeeded();break;case"update_user_meta":this.liveUpdateValue(i[e]);break;case"set_storage_item":this.setStorageItems(i[e]),this.liveUpdateValue(i[e]),this.handleConditionalSubmitLogicIfNeeded();break;case"wc_add_to_cart":!0===i[e]&&document.body.dispatchEvent(new CustomEvent("added_to_cart",{}))}this.enableSubmitButton(),e(!0)}))}async handleProValidation(e){for(let t in e)if("create_submission"===t)if(e[t]&&e[t].status&&"duplicate"==e[t].status)return this.fireProValidationMessage(e[t].message),!1;return!0}fireProValidationMessage(e="error",t,r=!1){this.form.querySelector("button[type=submit]").addEventListener("click",(function(){this.form.querySelectorAll(".message").forEach((e=>{e.style.display="none"}))})),setTimeout((()=>{const a=this.form.querySelector(".message.danger");a&&!r&&this.form.removeChild(a);const i=document.createElement("div");"error"==e?i.classList.add("message","danger","error"):i.classList.add("message","success");const n=document.createElement("div");n.classList.add("text");t=t.replace(/(<script>|<\/script>|<style>|<\/style>|<iframe>|<\/iframe>)/gi,""),n.innerHTML=t,i.appendChild(n),this.form.appendChild(i),"error"==e&&(this.hideLoading(),setTimeout((()=>{i.style.display="none"}),5e3),i.addEventListener("click",(()=>{i.style.display="none"})))}),50)}handleConditionalSubmitLogicIfNeeded(){this.form.dataset.brfSubmitConditions&&this.renderFormData(["submitConditions"])}liveUpdateValue(e){if("object"==typeof e)for(let t of e){if(!t.selector||!t.live)continue;let e=document.querySelector(t.selector);if(null==e)continue;let r=this.dispatchLiveUpdateSelectorEvent("brf_live_update",t);setTimeout((()=>{r.detail.newValue&&(t.value=r.detail.newValue),r.detail.newTarget&&(e=document.querySelector(r.detail.newTarget)),r.defaultPrevented||(this.form.querySelector(t.selector)&&!r.detail.newTarget?this.form.querySelector(t.selector).innerHTML=t.value:e.innerHTML=t.value)}))}}dispatchLiveUpdateSelectorEvent(e,t){const r=document.querySelector(t.selector);if(!r)return;if(!(r instanceof HTMLElement))return;let a=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.form.dispatchEvent(a),a}setStorageItems(e){if("object"==typeof e)for(let t of e)if(t.name){t.type||(t.type="replace");try{let e=window.localStorage.getItem(t.name);switch(t.type){case"replace":window.localStorage.setItem(t.name,t.value);break;case"increment":e?window.localStorage.setItem(t.name,parseInt(e)+1):window.localStorage.setItem(t.name,1);break;case"decrement":e&&window.localStorage.setItem(t.name,parseInt(e)-1);break;case"increment_by_number":e?window.localStorage.setItem(t.name,parseInt(e)+parseInt(t.value)):window.localStorage.setItem(t.name,parseInt(t.value));break;case"decrement_by_number":e&&window.localStorage.setItem(t.name,parseInt(e)-parseInt(t.value));break;case"add_to_array":if(e)if(brfIsParsable(e)&&"object"==typeof JSON.parse(e)){let r=JSON.parse(e);r.push(t.value),window.localStorage.setItem(t.name,JSON.stringify(r))}else window.localStorage.setItem(t.name,JSON.stringify([e,t.value]));else window.localStorage.setItem(t.name,JSON.stringify([t.value]));break;case"remove_from_array":if(e&&brfIsParsable(e)&&"object"==typeof JSON.parse(e)){let r=JSON.parse(e),a=r.indexOf(t.value);a>-1&&r.splice(a,1),window.localStorage.setItem(t.name,JSON.stringify(r))}}}catch(e){console.log(e)}}}startPaymentPolling(e="stripe"){if(this.form.querySelectorAll(".brf-form-message, .brf-validation-message, .message").forEach((e=>e.remove())),!document.querySelector(".brf-payment-processing-overlay")){const e=document.createElement("div");e.className="brf-payment-processing-overlay",e.innerHTML='\n <div class="brf-payment-processing-content">\n <div class="brf-spinner"></div>\n <p>Processing payment...</p>\n </div>\n ',document.body.appendChild(e)}let t=0;let r=0;const a=localStorage.getItem(`brf_${e}_payment_pending`),i=a?JSON.parse(a).sessionIdentifier:null;this.paymentPollingInterval=setInterval((()=>{t++,t-r>=10&&i&&(r=t,fetch(window.location.origin+`/wp-json/bricksforge/v1/payment-status/${e}/`+i).then((e=>e.json())).then((t=>{if("cancelled"===t.status){clearInterval(this.paymentPollingInterval);const r=document.querySelector(".brf-payment-processing-overlay");r&&r.remove(),this.form.classList.remove("form-loading");const a=this.form.querySelector('button[type="submit"]');a&&(a.classList.remove("sending"),a.disabled=!1),localStorage.removeItem(`brf_${e}_payment_complete`),localStorage.removeItem(`brf_${e}_payment_pending`),this.fireProValidationMessage("error",t.message||"Payment was cancelled. Please try again.",!1),this.form.scrollIntoView({behavior:"auto",block:"center"})}})).catch((()=>{})));const a=localStorage.getItem(`brf_${e}_payment_complete`);if(a){const t=JSON.parse(a),r=!t.provider||t.provider===e;if(t.formId===this.form.dataset.elementId&&r){clearInterval(this.paymentPollingInterval);const r=document.querySelector(".brf-payment-processing-overlay");r&&r.remove();this.form.querySelectorAll(".brf-form-message, .brf-validation-message, .message").forEach((e=>e.remove())),this.form.style.visibility="visible",this.form.style.display="block",this.form.classList.remove("form-loading");const a=this.form.querySelector('button[type="submit"]');a&&(a.classList.remove("sending"),a.disabled=!1),t.redirectUrl&&t.redirectUrl!==window.location.href.split("?")[0]?this.navigateTo(t.redirectUrl):(this.fireProValidationMessage("success",t.message,!1),this.form.scrollIntoView({behavior:"auto",block:"center"}),t.results&&t.results.success&&Array.isArray(t.results.success)&&t.results.success.forEach((e=>{"confetti"===e.action&&this.fireConfetti()}))),localStorage.removeItem(`brf_${e}_payment_complete`),localStorage.removeItem(`brf_${e}_payment_pending`)}}if(t>=240){clearInterval(this.paymentPollingInterval);const t=document.querySelector(".brf-payment-processing-overlay");t&&t.remove(),this.form.classList.remove("form-loading");const r=this.form.querySelector('button[type="submit"]');r&&(r.classList.remove("sending"),r.disabled=!1),localStorage.removeItem(`brf_${e}_payment_complete`),localStorage.removeItem(`brf_${e}_payment_pending`);const a=e.charAt(0).toUpperCase()+e.slice(1);this.fireProValidationMessage("error",`Payment verification timed out. Please check if the payment was processed in your ${a} dashboard. If the webhook is not configured, the payment cannot be verified automatically.`,!1)}}),500)}startStripePaymentPolling(){this.startPaymentPolling("stripe")}}var brfScrollVideoInstances=[],brfScrollVideoCurrentInstance=null;class BrfScrollVideo{scrollVideo;data={src:null,transitionSpeed:8,frameThreshold:.1,cover:!1,sticky:!1,full:!0,trackScroll:!0,useWebCodecs:!0,debug:!1};constructor(e){this.scrollVideo=e,this.init()}init(){if(!ScrollyVideo)throw new Error("The Scroll Video Library is not defined");this.buildVars(),this.createInstance()}buildVars(){this.scrollVideo.dataset.src&&(this.data.src=this.scrollVideo.dataset.src),this.scrollVideo.dataset.transitionSpeed&&(this.data.transitionSpeed=this.scrollVideo.dataset.transitionSpeed),this.scrollVideo.dataset.frameThreshold&&(this.data.frameThreshold=this.scrollVideo.dataset.frameThreshold),this.scrollVideo.dataset.cover?this.data.cover=this.scrollVideo.dataset.cover:this.data.cover=!1,this.scrollVideo.dataset.sticky&&1==this.scrollVideo.dataset.sticky?this.data.sticky=this.scrollVideo.dataset.sticky:this.data.sticky=!1,this.scrollVideo.dataset.full?this.data.full=this.scrollVideo.dataset.full:this.data.full=!1,this.scrollVideo.dataset.useWebCodecs?this.data.useWebCodecs=this.scrollVideo.dataset.useWebCodecs:this.data.useWebCodecs=!1,this.scrollVideo.dataset.debug?this.data.debug=this.scrollVideo.dataset.debug:this.data.debug=!1}createInstance(){"true"!==this.scrollVideo.dataset.brfInitialized&&(0==this.data.full&&(this.data.cover=!1,this.data.useWebCodecs=!1),brfScrollVideoCurrentInstance=new ScrollyVideo({scrollyVideoContainer:this.scrollVideo,src:this.data.src,transitionSpeed:this.data.transitionSpeed,frameThreshold:this.data.frameThreshold,cover:this.data.cover,sticky:this.data.sticky,full:this.data.full,trackScroll:this.data.trackScroll,useWebCodecs:!!bricksIsFrontend&&this.data.useWebCodecs,debug:this.data.debug}),this.scrollVideo.dataset.brfInitialized="true")}}class BrfThreeJs{root;scene;camera;renderer;loader;controls;data={};model;models=[];clock;mixer;constructor(e){this.root=e,this.init()}init(){if(!THREE)throw new Error("The Three.js Library is not defined");this.clock=new THREE.Clock,this.data=this.root.dataset.data?this.parsePossiblyMultipleJSON(this.root.dataset.data):{},this.data=this.convertNumericToFloat(this.data),this.identifyModel(),this.createScene(),this.addModel(),this.animate=this.animate.bind(this),this.animate()}parsePossiblyMultipleJSON(e){try{return JSON.parse(e)}catch(e){}const t="["+e.replace(/}\s*{/g,"}, {")+"]";
1try{return JSON.parse(t)[t.length-1]}catch(e){throw new Error("Invalid JSON input: "+e.message)}}convertNumericToFloat(e){for(let t in e)"string"!=typeof e[t]||isNaN(e[t])||(e[t]=parseFloat(e[t]));return e}identifyModel(){if(this.data&&this.data.model){if("string"==typeof this.data.model&&(this.data.model.includes(".gltf")||this.data.model.includes(".glb")))return void(this.model=this.data.model);const e=this.data.model.filename,t=BRFELEMENTS.uploadsDirectory+"/bricksforge/models/"+this.data.model.id+"/"+e;this.model=t}}createScene(){this.scene=new THREE.Scene,this.handleCamera(),this.handleLight(),this.handleRenderer(),this.handleControls(),window.addEventListener("resize",(()=>{this.handleResize()}))}handleCamera(){this.camera=new THREE.PerspectiveCamera(this.data.cameraFov,window.innerWidth/window.innerHeight,this.data.cameraNear,this.data.cameraFar),this.camera.position.x=this.data.cameraPositionX,this.camera.position.y=this.data.cameraPositionY,this.camera.position.z=this.data.cameraPositionZ,bricksforgeData.cameras=bricksforgeData.cameras||{},bricksforgeData.cameras[this.data.id]=this.camera}handleRenderer(){this.renderer=new THREE.WebGLRenderer({alpha:!0,antialias:this.data.rendererAntialiasing}),this.renderer.setSize(window.innerWidth,window.innerHeight),this.root.querySelector("canvas")||this.root.querySelector(".brf-three-js-scene").appendChild(this.renderer.domElement)}handleLight(){this.data.light.forEach((e=>{let t;switch((e=this.convertNumericToFloat(e)).type){case"ambient":t=new THREE.AmbientLight(e.color.hex,e.intensity);break;case"directional":t=new THREE.DirectionalLight(e.color.hex,e.intensity);break;case"hemisphere":t=new THREE.HemisphereLight(e.color.hex,e.groundColor,e.intensity);break;case"point":t=new THREE.PointLight(e.color.hex,e.intensity,e.distance,e.decay);break;case"rectarea":t=new THREE.RectAreaLight(e.color.hex,e.intensity,e.width,e.height);break;case"spot":t=new THREE.SpotLight(e.color.hex,e.intensity,e.distance,e.angle,e.penumbra,e.decay);break;default:t=new THREE.AmbientLight(e.color,e.intensity)}t.position.set(e.positionX,e.positionY,e.positionZ),e.castShadow&&(t.castShadow=!0),this.scene.add(t)}))}handleControls(){this.data.enableInteraction&&(this.controls=new THREE.OrbitControls(this.camera,this.renderer.domElement),this.controls.minDistance=this.data.minDistance,this.controls.maxDistance=this.data.maxDistance,this.controls.enablePan=!0===this.data.enablePan,this.controls.enableZoom=!0===this.data.enableZoom,this.controls.enableRotate=!0===this.data.enableRotate,!0===this.data.preventBottomView&&(this.controls.maxPolarAngle=Math.PI/2),!0===this.data.preventTopView&&(this.controls.minPolarAngle=Math.PI/2),this.controls.rotateSpeed=this.data.rotateSpeed,this.controls.zoomSpeed=this.data.zoomSpeed,this.controls.panSpeed=this.data.panSpeed)}saveModels(){window.bricksforgeData=window.bricksforgeData||{},window.bricksforgeData.models={...window.bricksforgeData.models,...this.models}||{},window.parent!==window&&(window.parent.bricksforgeData=window.bricksforgeData)}addModel(){this.loader=new THREE.GLTFLoader,this.loader.load(this.model,(e=>{const t=e.scene;t.scale.set(this.data.modelScaleX,this.data.modelScaleY,this.data.modelScaleZ),t.position.set(this.data.modelPositionX,this.data.modelPositionY,this.data.modelPositionZ),t.rotation.set(this.data.modelRotationX,this.data.modelRotationY,this.data.modelRotationZ),this.scene.add(t),this.models[this.data.id]=t,this.saveModels(),this.mixer=new THREE.AnimationMixer(t),e.animations.forEach((e=>{this.mixer.clipAction(e).play()}))}))}handleResize(){this.camera.aspect=window.innerWidth/window.innerHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(window.innerWidth,window.innerHeight)}handleAnimation(){if(this.models[this.data.id])switch(this.data.animationType){case"rotateLeft":this.models[this.data.id].rotation.y+=this.data.animationSpeed;break;case"rotateRight":this.models[this.data.id].rotation.y-=this.data.animationSpeed;break;case"rotateUp":this.models[this.data.id].rotation.x+=this.data.animationSpeed;break;case"rotateDown":this.models[this.data.id].rotation.x-=this.data.animationSpeed}}animate(){if(requestAnimationFrame(this.animate),this.mixer&&this.data.allowAnimation){const e=this.clock.getDelta();this.mixer.update(e)}this.data.enableAnimation&&this.data.animationType&&this.handleAnimation(),this.renderer.render(this.scene,this.camera)}}class BrfTour{element;instance;data={};constructor(e){Shepherd&&(this.element=e)}init(){if(this.element.dataset.brfTour&&(this.data=JSON.parse(this.element.dataset.brfTour)),!this.data.steps)return;let e=this.data.options.id,t="load"==this.data.options.trigger,r=this.data.options.triggerOnce,a=`brf_tour_${e}_completed`;t&&r&&localStorage.getItem(a)||(this.handleStyles(),this.run())}
1handleStyles(){let e=document.querySelector(".brf-tour-holder"),t=e.querySelector(".brf-tour-holder__text"),r=e.querySelector(".brf-tour-holder__title"),a=e.querySelector(".brf-tour-holder__buttons"),i=e.querySelector(".brf-tour-holder__buttons-hover"),n=e.querySelector(".brf-tour-holder__overlay");if(!e)return;let s=window.getComputedStyle(e).background,o=window.getComputedStyle(e).padding,l=window.getComputedStyle(e).border,c=window.getComputedStyle(e).borderRadius,d=window.getComputedStyle(t).color,u=window.getComputedStyle(t).fontSize,f=window.getComputedStyle(t).fontFamily,m=window.getComputedStyle(t).fontWeight,h=window.getComputedStyle(t).lineHeight,p=window.getComputedStyle(t).letterSpacing,b=window.getComputedStyle(t).textShadow,g=window.getComputedStyle(t).textAlign,y=window.getComputedStyle(t).textTransform,S=window.getComputedStyle(t).textDecoration,v=window.getComputedStyle(r).color,w=window.getComputedStyle(r).fontSize,E=window.getComputedStyle(r).fontFamily,T=window.getComputedStyle(r).fontWeight,A=window.getComputedStyle(r).lineHeight,k=window.getComputedStyle(r).letterSpacing,D=window.getComputedStyle(r).textShadow,L=window.getComputedStyle(r).textAlign,I=window.getComputedStyle(r).textTransform,F=window.getComputedStyle(r).textDecoration,C=window.getComputedStyle(a).background,x=window.getComputedStyle(a).padding,q=window.getComputedStyle(a).margin,N=window.getComputedStyle(a).border,R=window.getComputedStyle(a).borderRadius,M=window.getComputedStyle(a).color,O=window.getComputedStyle(a).fontSize,_=window.getComputedStyle(a).fontFamily,B=window.getComputedStyle(a).fontWeight,P=(window.getComputedStyle(a).lineHeight,`\n .shepherd-theme-bricksforge {\n background: ${s};\n padding: ${o};\n border: ${l};\n border-radius: ${c};\n }\n .shepherd-theme-bricksforge .shepherd-arrow:before {\n background: ${s}!important;\n }\n .shepherd-theme-bricksforge .shepherd-text {\n color: ${d};\n font-size: ${u};\n font-family: ${f};\n font-weight: ${m};\n line-height: ${h};\n letter-spacing: ${p};\n text-shadow: ${b};\n text-align: ${g};\n text-transform: ${y};\n text-decoration: ${S};\n }\n .shepherd-theme-bricksforge .shepherd-title {\n color: ${v};\n font-size: ${w};\n font-family: ${E};\n font-weight: ${T};\n line-height: ${A};\n letter-spacing: ${k};\n text-shadow: ${D};\n text-align: ${L};\n text-transform: ${I};\n text-decoration: ${F};\n }\n .shepherd-theme-bricksforge .shepherd-button {\n background: ${C};\n color: ${M};\n padding: ${x};\n margin: ${q};\n border: ${N};\n border-radius: ${R};\n font-size: ${O};\n font-family: ${_};\n font-weight: ${B};\n letter-spacing: ${window.getComputedStyle(a).letterSpacing};\n text-shadow: ${window.getComputedStyle(a).textShadow};\n text-align: ${window.getComputedStyle(a).textAlign};\n text-transform: ${window.getComputedStyle(a).textTransform};\n text-decoration: ${window.getComputedStyle(a).textDecoration};\n }\n .shepherd-theme-bricksforge .shepherd-button:hover {\n background: ${window.getComputedStyle(i).background};\n color: ${window.getComputedStyle(i).color}!important;\n font-size: ${window.getComputedStyle(i).fontSize};\n font-family: ${window.getComputedStyle(i).fontFamily};\n font-weight: ${window.getComputedStyle(i).fontWeight};\n letter-spacing: ${window.getComputedStyle(i).letterSpacing};\n text-shadow: ${window.getComputedStyle(i).textShadow};\n text-align: ${window.getComputedStyle(i).textAlign};\n text-transform: ${window.getComputedStyle(i).textTransform};\n text-decoration: ${window.getComputedStyle(i).textDecoration};\n }\n .shepherd-modal-is-visible.shepherd-modal-overlay-container {\n fill: ${window.getComputedStyle(n).fill}!important;\n }\n `);this.element.innerHTML+=`<style>${P}</style>`}run(){let e={},t=this.data.options,r=(t.scrollTo,t.scrollTo),a=(t.useModalOverlay,t.useModalOverlay);if(e.useModalOverlay=a,e.defaultStepOptions={scrollTo:r,classes:"shepherd-theme-bricksforge"},r){let t=e=>{let t=e.getBoundingClientRect().top;window.scrollTo({top:t+window.scrollY-100,behavior:"smooth"})};e.defaultStepOptions.scrollToHandler=t}switch(this.instance=new Shepherd.Tour(e),this.data.steps.forEach((e=>{let t=e.buttons.map((e=>{switch(e.action){case"next":e.action=this.instance.next;break;case"back":e.action=this.instance.back;break;case"cancel":e.action=this.instance.cancel;break;case"complete":e.action=this.instance.complete}return delete e.id,e}));document.querySelector(e.element)&&this.instance.addStep({id:e.stepId,title:e.title?e.title:"",cancelIcon:e.showCloseIcon?{enabled:!0,label:"Close"}:null,text:e.text,attachTo:{element:e.element,on:e.position},modalOverlayOpeningPadding:e.overlayPadding?e.overlayPadding:0,buttons:t})})),t.trigger?t.trigger:"load"){case"load":this.instance.start();break;case"click":let e=t.triggerSelector;if(!e)return;if(e=document.querySelector(e),!e)return;e.addEventListener("click",(()=>{this.instance.start()}))}this.instance.on("complete",(()=>{!!t.triggerOnce&&t.triggerOnce&&localStorage.setItem(`brf_tour_${t.id}_completed`,1)}))}}function brfCheckPaymentStatus(e=null){const t=new URLSearchParams(window.location.search);if(!e)if(t.has("payment_provider"))e=t.get("payment_provider");else{if(!t.has("stripe_payment"))return;e="stripe"}const r=t.get("payment_status")||t.get(`${e}_payment`);t.get("session_id");if(!r)return;const a=localStorage.getItem(`brf_${e}_payment_pending`),i=document.querySelector(".brxe-brf-pro-forms");if(a&&!i&&"success"===r){const r=JSON.parse(a);if(localStorage.setItem(`brf_${e}_payment_complete`,JSON.stringify({provider:e,formId:r.formId,message:"Payment successful! Thank you for your purchase.",redirectUrl:window.location.href.split("?")[0],timestamp:Date.now()})),window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}return}if(!i)return;let n;i.style.visibility="visible",i.style.display="block",i.classList.remove("form-loading"),"true"!==i.getAttribute("data-initialized")?(n=new BrfProForms(i),i.setAttribute("data-initialized","true")):n=BrfProForms.createSilentInstance(i),setTimeout((()=>
1{if("success"===r){const r=localStorage.getItem(`brf_${e}_payment_pending`);if(r){const a=JSON.parse(r),s=a.sessionIdentifier;if(!document.getElementById("brf-payment-overlay-styles")){const e=document.createElement("style");e.id="brf-payment-overlay-styles",e.textContent="\n .brf-payment-processing-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n }\n .brf-payment-processing-content {\n text-align: center;\n color: white;\n }\n .brf-payment-processing-content p {\n margin-top: 20px;\n font-size: 18px;\n font-weight: 500;\n }\n .brf-spinner {\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-radius: 50%;
1\n border-top: 4px solid white;\n width: 50px;\n height: 50px;\n animation: brf-spin 1s linear infinite;\n margin: 0 auto;\n }\n @keyframes brf-spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(e)}const o=document.createElement("div");o.className="brf-payment-processing-overlay",o.innerHTML='\n <div class="brf-payment-processing-content">\n <div class="brf-spinner"></div>\n <p>Processing payment...</p>\n </div>\n ',document.body.appendChild(o);let l=0;const c=60;let d=!1;const u=setInterval((()=>{if(l++,l>=c){if(clearInterval(u),d)return;d=!0;const r=document.querySelector(".brf-payment-processing-overlay");r&&r.remove();return i.querySelectorAll(".brf-form-message, .brf-validation-message, .message").forEach((e=>e.remove())),void fetch(window.location.origin+`/wp-json/bricksforge/v1/payment-status/${e}/`+s).then((e=>e.json())).then((r=>{if("completed"===r.status){const t=r.thank_you_url&&""!==r.thank_you_url.trim(),s=i.getAttribute(`data-${e}-success-message`)||i.getAttribute("data-payment-success-message")||"Payment successful! Thank you for your purchase.";if(localStorage.setItem(`brf_${e}_payment_complete`,JSON.stringify({provider:e,formId:a.formId,message:s,redirectUrl:t?r.thank_you_url:window.location.href.split("?")[0],results:r.results||{},timestamp:Date.now()})),t)return void n.navigateTo(r.thank_you_url);n.fireProValidationMessage("success",s,!1),i.scrollIntoView({behavior:"auto",block:"center"}),r.results&&r.results.success&&r.results.success.forEach((e=>{"confetti"===e.action&&n.fireConfetti()}))}else if("cancelled"===r.status)n.fireProValidationMessage("error",r.message||"Payment was cancelled. Please try again.",!1),i.scrollIntoView({behavior:"auto",block:"center"});else{const t=e.charAt(0).toUpperCase()+e.slice(1);n.fireProValidationMessage("error",`Payment verification timed out. The payment status could not be confirmed. Please check if the ${t} webhook is properly configured or verify the payment in your ${t} dashboard.`,!1),i.scrollIntoView({behavior:"auto",block:"center"})}if(window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}setTimeout((()=>{localStorage.removeItem(`brf_${e}_payment_pending`),localStorage.removeItem(`brf_${e}_payment_complete`)}),3e3)})).catch((r=>{console.error(`Error checking final ${e} status:`,r);const a=e.charAt(0).toUpperCase()+e.slice(1);if(n.fireProValidationMessage("error",`Payment verification failed. Please check if the payment was processed in your ${a} dashboard.`,!1),i.scrollIntoView({behavior:"auto",block:"center"}),window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}}))}d||fetch(window.location.origin+`/wp-json/bricksforge/v1/payment-status/${e}/`+s).then((e=>e.json())).then((r=>{if("cancelled"!==r.status||d){if("pending"===r.status&&"webhook_not_configured"===r.warning&&l>=10&&!d){d=!0,clearInterval(u);const r=document.querySelector(".brf-payment-processing-overlay");r&&r.remove();const a=e.charAt(0).toUpperCase()+e.slice(1);if(n.fireProValidationMessage("error",`${a} webhook is not configured. Payment status cannot be verified automatically. Please configure the webhook endpoint in your ${a} dashboard or check the payment manually.`,!1),i.scrollIntoView({behavior:"auto",block:"center"}),window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}setTimeout((()=>{localStorage.removeItem(`brf_${e}_payment_pending`),localStorage.removeItem(`brf_${e}_payment_complete`)}),3e3)}else if("completed"===r.status&&!d){d=!0,clearInterval(u);const s=r.thank_you_url&&""!==r.thank_you_url.trim();if(localStorage.setItem(`brf_${e}_payment_complete`,JSON.stringify({provider:e,formId:a.formId,message:"Payment successful! Thank you for your purchase.",redirectUrl:s?r.thank_you_url:window.location.href.split("?")[0],results:r.results||{},timestamp:Date.now()})),s)return void n.navigateTo(r.thank_you_url);const o=document.querySelector(".brf-payment-processing-overlay");o&&o.remove();i.querySelectorAll(".brf-form-message, .brf-validation-message, .message").forEach((e=>e.remove()));let l=!1;if(r.results&&r.results.success&&Array.isArray(r.results.success)&&r.results.success.forEach((e=>{"confetti"===e.action&&n.fireConfetti(),"redirect"===e.action&&e.redirect_url&&(l=!0,setTimeout((()=>{n.navigateTo(e.redirect_url)}),1500)),"reload"===e.action&&(l=!0,setTimeout((()=>{n.reloadPage()}),1500))})),!l){const t=i.getAttribute(`data-${e}-success-message`)||i.getAttribute("data-payment-success-message")||"Payment successful! Thank you for your purchase.";n.fireProValidationMessage("success",t,!1),i.scrollIntoView({behavior:"auto",block:"center"})}if(setTimeout((()=>{localStorage.removeItem(`brf_${e}_payment_pending`),localStorage.removeItem(`brf_${e}_payment_complete`)}),3e3),!s&&window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}}}else{d=!0,clearInterval(u);const a=document.querySelector(".brf-payment-processing-overlay");if(a&&a.remove(),n.fireProValidationMessage("error",r.message||"Payment was cancelled. Please try again.",!1),i.scrollIntoView({behavior:"auto",block:"center"}),window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}setTimeout((()=>{localStorage.removeItem(`brf_${e}_payment_pending`),localStorage.removeItem(`brf_${e}_payment_complete`)}),3e3)}}
1)).catch((t=>{console.error(`Error checking ${e} webhook status:`,t)}))}),500)}else{const r=i.getAttribute(`data-${e}-success-message`)||i.getAttribute("data-payment-success-message")||"Payment successful! Thank you for your purchase.";if(n.fireProValidationMessage("success",r,!1),i.scrollIntoView({behavior:"auto",block:"center"}),window.history&&window.history.replaceState){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}}}else if("cancelled"===r&&(n.fireProValidationMessage("error","Payment was cancelled. You can try again.",!1),i.scrollIntoView({behavior:"auto",block:"center"}),localStorage.removeItem(`brf_${e}_payment_pending`),window.history&&window.history.replaceState)){t.delete("payment_status"),t.delete("payment_provider"),t.delete(`${e}_payment`),t.delete("session_id");const r=window.location.pathname+(t.toString()?"?"+t.toString():"");window.history.replaceState({},document.title,r)}}),100)}class BrfMapField{constructor(e,t=null){this.element=e,this.formInstance=t,this.container=e.querySelector(".brf-map-container"),this.valueInput=e.closest(".pro-forms-builder-field").querySelector(".brf-map-value"),this.searchInput=e.querySelector(".brf-map-search-input"),this.provider=e.dataset.provider||"openstreetmap",this.apiKey=e.dataset.apiKey||"",this.map=null,this.marker=null,this.searchTimeout=null,this.defaultLat=parseFloat(e.dataset.defaultLat)||51.505,this.defaultLng=parseFloat(e.dataset.defaultLng)||-.09,this.defaultZoom=parseInt(e.dataset.defaultZoom)||13,this.allowDrag="true"===e.dataset.allowDrag,this.allowSearch="true"===e.dataset.allowSearch;const r=e.querySelector("template.brf-map-marker-icon-template");this.markerIconHtml=r?r.innerHTML.trim():"",this.init()}init(){const e=this.valueInput.value;if(e)try{const t=JSON.parse(e);t.lat&&(this.defaultLat=parseFloat(t.lat)),t.lng&&(this.defaultLng=parseFloat(t.lng)),t.zoom&&(this.defaultZoom=parseInt(t.zoom))}catch(e){}"google"===this.provider?this.initGoogleMaps():this.initLeaflet()}initLeaflet(){if("undefined"==typeof L)return void console.warn("Bricksforge: Leaflet library not loaded");const e=(window.BRFELEMENTS?.pluginurl||"")+"/assets/images/leaflet/",t=this.markerIconHtml?L.divIcon({html:this.markerIconHtml,className:"brf-map-marker-divicon",iconSize:null}):L.icon({iconUrl:e+"marker-icon.png",iconRetinaUrl:e+"marker-icon-2x.png",shadowUrl:e+"marker-shadow.png",iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],tooltipAnchor:[16,-28],shadowSize:[41,41]});this.map=L.map(this.container).setView([this.defaultLat,this.defaultLng],this.defaultZoom),L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(this.map),this.marker=L.marker([this.defaultLat,this.defaultLng],{draggable:this.allowDrag,icon:t}).addTo(this.map),this.allowDrag&&this.marker.on("dragend",(e=>{const t=e.target.getLatLng();this.reverseGeocode(t.lat,t.lng,"nominatim")})),this.map.on("click",(e=>{this.marker.setLatLng(e.latlng),this.reverseGeocode(e.latlng.lat,e.latlng.lng,"nominatim")})),this.allowSearch&&this.searchInput&&this.initNominatimSearch(),this.updateValue(this.defaultLat,this.defaultLng,"",this.defaultZoom),setTimeout((()=>{this.map.invalidateSize()}),100)}initNominatimSearch(){const e=this.searchInput.parentElement;let t=e.querySelector(".brf-map-search-results");t||(t=document.createElement("div"),t.className="brf-map-search-results",e.appendChild(t)),this.searchInput.addEventListener("input",(e=>{clearTimeout(this.searchTimeout);const r=e.target.value.trim();if(r.length<3)return t.innerHTML="",void(t.style.display="none");this.searchTimeout=setTimeout((()=>{this.searchNominatim(r,t)}),500)})),document.addEventListener("click",(r=>{e.contains(r.target)||(t.style.display="none")}))}async searchNominatim(e,t){try{const r=await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(e)}&limit=5&addressdetails=1`,{headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);const a=await r.text();let i;try{i=JSON.parse(a)}catch(e){return console.warn("Bricksforge: Nominatim returned non-JSON response"),t.innerHTML='<div class="brf-map-search-no-results">Search temporarily unavailable</div>',void(t.style.display="block")}if(t.innerHTML="",!Array.isArray(i)||0===i.length)return t.innerHTML='<div class="brf-map-search-no-results">No results found</div>',void(t.style.display="block");
1i.forEach((e=>{const r=document.createElement("div");r.className="brf-map-search-result-item",r.textContent=e.display_name,r.addEventListener("click",(()=>{const r=parseFloat(e.lat),a=parseFloat(e.lon);this.map.setView([r,a],this.defaultZoom),this.marker.setLatLng([r,a]),this.updateValue(r,a,e.display_name,this.map.getZoom(),!0),this.searchInput.value=e.display_name,t.style.display="none"})),t.appendChild(r)})),t.style.display="block"}catch(e){console.error("Bricksforge: Nominatim search error",e),t.innerHTML='<div class="brf-map-search-no-results">Search error occurred</div>',t.style.display="block"}}initGoogleMaps(){if(window.google&&window.google.maps)this.setupGoogleMaps();else{if(!this.apiKey)return console.warn("Bricksforge: Google Maps API key not configured"),void(this.container.innerHTML='<p style="padding: 20px; text-align: center;">Google Maps API key not configured</p>');if(!window.brfGoogleMapsLoading){window.brfGoogleMapsLoading=!0,window.brfGoogleMapsCallbacks=[];const e=document.createElement("script");e.src=`https://maps.googleapis.com/maps/api/js?key=${this.apiKey}&libraries=places,marker&loading=async&callback=brfGoogleMapsReady`,e.async=!0,document.head.appendChild(e),window.brfGoogleMapsReady=()=>{window.brfGoogleMapsLoading=!1,window.brfGoogleMapsCallbacks.forEach((e=>e())),window.brfGoogleMapsCallbacks=[]}}window.brfGoogleMapsCallbacks.push((()=>this.setupGoogleMaps()))}}setupGoogleMaps(){const e={lat:this.defaultLat,lng:this.defaultLng};if(this.map=new google.maps.Map(this.container,{center:e,zoom:this.defaultZoom,mapId:"BRICKSFORGE_MAP"}),google.maps.marker&&google.maps.marker.AdvancedMarkerElement){const t={position:e,map:this.map,gmpDraggable:this.allowDrag};if(this.markerIconHtml){const e=document.createElement("div");e.innerHTML=this.markerIconHtml,t.content=e.firstElementChild||e}this.marker=new google.maps.marker.AdvancedMarkerElement(t),this.allowDrag&&this.marker.addListener("dragend",(()=>{const e=this.marker.position;this.reverseGeocode(e.lat,e.lng,"google")}))}else this.marker=new google.maps.Marker({position:e,map:this.map,draggable:this.allowDrag}),this.allowDrag&&this.marker.addListener("dragend",(()=>{const e=this.marker.getPosition();this.reverseGeocode(e.lat(),e.lng(),"google")}));this.map.addListener("click",(e=>{void 0!==this.marker.position?this.marker.position=e.latLng:this.marker.setPosition(e.latLng),this.reverseGeocode(e.latLng.lat(),e.latLng.lng(),"google")})),this.allowSearch&&this.searchInput&&this.initGooglePlacesSearch(),this.updateValue(this.defaultLat,this.defaultLng,"",this.defaultZoom)}initGooglePlacesSearch(){this.initLegacyAutocomplete()}initPlaceAutocompleteElement(){this.searchInput.style.display="none";const e=new google.maps.places.PlaceAutocompleteElement({locationBias:this.map.getBounds()});e.classList.add("brf-map-search-input"),this.searchInput.parentNode.insertBefore(e,this.searchInput.nextSibling),this.map.addListener("bounds_changed",(()=>{e.locationBias=this.map.getBounds()})),e.addEventListener("gmp-placeselect",(async e=>{const t=e.place;await t.fetchFields({fields:["displayName","formattedAddress","location","viewport"]});const r=t.location;if(!r)return;const a=r.lat(),i=r.lng(),n={lat:a,lng:i};this.map.setCenter(r),void 0!==this.marker.position?this.marker.position=n:this.marker.setPosition(r),t.viewport?this.map.fitBounds(t.viewport):this.map.setZoom(17),this.updateValue(a,i,t.formattedAddress||t.displayName||"",this.map.getZoom(),!0),this.searchInput&&(this.searchInput.value=t.formattedAddress||t.displayName||"")}))}initLegacyAutocomplete(){const e=new google.maps.places.Autocomplete(this.searchInput);e.bindTo("bounds",this.map),e.addListener("place_changed",(()=>{const t=e.getPlace();if(!t.geometry||!t.geometry.location)return;const r=t.geometry.location.lat(),a=t.geometry.location.lng(),i={lat:r,lng:a};this.map.setCenter(t.geometry.location),void 0!==this.marker.position?this.marker.position=i:this.marker.setPosition(t.geometry.location),t.geometry.viewport?this.map.fitBounds(t.geometry.viewport):this.map.setZoom(17),this.updateValue(r,a,t.formatted_address||"",this.map.getZoom(),!0)}))}async reverseGeocode(e,t,r){let a="";try{if("nominatim"===r){const r=await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e}&lon=${t}`,{headers:{Accept:"application/json"}});if(r.ok){const e=await r.text();try{a=JSON.parse(e).display_name||""}catch(e){}}}else if("google"===r&&window.google){const r=new google.maps.Geocoder,i=await r.geocode({location:{lat:e,lng:t}});i.results&&i.results[0]&&(a=i.results[0].formatted_address)}}catch(e){console.error("Bricksforge: Reverse geocoding error",e)}const i=(this.provider,this.map.getZoom());
1this.updateValue(e,t,a,i,!0),this.searchInput&&a&&(this.searchInput.value=a)}updateValue(e,t,r,a,i=!1){const n=JSON.stringify({lat:e,lng:t,address:r||"",zoom:a||this.defaultZoom});this.valueInput.value=n,i&&(this.valueInput.dataset.userSelected="true"),this.valueInput.dispatchEvent(new Event("change",{bubbles:!0})),this.valueInput.dispatchEvent(new Event("input",{bubbles:!0}))}refresh(){"openstreetmap"===this.provider&&this.map?setTimeout((()=>{this.map.invalidateSize()}),100):"google"===this.provider&&this.map&&google.maps.event.trigger(this.map,"resize")}setLocation(e,t,r="",a=null){const i=a||this.defaultZoom;if("openstreetmap"===this.provider&&this.map)this.map.setView([e,t],i),this.marker.setLatLng([e,t]);else if("google"===this.provider&&this.map){const r={lat:e,lng:t};this.map.setCenter(r),this.map.setZoom(i),void 0!==this.marker.position&&"function"!=typeof this.marker.setPosition?this.marker.position=r:this.marker.setPosition(r)}this.updateValue(e,t,r,i)}}function brfCheckStripePaymentStatus(){brfCheckPaymentStatus("stripe")}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(function(){brfCheckPaymentStatus()})):brfCheckPaymentStatus()
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.