import{$4,$$4,$id4,debounce,formatMoney}from"@theme/utilities";import{getterAdd,getterGet,getterRunFn,btnTooltip,DrawerComponent,VariantChangeBase}from"@theme/global";import{ThemeEvents}from"@theme/events";const{dialogClose,dialogOpen,cartCount,cartUpdate,currencyUpdate,cartReload,progressBarChange}=ThemeEvents;var $wishlist_list=$id4("hdt_wishlist_list"),$compare_list=$id4("hdt_compare_list"),nameCachedWishlist="theme4:wishlist:id",nameCachedCompare="theme4:compare:id";if($wishlist_list)var arr_wishlist_list=$wishlist_list.textContent?$wishlist_list.textContent.split(" "):[];else var arr_wishlist_list=localStorage.getItem(nameCachedWishlist)?localStorage.getItem(nameCachedWishlist).split(","):[];if($compare_list)var arr_compare_list=$compare_list.textContent?$compare_list.textContent.split(" "):[];else var arr_compare_list=localStorage.getItem(nameCachedCompare)?localStorage.getItem(nameCachedCompare).split(","):[];var linkWishlistApp="/apps/ecomrise/wishlist",linkCompareApp="/apps/ecomrise/compare",actionAfterWishlistAdded=themeHDN.extras.AddedWishlistRemove?"remove":"added",actionAfterCompareAdded=themeHDN.extras.AddedCompareRemove?"remove":"added",limitWishlist=$wishlist_list?100:50,limitCompare=5,conver_to_link_fn=function(prefix=this.textFn,array=this.array){const x=themeHDN.routes.search_url+`/?view=${prefix}`,y=x+"&type=product&options[unavailable_products]=last&q=";return array.length?y+encodeURI(`id:${array.join(" OR id:")}`):x};arr_wishlist_list.length>limitWishlist&&(arr_wishlist_list.splice(limitWishlist-1,arr_wishlist_list.length-1),localStorage.setItem(nameCachedWishlist,arr_wishlist_list.toString())),window.isPageWishlist&&(arr_wishlist_list.length&&!window.isWishlistPerformed?window.location.href=conver_to_link_fn("wishlist",arr_wishlist_list):window.history.replaceState({},document.title,conver_to_link_fn("wishlist",[])),themeHDN.wisHref=conver_to_link_fn("wishlist",arr_wishlist_list)),arr_compare_list.length>limitCompare&&(arr_compare_list.splice(limitCompare-1,arr_compare_list.length-1),localStorage.setItem(nameCachedCompare,arr_compare_list.toString())),window.isPageCompare&&(arr_compare_list.length&&!window.isComparePerformed?window.location.href=conver_to_link_fn("compare",arr_compare_list):window.history.replaceState({},document.title,conver_to_link_fn("compare",[])));var _wishlist_id,_wishlist_handle,_update_wis_text,update_wis_text_fn,_update_wis_btns,update_wis_btns_fn,_click_wis,click_wis_fn,_add_wis,add_wis_fn,_remove_wis,remove_wis_fn,_action_after_remove_add,action_after_remove_add_fn,_show_popup_compare,show_popup_compare_fn,_conver_to_link;class Wishlist extends btnTooltip{constructor(){super(),getterAdd(_wishlist_id,this,this.dataset.id),getterAdd(_wishlist_handle,this,this.dataset.handle),getterAdd(_update_wis_text,this),getterAdd(_update_wis_btns,this),getterAdd(_click_wis,this),getterAdd(_add_wis,this),getterAdd(_remove_wis,this),getterAdd(_action_after_remove_add,this),getterAdd(_show_popup_compare,this),getterAdd(_conver_to_link,this),this.tabIndex=0,this.addEventListener("click",event=>getterRunFn(_click_wis,this,click_wis_fn).call(this,event)),this.addEventListener("keydown",event=>{event.key=="Enter"&&getterRunFn(_click_wis,this,click_wis_fn).call(this,event)})}static get observedAttributes(){return["action"]}get isFnWishlist(){return!0}get textFn(){return"wishlist"}get isPageWishlistorCompare(){return this.isFnWishlist?window.isPageWishlist:window.isPageCompare}get limit(){return this.isFnWishlist?limitWishlist:limitCompare}get nameCached(){return this.isFnWishlist?nameCachedWishlist:nameCachedCompare}get array(){return this.isFnWishlist?arr_wishlist_list:arr_compare_list}get actionAfterAdded(){return this.isFnWishlist?actionAfterWishlistAdded:actionAfterCompareAdded}get action(){return this.getAttribute("action")}attributeChangedCallback(name,oldValue,newValue){oldValue===newValue||oldValue===null&&newValue==="add"||(getterRunFn(_update_wis_text,this,update_wis_text_fn).call(this,newValue),super.attributeChangedCallback(name,oldValue,newValue))}connectedCallback(){if(super.connectedCallback(),this.array.indexOf(getterGet(_wishlist_id,this))>-1){if(this.hasAttribute("remove-on-page"))return;this.setAttribute("action",this.actionAfterAdded)}}}_wishlist_id=new WeakMap,_wishlist_handle=new WeakMap,_update_wis_text=new WeakSet,_update_wis_btns=new WeakSet,_click_wis=new WeakSet,_add_wis=new WeakSet,_remove_wis=new WeakSet,_action_after_remove_add=new WeakSet,_conver_to_link=new WeakSet,_show_popup_compare=new WeakSet,update_wis_text_fn=function(value){if(this.hasAttribute("remove-on-page"))return;const text=themeHDN.extras[`text_${this.isFnWishlist?"wis":"cp"}_${value}`],icon=themeHDN.extras[`icon_${this.isFnWishlist?"wis":"cp"}_${value}`];icon&&this.firstElementChild.replaceWith(document.createRange().createContextualFragment(icon)),text&&(this.lastElementChild.textContent=text,this.setAttribute("data-txt-tt",text))},update_wis_btns_fn=function(_action){$$4(`hdt-${this.textFn}[data-id="${getterGet(_wishlist_id,this)}"]`).forEach(btn=>{btn.setAttribute("action",_action)}),document.dispatchEvent(new CustomEvent(`theme4:${this.textFn}:update`,{bubbles:!0,detail:"the4"})),window.isPageWishlist&&(themeHDN.wisHref=conver_to_link_fn("wishlist",arr_wishlist_list))},click_wis_fn=function(e){this.action=="add"?getterRunFn(_add_wis,this,add_wis_fn).call(this):this.action==="added"?!this.isFnWishlist&&themeHDN.extras.enableComparePopup?getterRunFn(_show_popup_compare,this,show_popup_compare_fn).call(this):window.location.href=getterRunFn(_conver_to_link,this,conver_to_link_fn).call(this):getterRunFn(_remove_wis,this,remove_wis_fn).call(this,e)},add_wis_fn=function(e){if($wishlist_list&&this.isFnWishlist||$compare_list&&!this.isFnWishlist)this.setAttribute("aria-busy",!0),fetch(this.isFnWishlist?linkWishlistApp:linkCompareApp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:getterGet(_wishlist_id,this),product_handle:getterGet(_wishlist_handle,this),action:"add"})}).then(response=>response.json()).then(data=>{if(data.status!="success"){console.error(data.message||"Unknow error");return}this.isFnWishlist&&(arr_wishlist_list=JSON.parse(data.response.metafield.value).ecomrise_ids,Array.isArray(arr_wishlist_list)||(arr_wishlist_list=arr_wishlist_list.split(","))),this.isFnWishlist||(arr_compare_list=JSON.parse(data.response.metafield.value).ecomrise_ids,Array.isArray(arr_compare_list)||(arr_compare_list=arr_compare_list.split(",")),getterRunFn(_show_popup_compare,this,show_popup_compare_fn).call(this)),getterRunFn(_action_after_remove_add,this,action_after_remove_add_fn).call(this,this.actionAfterAdded)}).catch(function(error){console.log("Error: "+error)}).finally(()=>{this.setAttribute("aria-busy",!1)});else{if(this.array.unshift(getterGet(_wishlist_id,this)),this.array.length>this.limit){let arraySplice=this.array.splice(this.limit,1);$$4(`hdt-${this.textFn}[data-id="${arraySplice[0]}"]`).forEach(btn=>{btn.setAttribute("action","add")})}this.isFnWishlist||getterRunFn(_show_popup_compare,this,show_popup_compare_fn).call(this),getterRunFn(_action_after_remove_add,this,action_after_remove_add_fn).call(this,this.actionAfterAdded),localStorage.setItem(this.nameCached,this.array.toString())}},remove_wis_fn=function(e){e.preventDefault(),e.stopPropagation(),$wishlist_list&&this.isFnWishlist||$compare_list&&!this.isFnWishlist?(this.setAttribute("aria-busy",!0),fetch(this.isFnWishlist?linkWishlistApp:linkCompareApp,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:getterGet(_wishlist_id,this),product_handle:getterGet(_wishlist_handle,this),action:"add",_method:"DELETE"})}).then(response=>response.json()).then(data=>{if(data.status!="success"){console.error(data.message||"Unknow error");return}arr_wishlist_list=JSON.parse(data.response.metafield.value).ecomrise_ids,Array.isArray(arr_wishlist_list)||(arr_wishlist_list=arr_wishlist_list.split(",")),getterRunFn(_action_after_remove_add,this,action_after_remove_add_fn).call(this,"add")}).catch(function(error){console.log("Error: "+error)}).finally(()=>{this.setAttribute("aria-busy",!1)})):(this.array.splice(this.array.indexOf(getterGet(_wishlist_id,this)),1),localStorage.setItem(this.nameCached,this.array.toString()),getterRunFn(_action_after_remove_add,this,action_after_remove_add_fn).call(this,"add"))},action_after_remove_add_fn=function(action){this.getAttribute("action")=="remove"&&this.hasAttribute("remove-on-page")?(this.isFnWishlist?(this.setAttribute("aria-busy",!0),this.isPageWishlistorCompare&&(window.location.href=getterRunFn(_conver_to_link,this,conver_to_link_fn).call(this))):$$4(`.hdt-compare-item-${getterGet(_wishlist_id,this)}`).forEach(item=>{item.remove()}),getterRunFn(_update_wis_btns,this,update_wis_btns_fn).call(this,action),this.array.length==0&&($id4("drawerCompare")?.closest("hdt-drawer")?.close(),this.isPageWishlistorCompare&&(window.location.href=getterRunFn(_conver_to_link,this,conver_to_link_fn).call(this)))):(getterRunFn(_update_wis_btns,this,update_wis_btns_fn).call(this,action),this.isPageWishlistorCompare&&(window.location.href=getterRunFn(_conver_to_link,this,conver_to_link_fn).call(this)))},show_popup_compare_fn=function(event){!themeHDN.extras.enableComparePopup||this.isPageWishlistorCompare||($id4("drawerCompare")?.closest("hdt-drawer")?.open(),fetch(conver_to_link_fn("compare",arr_compare_list)+"§ion_id=compare-offcanvas").then(response=>response.text()).then(text=>{const html=document.createElement("div");html.innerHTML=text;const prds=html.querySelector("offcanvas-compare");prds&&prds.innerHTML.trim().length&&($4("offcanvas-compare").innerHTML=prds.innerHTML)}).catch(e=>{console.error(e)}))};var _clear_all,clear_all_fn;class ClearAll extends HTMLElement{constructor(){super(),getterAdd(_clear_all,this),this.tabIndex=0,this.addEventListener("click",getterRunFn(_clear_all,this,clear_all_fn)),this.addEventListener("keydown",event=>{event.key=="Enter"&&getterRunFn(_clear_all,this,clear_all_fn).call(this)})}get ofFn(){return this.getAttribute("of-fn")}get nameCached(){return this.ofFn=="compare"?nameCachedCompare:nameCachedWishlist}set array(value){this.ofFn=="compare"?arr_compare_list=value:arr_wishlist_list=value}}_clear_all=new WeakSet,clear_all_fn=function(){localStorage.removeItem(this.nameCached),$$4(`hdt-${this.ofFn}[action="added"]`).forEach(btn=>{btn.setAttribute("action","add")}),document.dispatchEvent(new CustomEvent(`theme4:${this.ofFn}:update`,{bubbles:!0,detail:"the4"})),this.array=[],$id4("drawerCompare")?.closest("hdt-drawer")?.close(),$4("#drawerCompare offcanvas-compare")&&($4("#drawerCompare offcanvas-compare").innerHTML="")},customElements.define("hdt-clear-all",ClearAll);class WishlistCount extends HTMLElement{constructor(){super(),this.textContent=this.array.length,document.addEventListener(`theme4:${this.prefix}:update`,e=>{this.textContent=this.array.length})}get isFnWishlist(){return!0}get array(){return this.isFnWishlist?arr_wishlist_list:arr_compare_list}get prefix(){return this.isFnWishlist?"wishlist":"compare"}}class WishlistLink extends HTMLElement{constructor(){super(),$4("a",this).href=conver_to_link_fn(this.prefix,this.array),document.addEventListener(`theme4:${this.prefix}:update`,e=>{$4("a",this).href=conver_to_link_fn(this.prefix,this.array)})}get isFnWishlist(){return!0}get array(){return this.isFnWishlist?arr_wishlist_list:arr_compare_list}get prefix(){return this.isFnWishlist?"wishlist":"compare"}}customElements.define("hdt-wishlist",Wishlist),customElements.define("hdt-wishlist-count",WishlistCount),customElements.define("hdt-wishlist-a",WishlistLink);class Compare extends Wishlist{get isFnWishlist(){return!1}get textFn(){return"compare"}}class CompareCount extends WishlistCount{get isFnWishlist(){return!1}}class CompareLink extends WishlistLink{get isFnWishlist(){return!1}}customElements.define("hdt-compare",Compare),customElements.define("hdt-compare-count",CompareCount),customElements.define("hdt-compare-a",CompareLink);function handleAccordionClick(){let accordion=this.parentElement;if(accordion.classList.toggle("open"),window.innerWidth<768){let content=accordion.querySelector(".hdt-collapse-content");accordion.classList.contains("open")?content.style.height=content.scrollHeight+"px":content.style.height="0"}}function updateMaxHeight(){window.innerWidth>=768&&document.querySelectorAll(".hdt-footer-section .hdt-collapse-content").forEach(function(content){content.style.height=""})}document.querySelectorAll(".hdt-footer-section .hdt-footer-heading").forEach(function(element){element.addEventListener("click",handleAccordionClick)}),window.addEventListener("resize",function(){window.innerWidth<768?document.querySelectorAll(".hdt-footer-section .hdt-footer-heading").forEach(function(element){element.removeEventListener("click",handleAccordionClick),element.addEventListener("click",handleAccordionClick)}):(document.querySelectorAll(".hdt-footer-section .hdt-footer-heading").forEach(function(element){element.removeEventListener("click",handleAccordionClick)}),updateMaxHeight())});class BackToTop extends HTMLElement{constructor(){super(),this.config=JSON.parse(this.getAttribute("config")),!(window.innerWidth<768&&this.config.hiddenMobile)&&(this.debounce_timer=0,this.debounce_timer2=0,this.circlechart=this.querySelector(".hdt-circle-css"),this.addEventListener("click",this.goTop.bind(this)),window.addEventListener("scroll",this.backToTop.bind(this)))}goTop(){document.body.scrollTop=0,document.documentElement.scrollTop=0}backToTop(){let self2=this;this.debounce_timer&&clearTimeout(this.debounce_timer),this.debounce_timer=setTimeout(function(){window.scrollY>self2.config.scrollTop?self2.classList.add("is--show"):self2.classList.remove("is--show")},40),this.circlechart&&(this.debounce_timer2&&clearTimeout(this.debounce_timer2),this.debounce_timer2=setTimeout(function(){let scrollTop2=window.scrollY,docHeight=document.body.offsetHeight,winHeight=window.innerHeight,scrollPercent=scrollTop2/(docHeight-winHeight),degrees=scrollPercent*360;self2.circlechart.style.setProperty("--cricle-degrees",degrees+"deg")},6))}}customElements.define("back-to-top",BackToTop);const contactForm=$$4('form[action^="/contact"]');contactForm.forEach(function(form){form.addEventListener("submit",function(event){sessionStorage.setItem("the4:recentform",this.getAttribute("id"))})});var recentform=sessionStorage.getItem("the4:recentform")||"";if(location.href.indexOf("contact_posted=true")>0&&recentform!==""){if(document.dispatchEvent(new CustomEvent("the4:recentform",{detail:{recentform},bubbles:!0,cancelable:!0})),$id4(recentform)?.classList.add("on-live"),recentform.indexOf("ContactFormAsk")>=0&&$id4(recentform).length>0){let modal_id=document.getElementById(recentform).getAttribute("data-modal");document.getElementById(modal_id).closest("hdt-modal").open(),sessionStorage.removeItem("the4:recentform")}$4(".form-status-mirror-"+recentform)&&($4(".form-status-mirror-"+recentform).style.cssText="display: block;")}else if(location.href.indexOf("customer_posted=true")>0&&recentform!=="")document.addEventListener("the4:recentform",event=>{let modal_id=document.getElementById(event.detail.recentform).getAttribute("data-id");document.getElementById(modal_id).closest("hdt-modal").open()}),document.dispatchEvent(new CustomEvent("the4:recentform",{detail:{recentform},bubbles:!0,cancelable:!0})),$id4(recentform)?.classList.add("on-live");else if(location.href.indexOf("contact_posted=true")>0&&location.href.indexOf("#")>0){var recentform=location.href.split("#")[1];$id4(recentform).length>0&&(sessionStorage.setItem("the4:recentform",recentform),$id4(recentform).classList.add("on-live"),$4(".form-status-mirror-"+recentform)&&($4(".form-status-mirror-"+recentform).style.cssText="display: block;"))}class numberRandom extends HTMLElement{constructor(){super();let config=JSON.parse(this.getAttribute("config"));this.min=config.min,this.max=config.max,this.interval=config.interval,this.number=Math.floor(Math.random()*(this.max-this.min+1))+this.min,this.ofset=["1","2","4","3","6","10","-1","-3","-2","-4","-6"],this.prioritize=["10","20","15"],this.h="",this.e="",this.M="",this.liveViewInt(),setInterval(this.liveViewInt.bind(this),this.interval)}liveViewInt(){if(this.h=Math.floor(Math.random()*this.ofset.length),this.e=this.ofset[this.h],this.number=parseInt(this.number)+parseInt(this.e),this.min>=this.number){this.M=Math.floor(Math.random()*this.prioritize.length);var a=this.prioritize[this.M];this.number+=a}(this.numberthis.max)&&(this.number=Math.floor(Math.random()*(this.max-this.min+1))+this.min),this.innerHTML=parseInt(this.number)}}customElements.define("number-random",numberRandom);class flashSold extends VariantChangeBase{constructor(){super();var self2=this;this.time=this.getAttribute("time"),this.config=JSON.parse(this.getAttribute("flash-sold")),this.mins=this.config.mins,this.maxs=this.config.maxs,this.mint=this.config.mint,this.maxt=this.config.maxt,this.dataID=this.config.id,this.getS=sessionStorage.getItem("soldS"+this.dataID)||this.getRandomInt(this.mins,this.maxs),this.getT=sessionStorage.getItem("soldT"+this.dataID)||this.getRandomInt(this.mint,this.maxt),this.numS=parseInt(this.getS),this.numT=parseInt(this.getT),this.intervalTime=parseInt(this.config.time),this.$sold=this.querySelector("[data-sold]"),this.$hour=this.querySelector("[data-hour]"),this.limitMinMax(),this.updateSold(this.numS,this.numT),setInterval(function(){this.numS=this.numS+self2.getRandomInt(1,4),this.numT=this.numT+(Math.random()*(.8-.1)+.1).toFixed(1)*1,self2.limitMinMax(),self2.updateSold(self2.numS,self2.numT)},this.intervalTime)}getRandomInt(min,max){return Math.floor(Math.random()*(max-min+1))+min}updateSold(num1,num2){this.$sold.innerHTML=num1,this.$hour.innerHTML=Math.floor(this.numT),sessionStorage.setItem("soldS"+this.dataID,num1),sessionStorage.setItem("soldT"+this.dataID,num2)}limitMinMax(){this.numS>this.maxs&&(this.numS=self.getRandomInt(this.mins,this.maxs)),this.numT>this.maxt&&(this.numT=self.getRandomInt(this.mins,this.maxt))}#preVariantId;onVariantChanged(event){const variant=event.detail.variant;variant&&this.#preVariantId!=variant.id&&(variant.available?this.closest(".hdt-product-info__item").style.display="block":this.closest(".hdt-product-info__item").style.display="none")}}customElements.define("flash-sold",flashSold);class filterIsotope extends HTMLElement{constructor(){super(),this.btns=this.querySelectorAll("button"),this.id=this.id,this.btns&&this.handleButtonClick()}handleButtonClick(){this.btns.forEach(btn=>{btn.addEventListener("click",()=>{this.querySelector("button.active").classList.remove("active"),btn.classList.add("active");let selectedFilter=btn.getAttribute("data-filter"),itemsToHide=$$4(`#${this.id} .hdt-brand-item:not(${selectedFilter})`),itemsToShow=$$4(`#${this.id} ${selectedFilter}`);selectedFilter=="._filter-show-all"&&(itemsToHide=[],itemsToShow=$$4(`#${this.id} .hdt-brand-item`)),itemsToShow.forEach(el=>{el.classList.remove("animate-filter-hide","hdt-hidden"),el.classList.add("animate-filter-show")}),itemsToHide.forEach(el=>{el.classList.add("animate-filter-hide","hdt-hidden"),el.classList.remove("animate-filter-show")})})})}}customElements.define("hdt-brands",filterIsotope);class countryFilter extends HTMLElement{constructor(){super(),this.search=$4("[name=country_filter]",this),this.reset=$4(".hdt-country_filter__reset",this),this.search&&this.search.addEventListener("input",debounce(event=>{this.filterCountries()},200).bind(this)),this.search.addEventListener("keydown",this.onSearchKeyDown.bind(this))}filterCountries(){const searchValue=this.search.value.toLowerCase(),allCountries=this.closest("hdt-popover").querySelectorAll("hdt-richlist button");let visibleCountries=allCountries.length;allCountries.forEach(item=>{item.getAttribute("data-name").toLowerCase().indexOf(searchValue)>-1?(item.classList.remove("hdt-d-none"),visibleCountries++):(item.classList.add("hdt-d-none"),visibleCountries--)}),window.innerWidth>768&&this.closest("hdt-popover").updatePos(),this.closest("hdt-popover").querySelector(".hdt-current-scrollbar").scrollTop=0}onSearchKeyDown(event){event.code.toUpperCase()==="ENTER"&&event.preventDefault()}}customElements.define("country-filter",countryFilter);class ProductRecommendations extends HTMLElement{constructor(){super()}connectedCallback(){if(this.hasAttribute("no-observe")){this.fetchAction();return}const handleIntersection=(entries,observer)=>{entries[0].isIntersecting&&(observer.unobserve(this),this.fetchAction())};new IntersectionObserver(handleIntersection.bind(this),{rootMargin:"0px 0px 400px 0px"}).observe(this)}fetchAction(){fetch(this.dataset.url).then(response=>response.text()).then(text=>{const html=document.createElement("div");html.innerHTML=text;const recommendations=html.querySelector("product-recommendations");recommendations&&recommendations.innerHTML.trim().length&&(this.innerHTML=recommendations.innerHTML),document.dispatchEvent(new CustomEvent("currency:update"))}).catch(e=>{console.error(e)})}}customElements.define("product-recommendations",ProductRecommendations);class ProductRecently extends HTMLElement{constructor(){super()}connectedCallback(){const handleIntersection=(entries,observer)=>{if(!entries[0].isIntersecting)return;observer.unobserve(this);let handleProducts=localStorage.getItem("theme4:recently:id"),prdId=this.dataset.id;if(handleProducts!==null){let products=handleProducts.split(",");if(prdId==products[0]&&products.length==1){this.closest(".section").style.display="none";return}let url=this.dataset.url.replace("q=","q=id:"+products.join("%20OR%20id:"));fetch(url).then(response=>response.text()).then(text=>{const html=document.createElement("div");html.innerHTML=text.replace("hdt-slider-wait","hdt-slider");const recently=html.querySelector("product-recently");recently&&recently.innerHTML.trim().length&&(this.innerHTML=recently.innerHTML),document.dispatchEvent(new CustomEvent("currency:update"))}).catch(e=>{console.error(e)})}let arrayProducts=handleProducts!==null?handleProducts.split(","):new Array;if(!arrayProducts.includes(prdId+"")){let prepend=function(value,array){var newArray=array.slice();return newArray.unshift(value),newArray};arrayProducts.length>=10&&arrayProducts.pop(),arrayProducts=prepend(prdId,arrayProducts),arrayProducts=arrayProducts.toString(),localStorage.setItem("theme4:recently:id",arrayProducts)}};new IntersectionObserver(handleIntersection.bind(this),{rootMargin:"0px 0px 400px 0px"}).observe(this)}}customElements.define("product-recently",ProductRecently);const modalAsk=document.getElementById("modal-contactFormAsk");modalAsk.addEventListener("dialog:opening",function(event){let askBtn=modalAsk.closest("hdt-modal").dialog.btnOpening,product=askBtn.getAttribute("data-product"),product_info=askBtn.parentElement.querySelector(".hdt-pr-popup__ask-product");if(product_info){const modalHeader=modalAsk.querySelector(".hdt-dialog-modal__header");if(modalHeader&&product_info){const oldProductInfo=modalHeader.querySelector(".hdt-pr-popup__ask-product");oldProductInfo&&oldProductInfo.remove(),modalHeader.prepend(product_info.cloneNode(!0))}}let productAsk=modalAsk.querySelector('[name="contact[product]"]');if(productAsk){let currentValue=productAsk.value||"",newValue=product||"";if(currentValue!==newValue){let formMessage=modalAsk.querySelector(".hdt-form-message");formMessage&&formMessage.remove()}(currentValue!==newValue||currentValue==="")&&(productAsk.value=newValue)}});class PredictiveSearch extends DrawerComponent{constructor(){if(super(),!this.hasAttribute("enabled"))return;this.cachedResults={},this.predictiveSearchResults=$4("[data-results-search]",this),this.select=$4("[data-cat-search]>select",this),this.input=$4('input[type="search"]',this),this.sectionIdResults=this.getAttribute("data-section-id-results")||"hdt_predictive-search",this.allPredictiveSearchInstances=$$4("predictive-search"),this.skeleton=$4("[data-skeleton-search]",this),this.noResults=$4(".hdt-cart-no-results",this),this.hideWrapper=$4(".hdt-cart-hide-has-results",this),this.showWrapper=$4(".hdt-cart-show-has-results",this),this.btn_viewall=$4(".hdt-view_all",this),this.href=this.btn_viewall?.getAttribute("href"),this.btn_viewall_replace_text=$4("[data-replace-text]",this),this.isOpen=!1,this.abortController2=new AbortController,this.searchTerm="",this.input&&this.input.addEventListener("input",debounce(event=>{this.onChange(event)},300).bind(this)),this.select&&this.select.addEventListener("change",debounce(event=>{this.onChange(event)},300).bind(this));const formData=new FormData(this.input.form);this.params="";for(const[key,value]of formData){if(key==="q")break;this.params+=`${key}=${value}&`}this.setupEventListeners()}setupEventListeners(){this.input.form.addEventListener("submit",this.onFormSubmit.bind(this)),this.input.addEventListener("focus",this.onFocus.bind(this)),this.addEventListener("focusout",this.onFocusOut.bind(this)),this.addEventListener("keyup",this.onKeyup.bind(this))}getQuery(){var currentValue=this.input.value.trim();if(this.select){this.selectVal=this.select.value||"*";var valSelected=this.selectVal.trim();valSelected!="*"&&(currentValue!==""?currentValue=`product_type:${valSelected} AND ${currentValue}`:currentValue=`product_type:${valSelected}`)}return currentValue}onChange(){const newSearchTerm=this.getQuery();if(!this.searchTerm||newSearchTerm.startsWith(this.searchTerm),this.updateSearchForTerm(this.searchTerm,newSearchTerm),this.searchTerm=newSearchTerm,this.btn_viewall?.setAttribute("href",this.href.replace(/\/search\?q=.*/g,"/search?q="+this.searchTerm)),this.btn_viewall_replace_text&&(this.btn_viewall_replace_text.innerText=themeHDN.extras.search.view_all+` ${this.searchTerm}`),!this.searchTerm.length){this.close(!0);return}this.getSearchResults(this.searchTerm)}onFormSubmit(event){(!this.getQuery().length||this.querySelector('[aria-selected="true"] a'))&&event.preventDefault()}onFocus(){const currentSearchTerm=this.getQuery();currentSearchTerm.length&&(this.searchTerm!==currentSearchTerm?this.onChange():this.getAttribute("results")==="true"?this.openSearch():this.getSearchResults(this.searchTerm))}onFocusOut(){setTimeout(()=>{this.contains(document.activeElement)||this.close()})}onKeyup(event){this.getQuery().length||this.close(!0),event.preventDefault()}updateSearchForTerm(previousTerm,newTerm){const searchForTextElement=this.querySelector("[data-predictive-search-search-for-text]"),currentButtonText=searchForTextElement?.innerText;if(currentButtonText){if(currentButtonText.match(new RegExp(previousTerm,"g")).length>1)return;const newButtonText=currentButtonText.replace(previousTerm,newTerm);searchForTextElement.innerText=newButtonText}}getSearchResults(searchTerm){const queryKey=searchTerm.replace(" ","-").toLowerCase();if(this.setLiveRegionLoadingState(),this.cachedResults[queryKey]){this.renderSearchResults(this.cachedResults[queryKey]);return}fetch(`${themeHDN.routes.predictive_search_url}?q=${encodeURIComponent(searchTerm)}&${this.params}section_id=${this.sectionIdResults}`,{signal:this.abortController2.signal}).then(response=>{if(!response.ok){var error=new Error(response.status);throw this.close(),error}return response.text()}).then(text=>{const resultsMarkup=new DOMParser().parseFromString(text,"text/html").querySelector("#shopify-section-"+this.sectionIdResults).innerHTML;this.allPredictiveSearchInstances.forEach(predictiveSearchInstance=>{this.cachedResults[queryKey]=resultsMarkup}),this.renderSearchResults(resultsMarkup)}).catch(error=>{if(error?.code!==20)throw this.close(),error})}setLiveRegionLoadingState(){this.hideWrapper.style.cssText="display: none;",this.showWrapper.style.cssText="display: block;",this.skeleton.classList.remove("hdt-hidden"),this.setAttribute("loading",!0)}renderSearchResults(resultsMarkup){this.predictiveSearchResults.innerHTML=resultsMarkup,this.setAttribute("results",!0),this.setLiveRegionResults(),this.openSearch(),document.dispatchEvent(new CustomEvent("currency:update"))}setLiveRegionResults(){this.removeAttribute("loading")}openSearch(){this.input.setAttribute("aria-expanded",!0),this.skeleton.classList.add("hdt-hidden"),this.isOpen=!0}close(clearSearchTerm=!1){this.closeResults(clearSearchTerm),this.isOpen=!1}closeResults(clearSearchTerm=!1){clearSearchTerm&&(this.input.value="",this.removeAttribute("results"),this.hideWrapper.style.cssText="display: block;",this.showWrapper.style.cssText="display: none;",this.predictiveSearchResults.innerHTML="");const selected=this.querySelector('[aria-selected="true"]');selected&&selected.setAttribute("aria-selected",!1),this.input.setAttribute("aria-activedescendant",""),this.removeAttribute("loading"),this.input.setAttribute("aria-expanded",!1),this.resultsMaxHeight=!1,this.predictiveSearchResults.removeAttribute("style")}}customElements.define("hdt-predictive-search",PredictiveSearch);import dayjs from"@theme/dayjs";dayjs.locale("en");class orderDelivery extends VariantChangeBase{constructor(){super(),this.config=JSON.parse(this.getAttribute("config")),this.offDays=this.config.off_day.replace(/ /g,"").split(","),this.nowDay=dayjs();var format_day=this.config.format_day,time=this.config.time.replace("24:00:00","23:59:59"),arrDayWeek=["SUN","MON","TUE","WED","THU","FRI","SAT"],dateStart=this.config.estimateStartDate||0,dateEnd=this.config.estimateEndDate||0,excludeDays=this.config.cut_day.replace(/ /g,"").split(","),startDay=dayjs(),i=0,endDay=dayjs(),j=0,nowTime=this.nowDay.format("HHmmss"),timeint=time.replace(/ /g,"").replace(/:/g,""),arrDay=themeHDN.extras.order.dayNames.replace(/ /g,"").split(","),arrMth=themeHDN.extras.order.monthNames.replace(/ /g,"").split(",");if(parseInt(nowTime)>=parseInt(timeint)&&(this.nowDay=this.nowDay.add(1,"day"),startDay=startDay.add(1,"day"),endDay=endDay.add(1,"day")),this.config.mode=="2"){for(;excludeDays.indexOf(arrDayWeek[startDay.format("d")])>-1||this.offDays.indexOf(startDay.format("DD/MM/****"))>-1||this.offDays.indexOf(startDay.format("DD/MM/YYYY"))>-1;)startDay=startDay.add(1,"day");for(;i-1||this.offDays.indexOf(startDay.format("DD/MM/****"))>-1||this.offDays.indexOf(startDay.format("DD/MM/YYYY"))>-1)&&i--;for(;excludeDays.indexOf(arrDayWeek[endDay.format("d")])>-1||this.offDays.indexOf(endDay.format("DD/MM/****"))>-1||this.offDays.indexOf(endDay.format("DD/MM/YYYY"))>-1;)endDay=endDay.add(1,"day");for(;j-1||this.offDays.indexOf(endDay.format("DD/MM/****"))>-1||this.offDays.indexOf(endDay.format("DD/MM/YYYY"))>-1)&&j--}else{for(startDay=startDay.add(dateStart,"day");excludeDays.indexOf(arrDayWeek[startDay.format("d")])>-1||this.offDays.indexOf(startDay.format("DD/MM/****"))>-1||this.offDays.indexOf(startDay.format("DD/MM/YYYY"))>-1;)startDay=startDay.add(1,"day");for(endDay=endDay.add(dateEnd,"day");excludeDays.indexOf(arrDayWeek[endDay.format("d")])>-1||this.offDays.indexOf(endDay.format("DD/MM/****"))>-1||this.offDays.indexOf(endDay.format("DD/MM/YYYY"))>-1;)endDay=endDay.add(1,"day")}arrDay=this.ArrUnique(arrDay),arrMth=this.ArrUnique(arrMth);var startDayDInt=parseInt(startDay.format("D")),daystStart=startDayDInt+this.nth(startDayDInt),MntStart=arrMth[parseInt(startDay.format("M"))-1],dayStart=arrDay[parseInt(startDay.format("d"))],EndDayDInt=parseInt(endDay.format("D")),daystEnd=EndDayDInt+this.nth(EndDayDInt),MntEnd=arrMth[parseInt(endDay.format("M"))-1],dayEnd=arrDay[parseInt(endDay.format("d"))];$4("[data-start-delivery]",this)&&($4("[data-start-delivery]",this).innerHTML=startDay.format(format_day).replace("t44",dayStart).replace("t45",daystStart).replace("t46",MntStart)),$4("[data-end-delivery]",this)&&($4("[data-end-delivery]",this).innerHTML=endDay.format(format_day).replace("t44",dayEnd).replace("t45",daystEnd).replace("t46",MntEnd))}ArrUnique(arr){var onlyUnique=function(value,index,self2){return self2.indexOf(value)===index};return arr.filter(onlyUnique)}nth(d){if(d>3&&d<21)return"th";switch(d%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}#preVariantId;onVariantChanged(event){const variant=event.detail.variant;variant&&this.#preVariantId!=variant.id&&(variant.available?(this.closest(".hdt-product-info__item").style.display="",variant.variant_state.pre_order&&(this.closest(".hdt-product-info__item").style.display="none")):this.closest(".hdt-product-info__item").style.display="none")}}customElements.define("order-delivery",orderDelivery);class countdownSimple extends HTMLElement{x=0;constructor(){super(),this.config=JSON.parse(this.getAttribute("config"));const time=this.config.time.replace("24:00:00","23:59:59");if(time=="19041994")return;this.textTemp=$4("template",this).innerHTML,this.notHasDay=!this.textTemp.includes("[days]");let today=dayjs();const nowTime=today.format("HHmmss"),configTime=time.replace(/ /g,"").replace(/:/g,"");parseInt(nowTime)>=parseInt(configTime)&&(today=today.add(1,"day")),this.countDownDate=new Date(`${today.format("YYYY-MM-DD")} ${time}`).getTime(),this.#update(),this.x=setInterval(this.#update.bind(this),this.textTemp.includes("[secs]")?1e3:6e4)}#update(){const now=new Date().getTime(),distance=this.countDownDate-now,days=Math.floor(distance/(1e3*60*60*24));let hours=Math.floor(distance%(1e3*60*60*24)/(1e3*60*60));const minutes=Math.floor(distance%(1e3*60*60)/(1e3*60)),seconds=Math.floor(distance%(1e3*60)/1e3);this.notHasDay&&(hours=days*24+hours),this.innerHTML=this.textTemp.replace("[days]",String(days).padStart(2,"0")).replace("[hours]",String(hours).padStart(2,"0")).replace("[mins]",String(minutes).padStart(2,"0")).replace("[secs]",String(seconds).padStart(2,"0")),distance<0&&(clearInterval(this.x),this.hidden=!0)}disconnectedCallback(){clearInterval(this.x)}}customElements.define("hdt-countdown-simple",countdownSimple);const dataInstagramCache={};class instagramFeedAPI extends HTMLElement{constructor(){super(),this.config=JSON.parse(this.getAttribute("config")),Shopify.designMode&&(document.addEventListener("shopify:section:select",event=>{this.refresh_ins()}),document.addEventListener("shopify:section:deselect",event=>{const{acc,id}=this.config;var data=sessionStorage.getItem("hdt_ins"+acc+id);data!=null&&data!=""&&sessionStorage.removeItem("hdt_ins"+acc+id)}))}connectedCallback(){this.refresh_ins()}refresh_ins(){const{acc,id}=this.config;if(acc!=""){var data=sessionStorage.getItem("hdt_ins"+acc+id);if(data!=null&&data!=""){var now=new Date,expiration=new Date(JSON.parse(data).timestamp);expiration.setMinutes(expiration.getMinutes()+30),now.getTime()>expiration.getTime()&&(data=null,sessionStorage.removeItem("hdt_ins"+acc+id))}if(data!=null&&data!="")this.instagramHTML(JSON.parse(data).content,!1);else{if(dataInstagramCache[acc]){$4(".hdt-slider__container",this).innerHTML=dataInstagramCache[acc],$4(".hdt-ins-loading",this)?.remove();const lazySlider=$4("hdt-slider-lazy",this);lazySlider&&(lazySlider.hidden=!1,lazySlider.InitLazy());return}fetch("https://graph.instagram.com/me/media?fields=id,media_type,media_url,permalink,thumbnail_url,caption,children&access_token="+atob(acc)).then(response=>{if(!response.ok)throw new Error("not ok");return response.json()}).then(res=>{this.instagramHTML(res.data,!0)}).catch(err=>{$4(".hdt-ins-loading",this)?.remove(),console.error("Instagram Feed:error fetch"),console.error(err)})}}}instagramHTML(data,saveSessionStorageIns){const arrIcons=($4(".hdt-icons-ins-svg",this).innerHTML||"").split("[hdtplit]"),icons={image:arrIcons[0],video:arrIcons[1],carousel_album:arrIcons[2]},{id,acc,target,limit}=this.config;let html="";data.forEach((el,index)=>{if(index>=limit)return 0;const media_type=el.media_type.toLowerCase();html+=``}),dataInstagramCache[acc]=html,$4(".hdt-slider__container",this).innerHTML=html,$4(".hdt-ins-loading",this)?.remove();const lazySlider=$4("hdt-slider-lazy",this);lazySlider&&(lazySlider.hidden=!1,lazySlider.InitLazy()),saveSessionStorageIns&&sessionStorage.setItem("hdt_ins"+acc+id,JSON.stringify({timestamp:new Date,content:data}))}}customElements.define("ins-feed-api",instagramFeedAPI);class ProductDescription extends HTMLElement{constructor(){super()}connectedCallback(){const handleIntersection=(entries,observer)=>{entries[0].isIntersecting&&(observer.unobserve(this),this.init())};new IntersectionObserver(handleIntersection.bind(this),{rootMargin:"0px 0px 0px 0px"}).observe(this)}init(){if(this.lm_btn=this.querySelector("[data-button]"),this.content=this.querySelector("[data-content]"),this.m_h=parseInt(this.dataset.heightLimit),!this.lm_btn||!this.content||!this.m_h)return;let content_h=this.content.scrollHeight;if(this.m_h>content_h){this.lm_btn.style.setProperty("display","none");return}this.content.style.setProperty("--height",`${content_h}px`),this.content.style.setProperty("max-height",`${this.m_h}px`),this.content.style.setProperty("--max-height",`${this.m_h}px`),this.lm_btn.addEventListener("click",()=>{this.classList.toggle("is--less")})}}if(customElements.define("product-description",ProductDescription),Shopify.designMode){let isStorageSupported=function(type){var storage=type==="session"?window.sessionStorage:window.localStorage;try{return storage.setItem("t4s","test"),storage.removeItem("t4s"),!0}catch{return!1}},alert_active_html=function(){return`
${$4(str_temp_active).innerHTML}
`};var ThemeCode=atob(window[atob("Y0hWeVkyaGg=")]),ThemeName_base64=window[atob("VkdobGJXVk9ZVzFsVkRR")],ThemeName=atob(ThemeName_base64),CookieName="SXNBY3RpdmVUaGVtZQ=="+ThemeName_base64,ShopEmail=atob(window[atob("VTJodmNFMWxiMVEw")]),isTrueSet=sessionStorage.getItem(CookieName)==="true",str_temp_active=atob("I3Q0cy10ZW1wLWtleS1hY3RpdmU="),str_purchase=atob("cHVyY2hhc2VfY29kZXQ0");if(ThemeCode==""){let dom1=new DOMParser().parseFromString(alert_active_html(),"text/html");document.body.append(dom1.body.firstElementChild);let dom2=new DOMParser().parseFromString('
',"text/html");document.body.prepend(dom2.body.firstElementChild),sessionStorage.removeItem(CookieName),localStorage.removeItem(CookieName)}else if(!isTrueSet){var domain=window.location.hostname,mix=["4","t","h","e","p","l","i","c","o","/",".",":","n","s"],mix_domain=mix[2]+mix[1]+mix[1]+mix[4]+mix[13]+mix[11]+mix[9]+mix[9]+mix[5]+mix[6]+mix[7]+mix[10]+mix[1]+mix[2]+mix[3]+mix[0]+mix[10]+mix[7]+mix[8]+mix[9]+mix[5]+mix[6]+mix[7]+mix[3]+mix[12]+mix[13]+mix[3]+mix[9]+mix[7]+mix[2]+mix[3]+mix[7]+"k",data={shopify_domain:domain,email:ShopEmail,theme:ThemeName,purchase_code:ThemeCode};fetch(mix_domain,{headers:{accept:"*/*","cache-control":"no-cache","x-requested-with":"XMLHttpRequest"},body:btoa(encodeURIComponent(JSON.stringify(data))),method:"POST",mode:"cors"}).then(function(response){if(response.ok)return response.json();throw""}).then(function(response){let dom=new DOMParser().parseFromString(alert_active_html(),"text/html");if(response.status==1){dom.body.firstElementChild.innerHTML="

ACTIVATED SUCCESSFULLY. Thanks for buying my theme!

",document.body.append(dom.body.firstElementChild);var isActived=localStorage.getItem(CookieName);sessionStorage.setItem(CookieName,"true"),isActived==="true"?$4(atob("I3B1cmNoYXNlX2NvZGV0NA==")).remove():(localStorage.setItem(CookieName,"true"),setTimeout(function(){$4(atob("I3B1cmNoYXNlX2NvZGV0NA==")).remove()},1e3))}else{var mess=response.message;if(mess=="No sale belonging to the current user found with that code")dom.body.firstElementChild.innerHTML="

Purchase code error. It is a sales reversal or a refund. :(((

";else if(mess.length==58||mess.length==101)dom.body.firstElementChild.innerHTML="

That license key doesn't appear to be valid. Please check your purchase code again!
Please open a ticket at support.the4.co if you have any question.

";else if(mess.length==104)dom.body.firstElementChild.innerHTML="

The license not match with current theme.!
Please open a ticket at support.the4.co if you have any question.

";else{try{var mess=mess.split("active domain `")[1].split("`. ")[0]}catch{}dom.body.firstElementChild.innerHTML="

Your purchase code is invalided since it is being activated at another store "+mess+".
Please open a ticket at support.the4.co to get quick assistance.

"}document.body.append(dom.body.firstElementChild)}}).catch(function(e){console.error(e)})}}class MasonryLayout extends HTMLElement{constructor(){super()}connectedCallback(){this.style.position="relative";const configAttr=this.getAttribute("config");if(configAttr)try{const userConfig=JSON.parse(configAttr);this.config={...userConfig}}catch{this.config={col_dk:5,col_tb:4,col_mb:2,gap:30,selector:".hdt-masonry-item"}}this.waitForImages().then(()=>{this.layoutMasonry(),this.animateItems(),setTimeout(()=>{items.forEach(item=>{item.style.transition="left 0.3s ease, top 0.3s ease, width 0.3s ease"})},items.length*100+500)}),window.addEventListener("resize",()=>{this.layoutMasonry()})}waitForImages(){const images=Array.from(this.querySelectorAll("img"));if(images.length===0)return Promise.resolve();let loaded=0;return new Promise(resolve=>{images.forEach(img=>{const item=img.closest(this.config.selector);function hideLoading(){const loading=item?.querySelector(".item-loading");loading&&(loading.style.display="none"),img.style.display="block"}img.complete?(hideLoading(),loaded++,loaded===images.length&&resolve()):(img.style.display="none",img.addEventListener("load",()=>{hideLoading(),loaded++,loaded===images.length&&resolve()},{once:!0}),img.addEventListener("error",()=>{hideLoading(),loaded++,loaded===images.length&&resolve()},{once:!0}))})})}layoutMasonry(){const items2=Array.from(this.querySelectorAll(this.config.selector)).filter(item=>item.style.display!=="none"),containerWidth=this.clientWidth;let columnCount=this.config.col_dk,gap=this.config.gap;containerWidth<768?(columnCount=this.config.col_mb,gap=this.config.gap_mb):containerWidth<1149&&(columnCount=this.config.col_tb);const columnHeights=Array(columnCount).fill(0),columnWidth=(containerWidth-gap*(columnCount-1))/columnCount;items2.forEach(item=>{item.style.display="block",item.style.position="absolute",item.style.width=`${columnWidth}px`}),items2.forEach(item=>{item.offsetHeight}),items2.forEach(item=>{const minCol=columnHeights.indexOf(Math.min(...columnHeights)),x=minCol*(columnWidth+gap),y=columnHeights[minCol];item.style.left=`${x}px`,item.style.top=`${y}px`,columnHeights[minCol]+=item.offsetHeight+gap}),this.style.height=Math.max(...columnHeights)+"px"}animateItems(){Array.from(this.querySelectorAll(this.config.selector)).forEach((item,index)=>{setTimeout(()=>{item.style.visibility="visible",item.style.opacity="0",item.style.transform="translateY(30px)",item.style.transition="opacity 0.5s, transform 0.5s",setTimeout(()=>{item.style.opacity="1",item.style.transform="translateY(0)"},10)},index*100)})}}class FilterSorting extends HTMLElement{constructor(){super(),this.selector=this.getAttribute("config")?JSON.parse(this.getAttribute("config")).selector:".hdt-masonry-item"}connectedCallback(){this.initializeFilter()}initializeFilter(){const filterItems=this.querySelectorAll("[data-category]"),masonry=this.querySelector("hdt-masonry-layout");if(!masonry)return;const items2=masonry.querySelectorAll(this.selector);filterItems.forEach(filter=>{filter.addEventListener("click",()=>{filterItems.forEach(f=>f.classList.remove("hdt-active")),filter.classList.add("hdt-active");const category=filter.getAttribute("data-category");items2.forEach(item=>{category==="all"||item.classList.contains(category)?(item.style.display="block",setTimeout(()=>{item.style.opacity="1",item.style.transform="translateY(0)"},100)):(item.style.opacity="0",item.style.transform="translateY(20px)",setTimeout(()=>{item.style.display="none"},300))}),setTimeout(()=>{typeof masonry.layoutMasonry=="function"&&masonry.layoutMasonry()},350)})})}}customElements.define("hdt-masonry-layout",MasonryLayout),customElements.define("hdt-filter-sorting",FilterSorting);function convertNameCookies(name){return name.replace(/=/g,"_")}function setCookie(name,value,days,hours){var expires="";if(days||hours){var date=new Date;date.setTime(date.getTime()+(days?days*24*60*60*1e3:hours*60*60*1e3)),expires="; expires="+date.toString()}document.cookie=convertNameCookies(name)+"="+(value||"")+expires+"; path=/"}function getCookie(name){for(var nameEQ=convertNameCookies(name)+"=",ca=document.cookie.split(";"),i=0;i{event.target.classList.contains("sys-cookies")&&self2.showCookiesBanner()}),document.addEventListener("shopify:section:deselect",event=>{event.target.classList.contains("sys-cookies")&&self2.hideCookiesBanner()}))}handleAccept(){this.isShowCookiesAll&&setCookie(this.cookies.cookiesName,"accepted",parseInt(this.cookies.day_next)),window.Shopify.customerPrivacy.setTrackingConsent(!0,this.hideCookiesBanner.bind(this))}handleDecline(){this.isShowCookiesAll&&setCookie(this.cookies.cookiesName,"accepted",parseInt(this.cookies.day_next)),window.Shopify.customerPrivacy.setTrackingConsent(!1,this.hideCookiesBanner.bind(this))}showCookiesBanner(){this.cookiesDrawer.classList.add("cookies-show")}hideCookiesBanner(){this.cookiesDrawer.classList.remove("cookies-show")}initCookieBanner(){const userCanBeTracked=window.Shopify.customerPrivacy.userCanBeTracked(),userTrackingConsent=window.Shopify.customerPrivacy.getTrackingConsent();(!userCanBeTracked&&userTrackingConsent==="no_interaction"||this.isShowCookiesAll)&&(Shopify.designMode||this.showCookiesBanner())}loadCookieBanner(){let self2=this;this.cookiesDrawer.length!=0&&(this.cookies.day_next=this.cookies.day_next||60,this.isShowCookiesAll=this.cookies.show=="1",!(getCookie(this.cookies.cookiesName)=="accepted"||this.cookiesDrawer.hasAttribute("open"))&&window.Shopify.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],function(error){if(error)throw error;self2.initCookieBanner()}))}}customElements.define("sys-cookies",cookiesBar);class newsletterModal extends HTMLElement{constructor(){if(super(),this.configs=JSON.parse(this.getAttribute("configs")),this.modal=this.querySelector("hdt-modal"),!Shopify.designMode&&getCookie("theme4:newsletter:"+this.configs.id)=="shown"){this.modal.setAttribute("closed","");return}this.dialog=this.querySelector("dialog"),this.action_close=this.querySelectorAll("[action-close]"),this.time_delay=this.configs.time_delay,this.day_next=this.configs.day_next,Shopify.designMode&&(this._shopifySection=this._shopifySection||this.closest(".shopify-section"),this._shopifySection.addEventListener("shopify:section:load",()=>this.modal.open()),this._shopifySection.addEventListener("shopify:section:select",()=>this.modal.open()),this._shopifySection.addEventListener("shopify:section:deselect",()=>this.modal.close()))}connectedCallback(){if(!Shopify.designMode){if(getCookie("theme4:newsletter:"+this.configs.id)=="shown"){this.modal.setAttribute("closed","");return}const fnShow=this.showModal.bind(this),fnShowScroll=this.showModalScroll.bind(this);if(this.configs.after==="time"){let tm=setTimeout(fnShow,this.configs.time_delay*1e3);this.dialog.addEventListener(`${dialogClose}`,()=>{clearTimeout(tm),this.hideModal(!1,!0)})}else window.addEventListener("scroll",fnShowScroll),this.dialog.addEventListener(`${dialogClose}`,()=>{window.removeEventListener("scroll",fnShowScroll),this.hideModal(!1,!0)});this.actionClose()}}disconnectedCallback(){}showModal(){this.modal.open()}showModalScroll(){window.scrollY>this.configs.scroll_delay&&this.modal.open()}hideModal(pause,off){off&&setCookie("theme4:newsletter:"+this.configs.id,"shown",this.day_next)}actionClose(){let self2=this;self2.action_close&&self2.action_close.forEach(btn=>{btn.addEventListener("click",function(){self2.modal.close(),self2.hideModal(!1,!0),setTimeout(()=>{self2.remove()},500)})})}}customElements.define("sys-newsletter",newsletterModal);class exitModal extends HTMLElement{constructor(){super(),this.configs=JSON.parse(this.getAttribute("configs")),!(!Shopify.designMode&&getCookie("theme4:exit:"+this.configs.id)=="shown")&&(this.modal=this.querySelector("hdt-modal"),this.dialog=this.querySelector("dialog"),this.day_next=this.configs.day_next,this.btn_copy=this.querySelector('button[is="discount_copy"]'),this.discount=this.querySelector('[is="discount"]'),Shopify.designMode&&(this._shopifySection=this._shopifySection||this.closest(".shopify-section"),this._shopifySection.addEventListener("shopify:section:load",()=>this.showModal()),this._shopifySection.addEventListener("shopify:section:select",()=>this.showModal()),this._shopifySection.addEventListener("shopify:section:deselect",()=>this.modal.close())))}connectedCallback(){if(!Shopify.designMode){if(getCookie("theme4:exit:"+this.configs.id)=="shown")return;this.configs.after==="move_cursor"?window.innerWidth>1150?this.moveCursor():this.scrollPage():this.configs.after==="scroll"?this.scrollPage():this.amountTime()}}moveCursor(){const fnShow=this.showModal.bind(this);document.querySelector("body").addEventListener("mouseleave",fnShow),this.dialog.addEventListener(`${dialogClose}`,()=>{document.querySelector("body").removeEventListener("mouseleave",fnShow),this.hideModal(!1,!0)})}scrollPage(){const fnShow=this.showModal.bind(this);let docHeight=document.documentElement.scrollHeight-document.documentElement.clientHeight-500,scroll=()=>{window.scrollY>=docHeight&&fnShow()};window.addEventListener("scroll",scroll),this.dialog.addEventListener(`${dialogClose}`,()=>{window.removeEventListener("scroll",scroll),this.hideModal(!1,!0)})}amountTime(){const fnShow=this.showModal.bind(this);let tm=setTimeout(fnShow,this.configs.time_delay*1e3);this.dialog.addEventListener(`${dialogClose}`,()=>{clearTimeout(tm),this.hideModal(!1,!0)})}showModal(){let self2=this;this.modal.open(),self2.btn_copy&&self2.discount&&(self2.btn_copy.addEventListener("click",function(){self2.discount.select(),self2.discount.setSelectionRange(0,99999),document.execCommand("copy"),self2.btn_copy.querySelector(".hdt-tooltip-text").innerText=`${themeHDN.extras.exit_popup.copied}: ${self2.discount.value}`}),self2.btn_copy.addEventListener("mouseleave",function(){self2.btn_copy.querySelector(".hdt-tooltip-text").innerText=themeHDN.extras.exit_popup.copy}))}hideModal(pause,off){off&&setCookie("theme4:exit:"+this.configs.id,"shown",this.day_next)}}customElements.define("sys-exit",exitModal);class atcAnimation extends HTMLElement{constructor(){super(),this.config=JSON.parse(this.getAttribute("config")),this.atc_btn=this.querySelector("[data-animation]:not([disabled])"),!this.config||this.atc_btn}init(){let class_list=this.config.ani.split(" ");this.interval=setInterval(()=>{this.atc_btn.classList.add(...class_list),this.timer=setTimeout(()=>{this.atc_btn.classList.remove(...class_list)},1e3)},parseInt(this.config.time)*1e3)}connectedCallback(){this.config&&this.atc_btn&&this.init()}disconnectedCallback(){clearInterval(this.interval),clearTimeout(this.timer)}}customElements.define("hdt-atc-animation",atcAnimation);class readmoreLess extends HTMLElement{constructor(){super(),this.config=JSON.parse(this.getAttribute("config"))}init(){console.log(this.offsetHeight),console.log(parseInt(this.config.readMoreHeight)),console.log(this.offsetHeight>parseInt(this.config.readMoreHeight)),this.closest("readmore-less-wrap").classList.toggle("less--desc",this.offsetHeight>parseInt(this.config.readMoreHeight)),this.closest("readmore-less-wrap").style.setProperty("--height",`${this.offsetHeight}px`)}onResize(){window.addEventListener("resize",()=>{this.closest("readmore-less-wrap").style.setProperty("--height",""),this.init()})}connectedCallback(){const handleIntersection=(entries,observer)=>{entries[0].isIntersecting&&(observer.unobserve(this),this.init(),this.onResize())};new IntersectionObserver(handleIntersection.bind(this),{rootMargin:"0px 0px 0px 0px"}).observe(this)}}customElements.define("readmore-less",readmoreLess);class CounterItem extends HTMLElement{constructor(){super(),this.started=!1,this.start=Math.abs(parseInt(this.getAttribute("data-start"))||0),this.end=Math.abs(parseInt(this.getAttribute("data-end"))||100),this.speed=parseInt(this.getAttribute("data-speed"))||1e3,this.number=this.querySelector("[data-number]"),this.duration=this.speed,this.current=this.start,this.number.innerHTML=this.start}connectedCallback(){this.end>this.start&&this.observe()}observe(){new IntersectionObserver((entries,observer2)=>{entries.forEach(entry=>{entry.isIntersecting&&!this.started&&(this.started=!0,this.animateCounter(),observer2.unobserve(this))})},{threshold:.6}).observe(this)}animateCounter(){const startTime=performance.now(),animate=now=>{const elapsed=now-startTime;if(elapsed{this.video.play()}),this.dialog.addEventListener(`${dialogClose}`,e=>{this.video.pause()}),this.action==="popup"&&this.button.addEventListener("click",()=>{this.modal.open()}),this.action==="inline"&&(this.button.addEventListener("click",()=>{this.initnModalInline()}),this.closeButton?.addEventListener("click",()=>{this.closeModalInline()}))}initnModalInline(){this.root.style.setProperty("position","relative"),this.root.appendChild(this.modal),this.modal.classList.add("hdt-modal-inline")}closeModalInline(){this.root.style.removeProperty("position"),this.modal.classList.remove("hdt-modal-inline"),this.appendChild(this.modal)}}customElements.define("hdt-video-popup",videoPopup);class productCardMedia extends HTMLElement{constructor(){super(),this.mainMedia=$4("hdt-video-player[main-media]",this),this.secondMedia=$4("hdt-video-player[second-media]",this)}connectedCallback(){this.setupEventListeners()}setupEventListeners(){this.addEventListener("mouseenter",()=>{this.mainMedia&&this.secondMedia&&this.mainMedia.pause(),this.secondMedia&&this.secondMedia.play()}),this.addEventListener("mouseleave",()=>{this.mainMedia&&this.mainMedia.play(),this.secondMedia&&this.secondMedia.pause()})}}customElements.define("hdt-product-card-media",productCardMedia);class SnowEffect extends HTMLElement{constructor(){super(),this.speed=parseFloat(this.getAttribute("speed"))||1,this.overlayOpacity=parseFloat(this.getAttribute("overlay-opacity"))||0,this.animationId=null,this.snowflakes=[],this.animate=this.animate.bind(this),this.resizeCanvas=this.resizeCanvas.bind(this)}static get observedAttributes(){return["speed","overlay-opacity"]}connectedCallback(){this.render(),this.setupCanvas(),this.createSnowPatterns(),this.setupEventListeners(),this.start()}disconnectedCallback(){this.stop(),window.removeEventListener("resize",this.resizeCanvas)}attributeChangedCallback(name,oldValue,newValue){oldValue!==newValue&&(name==="speed"&&(this.speed=newValue),name==="overlay-opacity"&&(this.overlayOpacity=newValue))}render(){this.innerHTML=` `}setupCanvas(){this.canvas=this.querySelector("canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.ctx&&this.resizeCanvas())}resizeCanvas(){this.canvas&&(this.canvas.width=window.innerWidth,this.canvas.height=window.innerHeight,this.snowflakes&&this.snowflakes.length>0&&this.createSnowPatterns())}createSnowPatterns(){this.snowflakes=[];const snowflakeCount=250;if(!(!this.canvas||this.canvas.width<=0||this.canvas.height<=0)){for(let i=0;ia.depthFactor-b.depthFactor)}}animate(){!this.ctx||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.overlayOpacity>0&&(this.ctx.fillStyle=`rgba(0, 0, 0, ${this.overlayOpacity})`,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)),this.snowflakes.length!==0&&(this.snowflakes.forEach(snowflake=>{const actualSpeed=this.speed>0?snowflake.speed*this.speed*snowflake.depthFactor:0;snowflake.y+=actualSpeed,snowflake.x+=snowflake.drift*snowflake.depthFactor,snowflake.x<-10&&(snowflake.x=this.canvas.width+10),snowflake.x>this.canvas.width+10&&(snowflake.x=-10),snowflake.y>this.canvas.height+10&&(snowflake.x=Math.random()*this.canvas.width,snowflake.y=-10-Math.random()*50),this.ctx.save(),this.ctx.globalAlpha=snowflake.opacity;const glowStrength=snowflake.depthFactor*3;this.ctx.shadowBlur=glowStrength,this.ctx.shadowColor=`rgba(255, 255, 255, ${snowflake.depthFactor*.8})`,this.ctx.shadowOffsetX=0,this.ctx.shadowOffsetY=0,this.ctx.beginPath(),this.ctx.arc(snowflake.x,snowflake.y,snowflake.size*.5,0,Math.PI*2);const brightness=Math.floor(snowflake.depthFactor*55+200);this.ctx.fillStyle=`rgb(${brightness}, ${brightness}, ${brightness})`,this.ctx.fill(),snowflake.size>3&&(this.ctx.beginPath(),this.ctx.arc(snowflake.x-snowflake.size*.2,snowflake.y-snowflake.size*.2,snowflake.size*.15,0,Math.PI*2),this.ctx.fillStyle=`rgba(255, 255, 255, ${snowflake.depthFactor*.6})`,this.ctx.fill()),this.ctx.restore()}),this.animationId=requestAnimationFrame(this.animate)))}setupEventListeners(){window.addEventListener("resize",this.resizeCanvas)}start(){this.animate()}stop(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)}}customElements.define("hdt-snow-effect",SnowEffect);class inactiveTabMessage extends HTMLElement{constructor(){super(),this.config=JSON.parse(this.getAttribute("config"))}connectedCallback(){this.config.message&&(this.intervalId=null,this.messageIndex=0,this.originalTitle=document.title,this.messages=this.config.message.split(";").map(m=>m.trim()).filter(m=>m.length),this.messages.length&&this.setupEventListeners())}setupEventListeners(){window.addEventListener("visibilitychange",this.handleInit.bind(this))}handleInit(){document.hidden?this.intervalId=setInterval(()=>{document.title=this.messages[this.messageIndex],this.messageIndex=(this.messageIndex+1)%this.messages.length},this.config.delay):(clearInterval(this.intervalId),document.title=this.originalTitle)}}customElements.define("hdt-inactive-tab",inactiveTabMessage);class FaviconCartBadge extends HTMLElement{constructor(){super(),this._badgeQueue=[],this._currentBadge=null,this._isReady=!1,this._isVideoPlaying=!1,this._canvas=null,this._context=null,this._originalImage=null,this._iconElements=[],this._canvasWidth=32,this._canvasHeight=32,this._animationTimeout=null,this._videoTimeout=null,this._settings={bgColor:{r:221,g:0,b:0},textColor:{r:255,g:255,b:255},fontFamily:"sans-serif",fontStyle:"bold",type:"circle",position:"down",animation:"slide",elementId:null,element:null},this._browser={ff:typeof InstallTrigger<"u",chrome:!!window.chrome,opera:!!window.opera||navigator.userAgent.indexOf("Opera")>=0,ie:!1,safari:Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},this._browser.supported=this._browser.chrome||this._browser.ff||this._browser.opera,this._animationTypes={fade:[{x:.4,y:.4,w:.6,h:.6,o:0},{x:.4,y:.4,w:.6,h:.6,o:.1},{x:.4,y:.4,w:.6,h:.6,o:.2},{x:.4,y:.4,w:.6,h:.6,o:.3},{x:.4,y:.4,w:.6,h:.6,o:.4},{x:.4,y:.4,w:.6,h:.6,o:.5},{x:.4,y:.4,w:.6,h:.6,o:.6},{x:.4,y:.4,w:.6,h:.6,o:.7},{x:.4,y:.4,w:.6,h:.6,o:.8},{x:.4,y:.4,w:.6,h:.6,o:.9},{x:.4,y:.4,w:.6,h:.6,o:1}],none:[{x:.4,y:.4,w:.6,h:.6,o:1}],pop:[{x:1,y:1,w:0,h:0,o:1},{x:.9,y:.9,w:.1,h:.1,o:1},{x:.8,y:.8,w:.2,h:.2,o:1},{x:.7,y:.7,w:.3,h:.3,o:1},{x:.6,y:.6,w:.4,h:.4,o:1},{x:.5,y:.5,w:.5,h:.5,o:1},{x:.4,y:.4,w:.6,h:.6,o:1}],popFade:[{x:.75,y:.75,w:0,h:0,o:0},{x:.65,y:.65,w:.1,h:.1,o:.2},{x:.6,y:.6,w:.2,h:.2,o:.4},{x:.55,y:.55,w:.3,h:.3,o:.6},{x:.5,y:.5,w:.4,h:.4,o:.8},{x:.45,y:.45,w:.5,h:.5,o:.9},{x:.4,y:.4,w:.6,h:.6,o:1}],slide:[{x:.4,y:1,w:.6,h:.6,o:1},{x:.4,y:.9,w:.6,h:.6,o:1},{x:.4,y:.9,w:.6,h:.6,o:1},{x:.4,y:.8,w:.6,h:.6,o:1},{x:.4,y:.7,w:.6,h:.6,o:1},{x:.4,y:.6,w:.6,h:.6,o:1},{x:.4,y:.5,w:.6,h:.6,o:1},{x:.4,y:.4,w:.6,h:.6,o:1}]},this._animationDuration=40}static get observedAttributes(){return["cart-count","bg-color","text-color","font-family","font-style","type","position","animation","event-name"]}connectedCallback(){this._initialize()}disconnectedCallback(){this._cleanup()}attributeChangedCallback(name,oldValue,newValue){if(this._isReady)switch(name){case"cart-count":this.setBadge(parseInt(newValue)||0);break;case"bg-color":this._settings.bgColor=this._hexToRgb(newValue);break;case"text-color":this._settings.textColor=this._hexToRgb(newValue);break;case"font-family":this._settings.fontFamily=newValue;break;case"font-style":this._settings.fontStyle=newValue;break;case"type":this._settings.type=newValue;break;case"position":this._settings.position=newValue.toLowerCase();break;case"animation":this._settings.animation=newValue;break;case"event-name":this._setupEventListener(newValue);break}}_initialize(){this._parseAttributes(),this._adjustAnimationPosition(),this._iconElements=this._getIcons(),this._canvas=document.createElement("canvas"),this._originalImage=document.createElement("img");const currentIcon=this._iconElements[this._iconElements.length-1];currentIcon&¤tIcon.hasAttribute("href")?(this._originalImage.setAttribute("crossOrigin","anonymous"),this._originalImage.onload=()=>{this._canvasHeight=this._originalImage.height>0?this._originalImage.height:32,this._canvasWidth=this._originalImage.width>0?this._originalImage.width:32,this._canvas.height=this._canvasHeight,this._canvas.width=this._canvasWidth,this._context=this._canvas.getContext("2d"),this._ready()},this._originalImage.setAttribute("src",currentIcon.getAttribute("href"))):(this._canvasHeight=32,this._canvasWidth=32,this._originalImage.height=this._canvasHeight,this._originalImage.width=this._canvasWidth,this._canvas.height=this._canvasHeight,this._canvas.width=this._canvasWidth,this._context=this._canvas.getContext("2d"),this._ready());const eventName=this.getAttribute("event-name")||cartCount;this._setupEventListener(eventName)}_parseAttributes(){const bgColor=this.getAttribute("bg-color")||"#d00",textColor=this.getAttribute("text-color")||"#fff";this._settings.bgColor=this._hexToRgb(bgColor),this._settings.textColor=this._hexToRgb(textColor),this._settings.fontFamily=this.getAttribute("font-family")||"sans-serif",this._settings.fontStyle=this.getAttribute("font-style")||"bold",this._settings.type=this.getAttribute("type")||"circle",this._settings.position=(this.getAttribute("position")||"down").toLowerCase(),this._settings.animation=this.getAttribute("animation")||"slide"}_adjustAnimationPosition(){const isUp=this._settings.position.indexOf("up")>-1,isLeft=this._settings.position.indexOf("left")>-1;if(isUp||isLeft)for(let type in this._animationTypes)for(let i=0;i{event.detail&&typeof event.detail.item_count<"u"&&this.setBadge(event.detail.item_count)},document.addEventListener(eventName,this._eventListener)}_ready(){this._isReady=!0,this.reset();const cart_count=parseInt(this.getAttribute("cart-count"))||0;cart_count>0&&this.setBadge(cart_count)}_cleanup(){clearTimeout(this._animationTimeout),clearTimeout(this._videoTimeout),this._eventListener&&this._currentEventName&&document.removeEventListener(this._currentEventName,this._eventListener)}_hexToRgb(hex){hex=hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(m,r,g,b)=>r+r+g+g+b+b);const result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);return result?{r:parseInt(result[1],16),g:parseInt(result[2],16),b:parseInt(result[3],16)}:{r:221,g:0,b:0}}_getIcons(){const elementId=this.getAttribute("element-id");let icons=[];if(elementId){const element=document.getElementById(elementId);element&&(icons=[element],element.setAttribute("href",element.getAttribute("src")))}else{const headLinks=document.getElementsByTagName("head")[0].getElementsByTagName("link");for(let i=0;i{icon.setAttribute("type","image/png")}),icons}_setIcon(canvas){const url=canvas.toDataURL("image/png");this._setIconSrc(url)}_setIconSrc(url){if(this._browser.ff||this._browser.opera){const old=this._iconElements[this._iconElements.length-1],newIcon=document.createElement("link");this._iconElements=[newIcon],this._browser.opera&&newIcon.setAttribute("rel","icon"),newIcon.setAttribute("rel","icon"),newIcon.setAttribute("type","image/png"),document.getElementsByTagName("head")[0].appendChild(newIcon),newIcon.setAttribute("href",url),old.parentNode&&old.parentNode.removeChild(old)}else this._iconElements.forEach(icon=>{icon.setAttribute("href",url)})}_normalizeValues(values){return values.n=typeof values.n=="number"?Math.abs(values.n|0):values.n,values.x=this._canvasWidth*values.x,values.y=this._canvasHeight*values.y,values.w=this._canvasWidth*values.w,values.h=this._canvasHeight*values.h,values.len=(values.n+"").length,values}_renderCircle(values){let isWide=!1;values=this._normalizeValues(values),values.len===2?(values.x=values.x-values.w*.4,values.w=values.w*1.4,isWide=!0):values.len>=3&&(values.x=values.x-values.w*.65,values.w=values.w*1.65,isWide=!0),this._context.clearRect(0,0,this._canvasWidth,this._canvasHeight),this._context.drawImage(this._originalImage,0,0,this._canvasWidth,this._canvasHeight),this._context.beginPath(),this._context.font=this._settings.fontStyle+" "+Math.floor(values.h*(values.n>99?.85:1))+"px "+this._settings.fontFamily,this._context.textAlign="center",isWide?(this._context.moveTo(values.x+values.w/2,values.y),this._context.lineTo(values.x+values.w-values.h/2,values.y),this._context.quadraticCurveTo(values.x+values.w,values.y,values.x+values.w,values.y+values.h/2),this._context.lineTo(values.x+values.w,values.y+values.h-values.h/2),this._context.quadraticCurveTo(values.x+values.w,values.y+values.h,values.x+values.w-values.h/2,values.y+values.h),this._context.lineTo(values.x+values.h/2,values.y+values.h),this._context.quadraticCurveTo(values.x,values.y+values.h,values.x,values.y+values.h-values.h/2),this._context.lineTo(values.x,values.y+values.h/2),this._context.quadraticCurveTo(values.x,values.y,values.x+values.h/2,values.y)):this._context.arc(values.x+values.w/2,values.y+values.h/2,values.h/2,0,2*Math.PI),this._context.fillStyle=`rgba(${this._settings.bgColor.r},${this._settings.bgColor.g},${this._settings.bgColor.b},${values.o})`,this._context.fill(),this._context.closePath(),this._context.beginPath(),this._context.stroke(),this._context.fillStyle=`rgba(${this._settings.textColor.r},${this._settings.textColor.g},${this._settings.textColor.b},${values.o})`,typeof values.n=="number"&&values.n>999?this._context.fillText((values.n>9999?9:Math.floor(values.n/1e3))+"k+",Math.floor(values.x+values.w/2),Math.floor(values.y+values.h-values.h*.2)):this._context.fillText(values.n,Math.floor(values.x+values.w/2),Math.floor(values.y+values.h-values.h*.15)),this._context.closePath()}_renderRectangle(values){values=this._normalizeValues(values),values.len===2?(values.x=values.x-values.w*.4,values.w=values.w*1.4):values.len>=3&&(values.x=values.x-values.w*.65,values.w=values.w*1.65),this._context.clearRect(0,0,this._canvasWidth,this._canvasHeight),this._context.drawImage(this._originalImage,0,0,this._canvasWidth,this._canvasHeight),this._context.beginPath(),this._context.font=this._settings.fontStyle+" "+Math.floor(values.h*(values.n>99?.9:1))+"px "+this._settings.fontFamily,this._context.textAlign="center",this._context.fillStyle=`rgba(${this._settings.bgColor.r},${this._settings.bgColor.g},${this._settings.bgColor.b},${values.o})`,this._context.fillRect(values.x,values.y,values.w,values.h),this._context.fillStyle=`rgba(${this._settings.textColor.r},${this._settings.textColor.g},${this._settings.textColor.b},${values.o})`,typeof values.n=="number"&&values.n>999?this._context.fillText((values.n>9999?9:Math.floor(values.n/1e3))+"k+",Math.floor(values.x+values.w/2),Math.floor(values.y+values.h-values.h*.2)):this._context.fillText(values.n,Math.floor(values.x+values.w/2),Math.floor(values.y+values.h-values.h*.15)),this._context.closePath()}_mergeObjects(obj1,obj2){const result={};for(let key in obj1)result[key]=obj1[key];for(let key in obj2)result[key]=obj2[key];return result}_runAnimation(options,callback,reverse,frameIndex){const frames=this._animationTypes[document.hidden||document.msHidden||document.webkitHidden||document.mozHidden?"none":this._settings.animation];frameIndex=reverse===!0?frameIndex!==void 0?frameIndex:frames.length-1:frameIndex!==void 0?frameIndex:0,callback=callback||function(){},frameIndex=0?((this._settings.type==="rectangle"?this._renderRectangle:this._renderCircle).call(this,this._mergeObjects(options,frames[frameIndex])),this._videoTimeout=setTimeout(()=>{reverse?frameIndex-=1:frameIndex+=1,this._runAnimation(options,callback,reverse,frameIndex)},this._animationDuration),this._setIcon(this._canvas)):callback()}_start(){if(this._isReady&&!this._isVideoPlaying&&this._badgeQueue.length>0){this._isVideoPlaying=!0;const processBadge=()=>{["type","animation","bgColor","textColor","fontFamily","fontStyle"].forEach(prop=>{prop in this._badgeQueue[0].options&&(this._settings[prop]=this._badgeQueue[0].options[prop])}),this._runAnimation(this._badgeQueue[0].options,()=>{this._currentBadge=this._badgeQueue[0],this._isVideoPlaying=!1,this._badgeQueue.length>0&&(this._badgeQueue.shift(),this._start())},!1)};this._currentBadge?this._runAnimation(this._currentBadge.options,()=>{processBadge()},!0):processBadge()}}setBadge(number,options={}){if(this._isReady)try{if(typeof number=="number"?number>0:number!==""){const badgeOptions={type:"badge",options:{n:number}};if("animation"in options&&this._animationTypes[options.animation+""]&&(badgeOptions.options.animation=options.animation+""),"type"in options&&(options.type==="circle"||options.type==="rectangle")&&(badgeOptions.options.type=options.type+""),["bgColor","textColor"].forEach(prop=>{prop in options&&(badgeOptions.options[prop]=this._hexToRgb(options[prop]))}),["fontStyle","fontFamily"].forEach(prop=>{prop in options&&(badgeOptions.options[prop]=options[prop])}),this._badgeQueue.push(badgeOptions),this._badgeQueue.length>100)throw new Error("Too many badges requests in queue.");this._start()}else this.reset()}catch(error){throw new Error("Error setting badge. Message: "+error.message)}}reset(){this._isReady&&(this._badgeQueue=[],this._currentBadge=!1,this._isVideoPlaying=!1,this._context.clearRect(0,0,this._canvasWidth,this._canvasHeight),this._context.drawImage(this._originalImage,0,0,this._canvasWidth,this._canvasHeight),this._setIcon(this._canvas),clearTimeout(this._videoTimeout),clearTimeout(this._animationTimeout))}get cart_count(){return parseInt(this.getAttribute("cart-count"))||0}set cart_count(value){this.setAttribute("cart-count",value)}get bgColor(){return this.getAttribute("bg-color")||"#d00"}set bgColor(value){this.setAttribute("bg-color",value)}get textColor(){return this.getAttribute("text-color")||"#fff"}set textColor(value){this.setAttribute("text-color",value)}}customElements.define("favicon-cart-badge",FaviconCartBadge);class SalesPopup extends HTMLElement{constructor(){super(),this.salesJson=JSON.parse(document.getElementById("hdt-popup__sales-JSON").innerHTML),this.close_btn=this.querySelector("[data-close-sale]"),this.quickview_btn=this.querySelector('[aria-controls="hdt-quick-view-modal"]'),this.progressbar=this.querySelector("[data-progressbar] > span"),this.image_sale=this.querySelector("[data-image-sale]"),this.title_sale=this.querySelector("[data-title-sale]"),this.url_link=this.querySelectorAll("[data-href-sale]"),this.location_sale=this.querySelector("[data-location-sale]"),this.time_sale=this.querySelector("[data-ago-sale]")}connectedCallback(){this.startTime=this.salesJson.starTime*this.salesJson.starTimeUnit,this.stayTime=this.salesJson.stayTime*this.salesJson.stayTimeUnit,this.index=0,this.limit=this.salesJson.limit,this.max=this.salesJson.max,this.min=0,this.classUp=this.salesJson.classUp,this.classDown=this.salesJson.classDown[this.classUp],this.ppType=this.salesJson.ppType,this.pauseOnHover=this.salesJson.pauseOnHover,this.resetOnHover=this.salesJson.resetOnHover,this.isMobile=this.salesJson.isMobile,this.idArray=this.salesJson.idArray,this.titleArray=this.salesJson.titleArray,this.handleArray=this.salesJson.handleArray,this.urlArray=this.salesJson.urlArray,this.locationArray=this.salesJson.locationArray,this.timeArray=this.salesJson.timeArray,this.imageArray=this.salesJson.imageArray,this.max=this.urlArray.length-1,this.max2=this.locationArray.length-1,this.max3=this.timeArray.length-1,this.starTimeout,this.stayTimeout,this.time={START:null,END:null,REMAINING:null},!(!this.isMobile&&window.innerWidth<768||this.hasAttribute("loaded"))&&(this.setAttribute("loaded",""),this.setupEvents(),this.unloadSalesPopup())}disconnectedCallback(){this.clearEvents()}getRandomInit(min,max){return Math.floor(Math.random()*(max-min+1))+min}updateData(index){var img=this.imageArray[index],img_url=`${img}&width=130`,img_srcset=`${img}&width=65 65w, ${img}&width=130 130w`;this.image_sale&&(this.image_sale.src=img_url,this.image_sale.srcset=img_srcset),this.title_sale&&(this.title_sale.textContent=this.titleArray[index]),this.url_link&&this.url_link.forEach(link=>{link.href=this.urlArray[index]}),this.location_sale&&(this.location_sale.textContent=this.locationArray[index]),this.time_sale&&(this.time_sale.textContent=this.timeArray[index]),this.quickview_btn&&this.quickview_btn.setAttribute("handle",this.handleArray[index])}hideSalesPopup(){this&&(this.removeAttribute("show"),this.classList.remove(this.classUp),this.classList.add(this.classDown))}showSalesPopup(){this&&(this.setAttribute("show",""),this.classList.add(this.classUp),this.classList.remove(this.classDown))}setupEvents(){this.pauseOnHover&&(this.addEventListener("mouseenter",e=>{this.mouseenterHandler(e)}),this.addEventListener("mouseleave",()=>{this.mouseleaveHandler()})),this.close_btn&&this.close_btn.addEventListener("click",e=>{e.preventDefault(),this.hideSalesPopup(),this.clearEvents()})}mouseenterHandler(){this.resetOnHover?this.progressbar&&this.progressbar.style.setProperty("animation-name","none"):this.time.REMAINING=this.time.END-new Date().getTime(),clearTimeout(this.stayTimeout)}mouseleaveHandler(){this.resetOnHover?(this.time.REMAINING=this.stayTime,this.progressbar&&this.progressbar.style.setProperty("animation-name","hdt-ani-w")):this.time.END=new Date().getTime()+this.time.REMAINING,this.stayTimeout=setTimeout(()=>{this.unloadSalesPopup(),this.hideSalesPopup()},this.time.REMAINING)}clearEvents(){this.removeEventListener("mouseenter",this.mouseenterHandler),this.removeEventListener("mouseleave",this.mouseleaveHandler),clearTimeout(this.stayTimeout),clearTimeout(this.starTimeout)}unloadSalesPopup(){this.starTimeout=setTimeout(()=>{this.showSalesPopup(),this.loadSalesPopup()},this.startTime)}startProgressbar(){this.progressbar&&this.progressbar.style.setProperty("animation-iteration-count","infinite")}stopProgressbar(){this.progressbar&&this.progressbar.style.removeProperty("animation-iteration-count")}loadSalesPopup(){this.removeAttribute("hidden"),this.ppType=="1"?(this.updateData(this.index),++this.index,this.index>this.max&&(this.index=0)):this.updateData(this.getRandomInit(this.min,this.max)),this.time.START=new Date().getTime(),this.time.END=this.time.START+this.stayTime,this.stayTimeout=setTimeout(()=>{clearTimeout(this.stayTimeout),this.unloadSalesPopup(),this.hideSalesPopup()},this.stayTime)}}customElements.define("hdt-sales-popup",SalesPopup);class ageVerificationModal extends HTMLElement{constructor(){super(),this.configs=JSON.parse(this.getAttribute("configs")),!(!Shopify.designMode&&getCookie("theme4:age-verify:"+this.configs.id)==="verified")&&(this.modal=this.querySelector("hdt-modal"),this.dialog=this.querySelector("dialog"),Shopify.designMode&&(this._shopifySection=this._shopifySection||this.closest(".shopify-section"),this._shopifySection.addEventListener("shopify:section:load",()=>this.showModal())))}connectedCallback(){Shopify.designMode||getCookie("theme4:age-verify:"+this.configs.id)!=="verified"&&(this.addEventListener("click",e=>{const el=e.target.closest("[data-action]");if(!el)return;const action=el.getAttribute("data-action");action==="verify"&&(e.preventDefault(),e.stopPropagation(),this.verifyAge()),action==="exit"&&(e.preventDefault(),e.stopPropagation(),this.exitSite())},{capture:!0}),this.dialog&&(this.allowBackdropClose=!1,this.dialog.addEventListener(`${dialogClose}`,()=>{this.allowBackdropClose&&this.hideModal()}),this.dialog.addEventListener("close",()=>{this.allowBackdropClose||this.modal&&this.modal.open&&this.modal.open()}),this.dialog.addEventListener("cancel",e=>{this.allowBackdropClose||(e.preventDefault(),e.stopPropagation(),this.exitSite())})),this.showModalWithDelay())}showModalWithDelay(){setTimeout(()=>this.showModal(),this.configs.time_delay*1e3)}setupScrollListener(){const fnShow=this.showModal.bind(this),docHeight=document.documentElement.scrollHeight-document.documentElement.clientHeight-500,onScroll=()=>{window.scrollY>=docHeight&&(fnShow(),window.removeEventListener("scroll",onScroll))};window.addEventListener("scroll",onScroll)}setupMouseLeaveListener(){const fnShow=this.showModal.bind(this);document.querySelector("body").addEventListener("mouseleave",fnShow)}showModal(){this.modal.open()}hideModal(){this.modal.close()}verifyAge(){if(this.configs.date_of_birth){const formRoot=(this.dialog||this).querySelector(".hdt-age-verify_content")||this.dialog||this,monthEl=formRoot.querySelector("#agemonth"),dayEl=formRoot.querySelector("#ageday"),yearEl=formRoot.querySelector("#ageyear"),showError=msg=>{let err=formRoot.querySelector(".hdt-age-error");if(!err){err=document.createElement("div"),err.className="hdt-age-error",err.style.cssText="color:#ef4444;margin-top:12px;font-size:13px;";const formWrap=formRoot.querySelector(".hdt-age-verify-form")||formRoot.querySelector(".hdt-content");formWrap?formWrap.insertAdjacentElement("afterend",err):formRoot.appendChild(err)}err.textContent=msg,err.style.display=""},clearError=()=>{const err=formRoot.querySelector(".hdt-age-error");err&&(err.textContent="",err.style.display="none")};if(!monthEl||!dayEl||!yearEl){showError("Please select your full date of birth.");return}if(monthEl.selectedIndex===0||dayEl.selectedIndex===0||yearEl.selectedIndex===0){showError("Please select your full date of birth.");return}const m=parseInt(monthEl.value,10),d=parseInt(dayEl.value,10),y=parseInt(yearEl.value,10),birth=new Date(y,m-1,d);if(!Number.isFinite(m)||!Number.isFinite(d)||!Number.isFinite(y)||birth.getFullYear()!==y||birth.getMonth()!==m-1||birth.getDate()!==d){showError("Please select your full date of birth.");return}const today=new Date,threshold=new Date(y+this.configs.age_limit,m-1,d);if(today0?Number.parseInt(this.configs.day_next_show):Number.parseInt(this.configs.day_next);setCookie("theme4:age-verify:"+this.configs.id,"verified",cookieDays),this._preventEscHandler&&(document.removeEventListener("keydown",this._preventEscHandler,!0),this._preventEscHandler=null),this._reopenOnClose&&(this.dialog&&this.dialog.removeEventListener("close",this._reopenOnClose,{once:!0}),this._reopenOnClose=null),this._blockOutsideClick&&(document.removeEventListener("click",this._blockOutsideClick,!0),this._blockOutsideClick=null),this._blockMouseHandlers&&Array.isArray(this._blockMouseHandlers)&&(this._blockMouseHandlers.forEach(({type,handler})=>{document.removeEventListener(type,handler,!0)}),this._blockMouseHandlers=null),this.allowBackdropClose=!0,this.hideModal()}exitSite(){const scope=this.dialog||this,root=scope.querySelector(".hdt-age-verify_content")||scope,headingEl=root.querySelector("h2");let descEl=root.querySelector(".hdt-text-base")||root.querySelector("p");const form=root.querySelector(".hdt-age-verify-form"),closeBtn=scope.querySelector('[ref="closeButton"]')||scope.querySelector(".hdt-dialog-btn__close");if(headingEl&&(headingEl.textContent="Access forbidden"),!descEl){descEl=document.createElement("div"),descEl.style.marginBottom="1.5rem";const container=root.querySelector(".hdt-content")||root;container.insertBefore(descEl,form||container.firstChild)}descEl.textContent="Your access is restricted because of your age.",form&&(form.style.display="none"),closeBtn&&(closeBtn.setAttribute("disabled","true"),closeBtn.style.display="none"),this._preventEscHandler||(this._preventEscHandler=e=>{e.key==="Escape"&&(e.preventDefault(),e.stopPropagation())},document.addEventListener("keydown",this._preventEscHandler,!0)),this._blockOutsideClick||(this._blockOutsideClick=e=>{this.dialog&&!this.dialog.contains(e.target)&&(e.preventDefault(),e.stopPropagation())},document.addEventListener("click",this._blockOutsideClick,!0)),this._blockMouseHandlers||(this._blockMouseHandlers=[],["click","mousedown","mouseup","mousemove","mouseover","mouseout","contextmenu","wheel","scroll","touchstart","touchmove","touchend","pointerdown","pointermove","pointerup"].forEach(type=>{const handler=e=>{e.preventDefault(),e.stopPropagation()};document.addEventListener(type,handler,!0),this._blockMouseHandlers.push({type,handler})})),this.dialog&&this.modal&&!this._reopenOnClose&&(this._reopenOnClose=()=>{this.modal.open&&this.modal.open()},this.dialog.addEventListener("close",this._reopenOnClose,{once:!0}))}}customElements.define("sys-age-verify",ageVerificationModal);var createCartPromise=()=>new Promise(async resolve=>{resolve(await(await fetch(`${Shopify.routes.root}cart.js`)).json())}),_upate_qty,upate_qty_fn;class QuickOrderList extends HTMLElement{constructor(){super();const ON_CHANGE_DEBOUNCE_TIMER=300;this.actions={add:"ADD",update:"UPDATE"},this.quickOrderListId="#"+this.id,this.sectionId=this.dataset.sectionId,this.is_cart_update=!0,this.updateThink();const debouncedOnChange=debounce(event=>{this.onChange(event)},ON_CHANGE_DEBOUNCE_TIMER);this.addEventListener("change",debouncedOnChange.bind(this)),getterAdd(_upate_qty,this)}onSubmit(event){event.preventDefault()}connectedCallback(){document.addEventListener($4("hdt-cart-drawer")?cartUpdate:"variant:add",this.fetchQuickOrder.bind(this))}updateThink(){this.items_in_cart=$4("[update_items_in_cart]",this),this.items_price_in_cart=$4("[update_items_price_in_cart]",this),$4("form#QuickOrderList",this).addEventListener("submit",this.onSubmit.bind(this))}async fetchQuickOrder(){if(!this.is_cart_update)return;const section_data=await fetch(`${window.location.pathname}?section_id=${this.sectionId}`).then(r=>r.text()),sourceQty=new DOMParser().parseFromString(section_data,"text/html").querySelector(this.quickOrderListId);$4("form#QuickOrderList",this).removeEventListener("submit",this.onSubmit.bind(this)),this.innerHTML=sourceQty.innerHTML,document.dispatchEvent(new CustomEvent(currencyUpdate)),this.updateThink()}onChange(event){const inputValue=parseInt(event.target.value),cartQuantity=parseInt(event.target.dataset.cartQuantity),index=event.target.dataset.index,quantity=inputValue-cartQuantity;cartQuantity>0?this.updateQuantity(index,inputValue,this.actions.update):this.updateQuantity(index,quantity,this.actions.add)}onLoading(id){$4(`#Variant-${id} [price_loading]`,this)?.setAttribute("aria-busy",!0),$$4("#hdt-quick-order-list-total .hdt-btn-loading__svg",this).forEach(el=>el.setAttribute("aria-busy",!0))}deLoading(id){$4(`#Variant-${id} [price_loading]`,this)?.setAttribute("aria-busy",!1),$$4("#hdt-quick-order-list-total .hdt-btn-loading__svg",this).forEach(el=>el.setAttribute("aria-busy",!1))}removeButton(id,quantity){quantity!==0?$4(`#Variant-${id} hdt-quick-order-list-remove-button`,this).removeAttribute("hidden"):$4(`#Variant-${id} hdt-quick-order-list-remove-button`,this).setAttribute("hidden","")}updateInCart(id,variant_in_cart){$4(`#Variant-${id} .hdt-quantity__rules-cart`,this).removeAttribute("hidden");let variant_qty_cart=$4(`#Variant-${id} .hdt-quantity-cart`,this),variant_total=$4(`#Variant-${id} [variant_update_price]`,this);if(variant_in_cart?.length!==0&&variant_in_cart){let variant_total_price=parseFloat(variant_in_cart.original_line_price);variant_qty_cart.innerText=variant_in_cart.quantity,variant_total.innerText=formatMoney(variant_total_price,themeHDN.settings.currencyFormat),variant_total.setAttribute("data-variant-price",variant_total_price)}else variant_qty_cart.innerText=0,variant_total.innerText=formatMoney(0,themeHDN.settings.currencyFormat),variant_total.setAttribute("data-variant-price",0),$4(`#Variant-${id} .hdt-quantity__rules-cart`,this).setAttribute("hidden","");this.removeT4CrurrencyData(variant_total)}updateCartQty(id,quantity){$4(`#Variant-${id}`,this).setAttribute("data-cart-qty",quantity)}removeT4CrurrencyData(el,dataset=el.dataset){for(const[key,value]of Object.entries(dataset))key.toLowerCase().indexOf("currency")>=0&&delete el.dataset[key]}updateTotalInCart(){let items_total=0,items_price=0;$$4("[data-cart-quantity]",this).forEach(item=>items_total+=parseInt(item.getAttribute("data-cart-quantity"))),this.items_in_cart.innerText=items_total,parseInt(items_total)>0?this.items_in_cart.setAttribute("qty-cart-show",""):this.items_in_cart.removeAttribute("qty-cart-show"),$$4("[data-variant-price]",this).forEach(price=>items_price+=parseFloat(price.getAttribute("data-variant-price"))),this.items_price_in_cart.innerText=formatMoney(items_price,themeHDN.settings.currencyFormat),this.removeT4CrurrencyData(this.items_price_in_cart),document.dispatchEvent(new CustomEvent(currencyUpdate))}fetchConfig(type="json"){return{method:"POST",headers:{"Content-Type":"application/json",Accept:`application/${type}`}}}updateQuantity(id,quantity,action){this.is_cart_update=!1,document.dispatchEvent(new CustomEvent("theme:loading:doing",{bubbles:!0})),this.removeButton(id,quantity),this.onLoading(id);let bundleSections=[],routeUrl=`${Shopify.routes.root}cart/change.js`,body=JSON.stringify({quantity,id,sections_url:window.location.pathname,sections:bundleSections.join(",")}),fetchConfigType;action===this.actions.add&&(fetchConfigType="javascript",routeUrl=`${Shopify.routes.root}cart/add.js`,body=JSON.stringify({items:[{quantity:parseInt(quantity),id:parseInt(id)}],sections_url:window.location.pathname,sections:bundleSections.join(",")})),fetch(`${routeUrl}`,{...this.fetchConfig(fetchConfigType),body}).then(response=>response.text()).then(state=>{let cartContent=JSON.parse(state);const quantityElement=document.getElementById(`Quantity-${id}`);quantity===0&&this.resetQuantityInput(id,quantityElement,!0),quantityElement.setAttribute("data-cart-quantity",quantity),getterRunFn(_upate_qty,this,upate_qty_fn).call(this,cartContent,parseInt(id),action,bundleSections),this.updateCartQty(id,quantity)}).catch(error=>{console.log(error)}).finally(()=>{this.updateTotalInCart(),document.dispatchEvent(new CustomEvent(currencyUpdate)),document.dispatchEvent(new CustomEvent("theme:loading:done",{bubbles:!0})),this.deLoading(id),document.dispatchEvent(new CustomEvent(cartReload)),this.is_cart_update=!0})}updateMultipleQty(items2){let bundleSections=[this.sectionId];const body=JSON.stringify({updates:items2,sections_url:window.location.pathname,sections:bundleSections.join(",")});this.setAttribute("aria-busy",!0),fetch(`${Shopify.routes.root}cart/update.js`,{...this.fetchConfig(void 0),body}).then(response=>response.json()).then(response=>{const section_data=response?.sections[this.sectionId],sourceQty=new DOMParser().parseFromString(section_data,"text/html").querySelector(this.quickOrderListId);$4("form#QuickOrderList",this).removeEventListener("submit",this.onSubmit.bind(this)),this.innerHTML=sourceQty.innerHTML,document.dispatchEvent(new CustomEvent(currencyUpdate)),this.updateThink(),document.dispatchEvent(new CustomEvent(cartReload))}).catch(error=>{console.log(error)}).finally(()=>{this.setAttribute("aria-busy",!1)})}resetQuantityInput(id,quantityElement,resetValue){const input=quantityElement??document.getElementById(`Quantity-${id}`);input.value=input.getAttribute("value"),resetValue?input.value=0:input.value=input.getAttribute("value")}updateError(updatedValue,id){let message="";typeof updatedValue>"u"?message=window.cartStrings.error:message=window.cartStrings.quantityError.replace("[quantity]",updatedValue),this.updateLiveRegions(id,message)}updateLiveRegions(id,message){const variantItemError=this.getElementById("Quick-order-list-item-error");variantItemError&&($4(".hdt-variant-item__error-text",variantItemError).innerHTML=message,variantItemError.removeAttribute("hidden"))}}_upate_qty=new WeakSet,upate_qty_fn=async function(cartContent,id,action){const variant_in_cart=cartContent.items.find(item=>item.variant_id===id);this.updateInCart(id,variant_in_cart)},customElements.define("hdt-quick-order-list",QuickOrderList);class QuickOrderListRemoveButton extends HTMLElement{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault(),this.closest("hdt-quick-order-list").updateQuantity(this.dataset.index,0),this.setAttribute("hidden","")})}}customElements.define("hdt-quick-order-list-remove-button",QuickOrderListRemoveButton);class QuickOrderListRemoveAllButton extends HTMLElement{constructor(){super()}connectedCallback(){this.quickOrderList=this.closest("hdt-quick-order-list"),this.updateStatus(),this.addEventListener("click",event=>{event.preventDefault(),this.quickOrderList.updateMultipleQty(this.getValue().items,this.getValue().list_variants),this.setAttribute("hidden","")})}updateStatus(){}getValue(){const allVariants=Array.from(this.quickOrderList.querySelectorAll("[data-variant-id]")),items2={},list_variants=[];let hasVariantsInCart=!1;return allVariants.forEach(variant=>{parseInt(variant.dataset.cartQty)>0&&(hasVariantsInCart=!0,items2[parseInt(variant.dataset.variantId)]=0,list_variants.push(variant.dataset.variantId))}),{items:items2,list_variants,hasVariantsInCart}}}customElements.define("hdt-quick-order-list-remove-all-button",QuickOrderListRemoveAllButton),document.addEventListener("DOMContentLoaded",function(){const stickyATC=document.querySelector('[data-sticky-mode="hdt_show_scrolls_outside_the_scope_of_the_form"]');if(stickyATC){let productForm=document.getElementById(stickyATC.getAttribute("form"));if(productForm||(productForm=document.querySelector('.hdt-product-form, form[action*="/cart/add"]')),productForm){let checkFormVisibility=function(){productForm.getBoundingClientRect().bottom>50?stickyATC.classList.remove("show"):stickyATC.classList.add("show"),ticking=!1},onScroll=function(){ticking||(requestAnimationFrame(checkFormVisibility),ticking=!0)},ticking=!1;window.addEventListener("scroll",onScroll),checkFormVisibility()}}});class ToastNotification{constructor(){this.container=null,this.init()}init(){document.querySelector(".toast-container")?this.container=document.querySelector(".toast-container"):(this.container=document.createElement("div"),this.container.className="toast-container",document.body.appendChild(this.container))}show(message,type="info",title="Notification",duration=5e3){const toast2=this.createToast(message,type,title);return this.container.appendChild(toast2),setTimeout(()=>{toast2.classList.add("show")},10),duration>0&&setTimeout(()=>{this.hide(toast2)},duration),toast2}createToast(message,type,title){const toast2=document.createElement("div");return toast2.className=`toast ${type}`,toast2.innerHTML=`
${this.getIcon(type)}
${title}
${message}
`,toast2.querySelector(".toast-close").addEventListener("click",()=>{this.hide(toast2)}),toast2}hide(toast2){toast2.classList.add("hide"),setTimeout(()=>{toast2.parentNode&&toast2.parentNode.removeChild(toast2)},300)}getIcon(type){const icons={error:"!",success:"\u2713",warning:"!",info:"i"};return icons[type]||icons.info}static success(message,title="Success"){return new ToastNotification().show(message,"success",title)}static error(message,title="Error"){return new ToastNotification().show(message,"error",title)}static warning(message,title="Warning"){return new ToastNotification().show(message,"warning",title)}static info(message,title="Info"){return new ToastNotification().show(message,"info",title)}}const toast=new ToastNotification;window.addEventListener("cart:error",event=>{let errorMessage=window.themeHDN.extras.cart.error_message;event.detail&&event.detail.data.message?errorMessage=event.detail.data.message:event.detail&&event.detail.data.error?errorMessage=event.detail.data.error:typeof event.detail=="string"&&(errorMessage=event.detail),ToastNotification.error(errorMessage,window.themeHDN.extras.cart.toast_title)});class ConfettiElement extends HTMLElement{constructor(){super(),this.canvas=null,this.ctx=null,this.W=0,this.H=0,this.mp=150,this.particles=[],this.angle=0,this.tiltAngle=0,this.confettiActive=!0,this.animationComplete=!0,this.deactivationTimerHandler=null,this.reactivationTimerHandler=null,this.animationHandler=null,this.whenShow=null,this.hideAfterShow=null,this.isShow=[],this.particleColors={colorOptions:["DodgerBlue","OliveDrab","Gold","pink","SlateBlue","lightblue","Violet","PaleGreen","SteelBlue","SandyBrown","Chocolate","Crimson"],colorIndex:0,colorIncrementer:0,colorThreshold:10,getColor:function(){return this.colorIncrementer>=10&&(this.colorIncrementer=0,this.colorIndex++,this.colorIndex>=this.colorOptions.length&&(this.colorIndex=0)),this.colorIncrementer++,this.colorOptions[this.colorIndex]}},this.handleResize=this.handleResize.bind(this)}connectedCallback(){this.init(),this.setupEventListeners()}disconnectedCallback(){this.cleanup(),this.removeEventListeners()}createConfettiParticle(color){const ctx=this.ctx,W=this.W,H=this.H,mp=this.mp;return{x:Math.random()*W,y:Math.random()*H-H,r:this.randomFromTo(10,30),d:Math.random()*mp+10,color,tilt:Math.floor(Math.random()*10)-10,tiltAngleIncremental:Math.random()*.07+.05,tiltAngle:0,draw:function(){return ctx.beginPath(),ctx.lineWidth=this.r/2,ctx.strokeStyle=this.color,ctx.moveTo(this.x+this.tilt+this.r/4,this.y),ctx.lineTo(this.x+this.tilt,this.y+this.tilt+this.r/4),ctx.stroke()}}}init(){this.setGlobals(),window.addEventListener("resize",this.handleResize)}setupEventListeners(){this.handleConfettiStart=this.handleConfettiStart.bind(this),this.handleConfettiPause=this.handleConfettiPause.bind(this),document.addEventListener("confetti:start",this.handleConfettiStart),document.addEventListener("confetti:pause",this.handleConfettiPause),document.querySelector("#CartDrawer")?.addEventListener(dialogClose,()=>{this.pause()}),document.addEventListener(progressBarChange,event=>{this.handleProgressBarChange(event)})}removeEventListeners(){document.removeEventListener("confetti:start",this.handleConfettiStart),document.removeEventListener("confetti:pause",this.handleConfettiPause),document.querySelector("#CartDrawer").removeEventListener(dialogClose,()=>{this.pause()})}handleProgressBarChange(event){if(clearTimeout(this.whenShow),clearTimeout(this.hideAfterShow),this.isShow.length==1&&parseInt(event.detail.rangeValue)==1){this.handlePauseAnimation();return}parseInt(event.detail.rangeValue)==1&&this.isShow.length<=1?(this.showPopover(),this.start(),this.isShow.push(event.detail.rangeValue)):this.isShow.pop(1),this.handlePauseAnimation()}handlePauseAnimation(){this.whenShow=setTimeout(()=>{this.pause(),this.hideAfterShow=setTimeout(()=>{this.hidePopover()},5e3)},3e3)}handleConfettiStart(event){event.detail&&event.detail.target&&event.detail.target!==this||(this.showPopover(),this.start())}handleConfettiPause(event){clearTimeout(this.whenShow),clearTimeout(this.hideAfterShow),!(event.detail&&event.detail.target&&event.detail.target!==this)&&(this.pause(),this.hideAfterShow=setTimeout(()=>{this.hidePopover()},5e3))}cleanup(){window.removeEventListener("resize",this.handleResize),this.removeEventListeners(),this.clearTimers(),this.stopConfetti(),this.hideTimeout&&clearTimeout(this.hideTimeout)}handleResize(){this.W=window.innerWidth,this.H=window.innerHeight,this.canvas&&(this.canvas.width=this.W,this.canvas.height=this.H)}setGlobals(){let canvas=this.querySelector("#confettiCanvas");canvas||(canvas=document.createElement("canvas"),canvas.id="confettiCanvas",canvas.style.cssText="position: fixed; top: 0; left: 0; display: none; z-index: 9999; pointer-events: none;",this.appendChild(canvas)),this.canvas=canvas,this.ctx=this.canvas.getContext("2d"),this.W=window.innerWidth,this.H=window.innerHeight,this.canvas.width=this.W,this.canvas.height=this.H}initializeConfetti(){if(!this.canvas||!this.ctx){console.error("Canvas not initialized");return}this.clearTimers(),this.canvas.style.display="block",this.particles=[],this.animationComplete=!1,this.confettiActive=!0;for(let i=0;ithis.W+20||particle.x<-20||particle.y>this.H)&&this.confettiActive&&(index%5>0||index%2===0?this.repositionParticle(particle,Math.random()*this.W,-10,Math.floor(Math.random()*10)-10):Math.sin(this.angle)>0?this.repositionParticle(particle,-5,Math.random()*this.H,Math.floor(Math.random()*10)-10):this.repositionParticle(particle,this.W+5,Math.random()*this.H,Math.floor(Math.random()*10)-10))}stepParticle(particle,particleIndex){particle.tiltAngle+=particle.tiltAngleIncremental,particle.y+=(Math.cos(this.angle+particle.d)+3+particle.r/2)/2,particle.x+=Math.sin(this.angle),particle.tilt=Math.sin(particle.tiltAngle-particleIndex/3)*15}repositionParticle(particle,xCoordinate,yCoordinate,tilt){particle.x=xCoordinate,particle.y=yCoordinate,particle.tilt=tilt}startConfetti(){this.animationHandler&&(cancelAnimationFrame(this.animationHandler),this.animationHandler=null),this.W=window.innerWidth,this.H=window.innerHeight,this.canvas&&(this.canvas.width=this.W,this.canvas.height=this.H);const animloop=()=>this.animationComplete?null:(this.animationHandler=requestAnimationFrame(animloop),this.draw());animloop()}clearTimers(){this.reactivationTimerHandler&&clearTimeout(this.reactivationTimerHandler),this.animationHandler&&(cancelAnimationFrame(this.animationHandler),this.animationHandler=null)}deactivateConfetti(){this.confettiActive=!1}stopConfetti(){this.animationComplete=!0,this.ctx&&this.ctx.clearRect(0,0,this.W,this.H),this.canvas&&(this.canvas.style.display="none")}restartConfetti(){this.clearTimers(),this.stopConfetti(),this.reactivationTimerHandler=setTimeout(()=>{this.confettiActive=!0,this.animationComplete=!1,this.initializeConfetti()},100)}forceStopConfetti(){this.clearTimers(),this.stopConfetti()}start(){(this.animationComplete||!this.confettiActive)&&this.initializeConfetti()}pause(){this.deactivateConfetti()}stop(){this.forceStopConfetti()}restart(){this.restartConfetti()}}customElements.define("confetti-element",ConfettiElement); //# sourceMappingURL=/cdn/shop/t/7/assets/custom.js.map?v=152237979489454072281778520304