import{Segment}from"@dna/analytics";const registerGlobal=window.DNARegisterGlobal;export const getProductRecommendations=async(productId,limit=10,intent="related")=>{const response=await fetch(`${window.Shopify.routes.root}recommendations/products.json?product_id=${productId}&limit=${limit}&intent=${intent}`),{products}=await response.json();return products},validateNumber=value=>Number.isFinite(Number.parseFloat(value));export function minorToMajorUnit(priceInMinorUnit){return validateNumber(priceInMinorUnit)?(priceInMinorUnit/100).toFixed(2):!1}export function renderPrice(rawPrice,options={includeCurrencySymbol:!0,convertToUSD:!1}){const getMinorUnits=window.__DNA_GLOBAL__?.currency.getMinorUnits,currencyCode=Shopify?.currency?.active||"USD",locale=Shopify?.locale||"en-US";let numericPrice=rawPrice;if(typeof rawPrice=="string"&&(numericPrice=Number(rawPrice.replaceAll(/[^0-9,\.]/g,"")),Number.isNaN(numericPrice)&&console.warn(`Could not render price ${rawPrice}`)),options.convertToUSD){const convertedPrice=numericPrice/window.Shopify.currency.rate;numericPrice=Number(convertedPrice.toFixed())}window.__DNA_GLOBAL__?.currency.no_subunits&&(numericPrice/=100);const normalizedPrice=numericPrice/10**getMinorUnits(currencyCode),formatterOptions={};return options.includeCurrencySymbol&&(formatterOptions.style="currency",formatterOptions.currency=currencyCode,formatterOptions.currencyDisplay="narrowSymbol"),normalizedPrice%1===0&&(formatterOptions.minimumFractionDigits=0,formatterOptions.maximumFractionDigits=0),createPriceFormatter(locale,formatterOptions).format(normalizedPrice)}function createPriceFormatter(locale,options){return new Intl.NumberFormat(locale,options)}export function snakeToCamel(string){return string.replace(/(_\w)/g,matches=>matches[1].toUpperCase())}export function removeTextBeforeCharacterAndTrim(source,character){if(typeof source!="string")return"";const index=source.indexOf(character);return index===-1?source:source.slice(index+1).trim()}export function debounce(func,delay){let timer;return function(...args){clearTimeout(timer),timer=setTimeout(()=>{func.apply(this,args)},delay)}}export function isStringifiedArray(string){if(typeof string!="string")return!1;if(string.startsWith("[")&&string.endsWith("]"))try{const potentialArray=JSON.parse(string);return Array.isArray(potentialArray)}catch{return!1}return!1}export function openDrawer(id){document.dispatchEvent(new CustomEvent("dna:drawer:open",{detail:{id}}))}export function escapeHtml(html){const div=document.createElement("div");return div.textContent=html,div.innerHTML}export function notify(message,variant="primary",duration=3e3){const alert=Object.assign(document.createElement("sl-alert"),{variant,closable:!0,duration,innerHTML:` ${escapeHtml(message)} `});return document.body.append(alert),alert.toast()}window.notify=notify;export const addToCart=async(_items,openCart=!0,notifyFailure=!0)=>{let items=_items;Array.isArray(items)||(items=[items]);try{const response=await fetch(`${Shopify.routes.root}cart/add.js`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items})});if(!response.ok)throw new Error("Network response was not ok");const $cartStatusMessage=document.querySelector(".cart-status-message");$cartStatusMessage&&($cartStatusMessage.textContent="Item added to cart",setTimeout(()=>{$cartStatusMessage.textContent=""},5e3));const detail=await(await fetch(`${window.Shopify.routes.root}cart.js`)).json();document.dispatchEvent(new CustomEvent("dna:cart:refresh",{bubbles:!0,composed:!0,detail}));const metadataWarning="A product was added to the cart with incomplete metadata. There may be missing information visible in the cart or in analytics events.";for(const item of items)if(!item.properties||!item.properties._storefront_category){console.warn(metadataWarning);break}openCart&&document.dispatchEvent(new CustomEvent("dna:cart:open",{bubbles:!0,detail:response})),Segment.protect(()=>{if(detail.items.length){for(const cartItem of detail.items)for(const addedItem of items)if(addedItem.id&&cartItem.id){const addedItemId=addedItem.id.toString().toLowerCase().trim(),cartItemId=cartItem.id.toString().toLowerCase().trim();if(addedItemId===cartItemId){const addToCartAnalyticsData={brand:Segment.CONSTANTS.BRAND,cart_id:Segment.cartToken,category:splitProductName(cartItem.product_title).style,currency:Segment.presentmentCurrency,image_url:cartItem.featured_image.url,name:splitProductName(cartItem.product_title).color,price:Number(minorToMajorUnit(cartItem.price)),product_category:cartItem.properties._storefront_category?cartItem.properties._storefront_category:cartItem.tags?getCategoryFromTags(cartItem.tags):void 0,product_id:cartItem.product_id.toString(),quantity:1,shopify_product_id:cartItem.product_id.toString(),shopify_variant_id:cartItem.variant_id.toString(),sku:cartItem.sku,sku_short:getMasterSku(cartItem.sku),url:`${window.location.origin}/products/${cartItem.handle}`,variant:cartItem.variant_title};Segment.dataLayerPush(Segment.CONSTANTS.EVENTS.PRODUCT_ADDED,addToCartAnalyticsData),window.igEvents=window.igEvents||[],window.igEvents.push({event:Segment.CONSTANTS.EVENTS.PRODUCT_ADDED,properties:addToCartAnalyticsData})}}}})}catch(error){console.error(error.message),notifyFailure&¬ify("Failed to add to cart.","danger")}};export async function updateCartQuantity(_items,openCart=!0){let items=_items;Array.isArray(items)||(items=[items]);try{const updates={};for(const item of items)updates[item.id]=item.quantity;const response=await fetch(`${Shopify.routes.root}cart/update.js`,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify({updates})});if(!response.ok)throw new Error("Error updating quantity in cart");openCart&&document.dispatchEvent(new CustomEvent("dna:cart:open",{bubbles:!0,composed:!0,detail:response}));const detail=await response.json();document.dispatchEvent(new CustomEvent("dna:cart:refresh",{bubbles:!0,composed:!0,detail}))}catch(error){throw console.error(error.message),error}}export function interpolate(template,replacements){return template.replace(/\{\{\s*(\w+)\s*\}\}/g,(_,placeholder)=>replacements[placeholder]||_)}export function getChildSlot(shadowRoot=null,name="",firstOnly=!1){const children=shadowRoot?.querySelector("slot")?.assignedElements({flatten:!0}).filter(node=>node.matches(name))||[];return firstOnly?(children||[])[0]:children}export function one(selector,_parent){let parent=_parent;return parent==null&&(parent=document),parent.querySelector(selector)}export function all(selector,_parent){let parent=_parent;parent==null&&(parent=document);const selection=parent.querySelectorAll(selector);return Array.prototype.slice.call(selection)}export function toggle(element,classes=[]){for(_class of classes)element.classList.toggle(_class)}export const pauseAllMedia=()=>{const $youTubeVideos=document.querySelectorAll(".js-youtube");for(const $video of $youTubeVideos)$video.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}',"*");const $vimeoVideos=document.querySelectorAll(".js-vimeo");for(const $video of $vimeoVideos)$video.contentWindow.postMessage('{"method":"pause"}',"*");const $videos=document.querySelectorAll("video");for(const $video of $videos)$video.pause();const $models=document.querySelectorAll("product-model");for(const $model of $models)$model.modelViewerUI?.pause()},throttle=(callback,limit)=>{let waiting=!1;return function(...args){waiting||(callback.apply(this,args),waiting=!0,setTimeout(()=>{waiting=!1},limit))}},serializeForm=form=>{const obj={},formData=new FormData(form);for(const key of formData.keys()){const regex=/(?:^(properties\[))(.*?)(?:\]$)/;regex.test(key)?(obj.properties=obj.properties||{},obj.properties[regex.exec(key)[2]]=formData.get(key)):obj[key]=formData.get(key)}return JSON.stringify(obj)},fetchConfig=(type="json",method="POST")=>({method,headers:{"Content-Type":"application/json",Accept:`application/${type}`}}),isTouch=()=>"ontouchstart"in window||navigator.maxTouchPoints;class ViewportObserver{constructor(){this.listeners=[],this.mediaQueries={mobile:window.matchMedia("(max-width: 768px)"),tablet:window.matchMedia("(min-width: 768px) and (max-width: 1024px)"),desktop:window.matchMedia("(min-width: 1024px) and (max-width: 1440px)"),widescreen:window.matchMedia("(min-width: 1440px)")},this.currentViewport=this.getCurrentViewport();for(const mediaQuery of Object.values(this.mediaQueries))mediaQuery.addEventListener("change",this._handleMediaQueryChange)}getCurrentViewport(){if(this.mediaQueries.mobile.matches)return"mobile";if(this.mediaQueries.tablet.matches)return"tablet";if(this.mediaQueries.desktop.matches)return"desktop";if(this.mediaQueries.widescreen.matches)return"widescreen"}_handleMediaQueryChange=()=>{const newViewport=this.getCurrentViewport();newViewport!==this.currentViewport&&(this.currentViewport=newViewport,this.notifyListeners())};addListener(listener){this.listeners.push(listener)}removeListener(listener){this.listeners=this.listeners.filter(_listener=>_listener!==listener)}notifyListeners(){for(const listener of this.listeners)listener(this.currentViewport)}}export const viewportObserver=new ViewportObserver,deepClone=obj=>JSON.parse(JSON.stringify(obj));export function handleize(str){return str.normalize("NFD").replace(/[\[\]'()"]+/g,"").replace(/[\u0300-\u036f]/g,"").replace(/([^\w]+|\s+)/g,"-").replace(/\-\-+/g,"-").replace(/(^-+|-+$)/g,"").toLowerCase()}export const decode=str=>decodeURIComponent(str).replace(/\+/g," "),externalVideoEmbedSrc=(host,id,autoplay=!1,controls=!1,loop=!1)=>{let src="";const queryParam=(param,value)=>`${param}=${Number(value)}`,autoplayParam=queryParam("autoplay",autoplay),controlsParam=queryParam("controls",controls),loopParam=queryParam("loop",loop),queryParams=`${autoplayParam}&${controlsParam}&${loopParam}`;let muted;switch(host){case"youtube":muted="mute=1&",src=`https://www.youtube.com/embed/${id}?${queryParams}&enablejsapi=1&modestbranding=1&${muted}cc_load_policy=0&disablekb=0&fs=1&iv_load_policy=1&playsinline=1&rel=1&widgetid=1`;break;case"vimeo":muted="muted=1&",src=`https://player.vimeo.com/video/${id}?${queryParams}&${muted}byline=0&playsinline=1&title=0`;break;default:console.error('Invalid host value (must be "youtube" or "vimeo")')}return src},getPreviousSibling=(element,selector)=>{let sibling=element.previousElementSibling;if(!selector)return null;for(;sibling;){if(sibling.matches(selector))return sibling;sibling=sibling.previousElementSibling}},t=(namespace,fallback)=>window.langMessages[namespace]?window.langMessages[namespace]:fallback;export class HTMLUpdateUtility{#preProcessCallbacks=[];#postProcessCallbacks=[];addPreProcessCallback(callback){this.#preProcessCallbacks.push(callback)}addPostProcessCallback(callback){this.#postProcessCallbacks.push(callback)}viewTransition(oldNode,newContent){for(const callback of this.#preProcessCallbacks)callback(newContent);const newNode=oldNode.cloneNode();HTMLUpdateUtility.setInnerHTML(newNode,newContent.innerHTML),oldNode.parentNode.insertBefore(newNode,oldNode),oldNode.style.display="none";for(const callback of this.#postProcessCallbacks)callback(newNode);setTimeout(()=>oldNode.remove(),1e3)}static setInnerHTML(element,html){element.innerHTML=html;const $scripts=element.querySelectorAll("script");for(const $oldScriptTag of $scripts){const $newScriptTag=document.createElement("script");for(const attribute of Array.from($oldScriptTag.attributes))$newScriptTag.setAttribute(attribute.name,attribute.value);$newScriptTag.appendChild(document.createTextNode($oldScriptTag.innerHTML)),$oldScriptTag.parentNode.replaceChild($newScriptTag,$oldScriptTag)}}}export function splitProductName(title){if(!title||typeof title!="string")return{style:"",color:""};const titleArray=title.split("-"),style=titleArray[0]?.trim()||"",color=titleArray[1]?.trim()||"";return{style,color}}export function getMasterSku(sku=""){if(typeof sku!="string")return;const elements=sku.split("_");return elements.pop(),elements.join("_")}export function getCategoryFromTags(tags=[]){const result=tags.find(tag=>tag.includes("storefront:category:"));return result?result.split("storefront:category:")[1]:!1}export function filterObjectKeys(obj,keysToKeep){const keysSet=new Set(keysToKeep);return Object.fromEntries(Object.entries(obj).filter(([key])=>keysSet.has(key)))}export function loadChat(context){if(Segment.protect(Segment.track(Segment.CONSTANTS.EVENTS.CHAT_CLICKED,{chat_context:context})),typeof Gladly<"u")Gladly.show();else{const waitForGladly=({key,sub},callback)=>{window[key]?sub&&window[key][sub]?setTimeout(()=>{waitForGladly({key,sub},callback)},100):callback():setTimeout(()=>{waitForGladly({key,sub},callback)},100)};waitForGladly({key:"Gladly",sub:"show"},()=>{Gladly.show()})}}export function addLeadingZero(number){return number<10&&number>=0?number.toString().padStart(2,"0"):number.toString()}export function formattedIterableDate(){const date=new Date,utcYear=date.getUTCFullYear().toString(),utcMonth=addLeadingZero(date.getUTCMonth()+1),utcDay=addLeadingZero(date.getUTCDate()),utcHours=addLeadingZero(date.getUTCHours()),utcMinutes=addLeadingZero(date.getUTCMinutes()),utcSeconds=addLeadingZero(date.getUTCSeconds());return`${utcYear}-${utcMonth}-${utcDay} ${utcHours}:${utcMinutes}:${utcSeconds} +00:00`}export function getLineItemProperties(product,variant,properties){let lineItemProperties={};if(properties){const entries=new Map(properties);lineItemProperties=Object.fromEntries(entries)}else{const returnExperience=product.metafields?.rothys?.return_rules;returnExperience&&(lineItemProperties._LPROP=returnExperience);const preorderMessage=product.metafields?.rothys?.preorder_backorder_experience||variant?.metafields?.rothys?.preorder_backorder_experience,preorderShipDate=product.metafields?.rothys?.estimated_ship_date||variant?.metafields?.rothys?.estimated_ship_date;if(preorderMessage&&(lineItemProperties._preorder_message=preorderMessage,lineItemProperties._preorder_ship_date=preorderShipDate),!__DNA_GLOBAL__.customerB2B){const parsedMetafieldValue=Number.parseInt(product?.metafields?.rothys?.maximum_order_quantity,10);lineItemProperties._limit=Number.isNaN(parsedMetafieldValue)?__DNA_GLOBAL__.b2cMaxOrderQuantity:parsedMetafieldValue}if(product.tags?.length){const storefrontCategory=getCategoryFromTags(product.tags);storefrontCategory&&(lineItemProperties._storefront_category=storefrontCategory)}variant?.variantMedia&&(lineItemProperties._gift_card_image=variant.variantMedia[0].url);const variantInventoryQuantity=variant?.quantityAvailable||variant?.inventory_quantity;(variantInventoryQuantity&&variantInventoryQuantity<=5||variant?.low_stock)&&(lineItemProperties._low_stock=!0),variant?.compareAtPrice&&Number(variant?.compareAtPrice)!==0?lineItemProperties._compare_at_price=variant?.compareAtPrice:product?.compareAtPrice&&Number(product?.compareAtPrice)!==0&&(lineItemProperties._compare_at_price=product?.compareAtPrice)}return lineItemProperties}export function getUniqueSizeMappingRegions(metaobjects){const sizeMappingRegions=metaobjects.map(metaobject=>metaobject?.fields?.size_mapping_region??null);return[...new Set(sizeMappingRegions.filter(Boolean))]}export function buildSizeMap(metaobjects,countries){const region=countries.us?.fields.size_mapping_region||"US";return metaobjects.reduce((acc,item)=>{const{fields}=item,{type}=fields,system=type.toLowerCase(),sizingKeyRegex=/[a-z]{2}_size/,map=Object.keys(fields).filter(key2=>key2.match(sizingKeyRegex)).reduce((acc2,key2)=>(acc2[key2.split("_")[0].toUpperCase()]=Number.parseFloat(fields[key2]),acc2),{});acc[system]||(acc[system]={});const key=__DNA_GLOBAL__.enableLocalSizingDropDown?map[region]:map.US;return acc[system][key]=map,acc},{})}export function richTextToHTML(content){const parsedContent=JSON.parse(content);let html="";for(const node of parsedContent.children)switch(node.type){case"heading":html+=`${node.children[0].value}`;break;case"list":html+=`<${node.listType==="unordered"?"ul":"ol"}>`;for(const item of node.children)html+=`
  • ${item.children[0].value}
  • `;html+=`<${node.listType==="unordered"?"/ul":"/ol"}>`;break;case"paragraph":html+="

    ";for(const item of node.children)item.type==="text"&&item.bold?html+=`${item.value}`:item.type==="text"&&item.italic?html+=`${item.value}`:item.type==="text"&&(html+=`${item.value} `),item.type==="link"&&item.bold?html+=`${item.children[0].value}`:item.type==="link"&&item.italic?html+=`${item.children[0].value}`:item.type==="link"&&(html+=`${item.children[0].value}`);html+="

    ";break}return html}export const igReady=new Promise(res=>{window.igData&&typeof window.igData.getVersion=="function"?res(window.igData):window.addEventListener("ig:ready",()=>{res(window.igData)})});export async function igGetExperimentControl(experimentIds={}){const igData=await igReady,experimentId=window.location.hostname==="rothys.com"?experimentIds.production:experimentIds.staging;return igData.user?.getVariation(experimentId)?.isControl??!0}export async function igGetExperimentVariationName(experimentIds={}){const igData=await igReady,experimentId=window.location.hostname==="rothys.com"?experimentIds.production:experimentIds.staging;return igData.user?.getVariation(experimentId)?.name}export function getSectionPosition(section){if(!section)return;const $sections=document.querySelectorAll("#main .shopify-section");return Array.from($sections).indexOf(section)+1||null}let loadedBadges;export async function getBadgeMetaobject(){return loadedBadges||(loadedBadges=__DNA_GLOBAL__.StorefrontClient.GetAllMetaobjectsByType("badges")),loadedBadges}export function getHaversineDistance(origin,destination){const originLatitudeRadians=origin.latitude*(Math.PI/180),destinationLatitudeRadians=destination.latitude*(Math.PI/180),diffLatitude=destinationLatitudeRadians-originLatitudeRadians,diffLongitude=(destination.longitude-origin.longitude)*(Math.PI/180);return 2*3958.8*Math.asin(Math.sqrt(Math.sin(diffLatitude/2)*Math.sin(diffLatitude/2)+Math.cos(originLatitudeRadians)*Math.cos(destinationLatitudeRadians)*Math.sin(diffLongitude/2)*Math.sin(diffLongitude/2)))}export function getStoreHours(store){const hours=store.hours_json;if(typeof hours!="object")return;const date=new Date,formattedDate=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",timeZone:hours.timezone}).format(date),now=new Date(formattedDate),currentDay=now.getDay(),currentHour=now.getHours()*100;let storeDay,storeNextDay,storeOpenHour,storeCloseHour;const setOpeningInfo=(day,nextDay)=>{storeDay=hours[day],storeNextDay=hours[nextDay],storeDay.open.length&&(storeOpenHour=Number.parseInt(storeDay.open.replaceAll(":","").replaceAll("am","").replaceAll("pm",""))),storeDay.close.length&&(storeCloseHour=Number.parseInt(storeDay.close.replaceAll(":","").replaceAll("am","").replaceAll("pm","")))};switch(currentDay){case 0:setOpeningInfo("sunday","monday");break;case 1:setOpeningInfo("monday","tuesday");break;case 2:setOpeningInfo("tuesday","wednesday");break;case 3:setOpeningInfo("wednesday","thursday");break;case 4:setOpeningInfo("thursday","friday");break;case 5:setOpeningInfo("friday","saturday");break;case 6:setOpeningInfo("saturday","sunday");break}return store.open_now=!1,currentHour>=storeOpenHour&¤tHour{const insertBeforeSlide=Array.from(carousel.querySelectorAll("sl-carousel-item"))[2]||null;insertBeforeSlide?.parentNode?insertBeforeSlide.parentNode.insertBefore(slideNode,insertBeforeSlide):carousel.appendChild(slideNode)}),setTimeout(()=>{slideNode.classList.remove("hidden"),document.querySelector("dna-announcement-bar").style.color=textColor,document.querySelector("dna-announcement-bar").style.background=backgroundColor;const newIndex=Array.from(carousel.querySelectorAll("sl-carousel-item")).indexOf(slideNode)-1;carousel.goToSlide(newIndex)},1e3)}registerGlobal(splitProductName,"splitProductName","utils"),registerGlobal(renderPrice,"renderPrice","utils"),registerGlobal(formattedIterableDate,"formattedIterableDate","utils"),registerGlobal(getSectionPosition,"getSectionPosition","utils"),registerGlobal(notify,"notify","utils"),registerGlobal(injectAnnouncementBarSlide,"injectAnnouncementBarSlide","utils"); //# sourceMappingURL=/cdn/shop/t/1163/assets/lib-utils.js.map?v=139982875276604810441760566308