"use strict";const WVPL_MAX_FAILED_ATTEMPTS=5;let microStart=0;class WVPLEngine{constructor(t){this.setVars(t),this.setupObservers(),this.active=!0,this.switched=!0,this.instances=[],this.currentId,this.currentInstance=null,this.failedAttempts=0,this.peakLength=1920,this.setupAudioEngine(),this.node=document.querySelector("#wvpl-sticky-player"),this.queue=[],this.start()}setupAudioEngine(t){this.setAudioType(t),this.webAudio=new Audio,this.webAudio.preload="metadata",this.webAudio.crossOrigin="anonymous",this.mediaElement=new Audio,this.mediaElement.preload="metadata",this.volume=1,this.muted=!1,delete this.audioCtx,delete this.gain,delete this.analyserGain,this.isWebAudio()&&(this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.gain=this.audioCtx.createGain(),this.analyserGain=this.audioCtx.createGain(),this.createSource(),this.setSmoothingTimeConstant(parseFloat(this.getOption("wave_animation")||1))),this.addEvents()}setAudioType(t){switch(t=t||"WebAudio",!0){case this.getOption("force_media_element"):case this.getiOSVersion()&&this.getOption("force_ios_media_element"):case this.getiOSVersion()&&this.getOption(`force_ios_${this.getiOSVersion()}_media_element`):case this.getSafariVersion()&&this.getOption("force_safari_media_element"):case this.getSafariVersion()&&this.getOption(`force_safari_${this.getSafariVersion()}_media_element`):t="MediaElement";break}this.audioType=t}getAudioType(){return this.audioType}isWebAudio(){return"WebAudio"===this.getAudioType()}isMediaElement(){return"MediaElement"===this.getAudioType()}audio(){return this.isWebAudio()?this.webAudio:this.mediaElement}cancelAnimationFrame(){(window.cancelAnimationFrame||window.mozCancelAnimationFrame).call(window,this.afRequest)}setupObservers(){this.setupInstanceObserver(),this.setupVariationFormObserver()}setupInstanceObserver(){const t={attributes:!1,childList:!0,subtree:!0};this.instanceObserver=new MutationObserver(((e,s)=>{e.forEach((e=>{e.target.querySelector(".waveplayer:not(.active):not(.activating)")&&(this.loadInstances(),s.disconnect(),requestAnimationFrame((()=>{s.observe(document.body,t)})))}))})),requestAnimationFrame((()=>{this.instanceObserver.observe(document.body,t)}))}setupVariationFormObserver(){if(!this.vars.wc_version)return;if(!document.querySelector("#wvpl-variation-popup")){let t=this.vars.palettes.filter((t=>t.colors===this.getOption("default_palette")));t=t.length>0&&t[0].id,this.variationPopup=document.createElement("div"),this.variationPopup.id="wvpl-variation-popup",this.variationPopup.classList.add("woocommerce","single-product",`wvpl-style-${this.getOption("style")}`,`wvpl-palette-${t}`),document.body.appendChild(this.variationPopup)}if(this.variationPopup.innerHTML="",!this.variationPopupObserver){const t={attributes:!0,childList:!0,subtree:!0};this.variationPopupObserver=new MutationObserver(this.variationFormCallback.bind(this)),requestAnimationFrame((()=>{this.variationPopupObserver.observe(this.variationPopup,t)}))}const t=document.createElement("div");t.classList.add("product","wvpl-variation-form"),jQuery(t).on("wc_variation_form",(t=>{document.body.classList.add("wvpl-variation-popup")})),this.variationPopup.append(t)}setVars(t){this.vars=t.wvplVars,this.__=t.wp.i18n.__,this._n=t.wp.i18n._n,this.template=t.lodash.template}getSafariVersion(){if(void 0===this.safariVersion){this.safariVersion=!1;const t=navigator.userAgent.toLowerCase().match(/version\/(\d+)/);t&&(this.safariVersion=t[1])}return this.safariVersion}getiOSVersion(){if(void 0===this.iOSVersion){this.iOSVersion=!1;const t=navigator?.userAgent?.match(/(iPad|iPhone).+OS (\d+)_/);t&&(this.iOSVersion=parseInt(t[2]))}return this.iOSVersion}isSafari(){return this.getSafariVersion()}isiOS(){return this.getiOSVersion()}isDocumentHidden(){return void 0!==document.hidden?document.hidden:void 0!==document.msHidden?document.msHidden:void 0!==document.webkitHidden&&document.webkitHidden}getInstanceById(t){return t=t||this.getCurrentId(),this.instances.find((e=>e.id===t))}nextInstance(){const t=this.getVisibleInstancesInDOM();let e=this.getCurrentIndex();return e<0?t[0]:(e++,!(e>=this.instances.length)&&t[e])}prevInstance(){const t=this.getVisibleInstancesInDOM();let e=this.getCurrentIndex();return!(e<0)&&(e--,!(e<0)&&t[e])}processQueue(){if(this.queue.length>0){const t=this.queue.shift();this.addInstance(t),requestAnimationFrame((()=>this.processQueue()))}else window.dispatchEvent(new CustomEvent("resize")),window.dispatchEvent(new CustomEvent("waveplayer.queue.processed"))}addInstance({player:t,tracks:e,nonce:s}){const i=this.instances.find((e=>e.id===t.dataset.instance_id));if(i)i.init(t,e,s,this);else{for(const t of e)t?.peaks&&!Array.isArray(t.peaks)&&(t.peaks=this.readPeaks(t.peaks));const i=new WVPLInstance(t,e,s,this);this.instances.push(i),1===this.instances.length&&(this.currentId=i.id,window.dispatchEvent(new CustomEvent("waveplayer.instance.added",{detail:{instance:i}})))}}removeInstance(t){if(this.getInstanceById(t)){const e=this.getCurrentIndex(t);this.instances.splice(e,1)}}getElement(t){return t=t||this.getCurrentId(),document.getElementById(t)}getOption(t){return this.vars.options[t]}setOption(t,e){this.vars.options[t]=e,this.redrawAllInstances()}getVar(t){return this.vars?.[t]}setVar(t,e){this.vars[t]=e}getInstancesInDOM(){if(this.instances)return this.instances.filter((t=>document.querySelector(`.waveplayer[data-instance_id="${t.id}"]`)))}getVisibleInstancesInDOM(){return this.getInstancesInDOM().filter((t=>t.node.offsetParent))}getFirstInstanceInDOM(){const t=this.getVisibleInstancesInDOM();return t?t[0]:null}getCurrentId(){const t=this.getFirstInstanceInDOM();return this?.currentId||t?.id}isInstanceInDOM(t){return t=t||this.currentId,this.getInstancesInDOM().find((e=>e.id===t))}getCurrentInstance(){return void 0===this.currentId?this.getFirstInstanceInDOM():this.instances.find((t=>t.id===this.currentId))}setCurrentInstance(t){if(t=t||this.getFirstInstanceInDOM()){if(!this.currentId||this.currentId!==t.id){const e=this.getCurrentInstance();e&&(e.updateStatistics(),e.stop()),this.currentId=t.id,this.switched=!0}this.node&&(this.node.dataset.instance_id=t.id)}}start(){const t=new CustomEvent("waveplayer.engine.starting",{detail:{engine:this}});document.dispatchEvent(t),this.stickyPlayerInit(),this.navigatorInit(),this.loadInstances(),this.setCurrentInstance();let e=this.getVisibleInstancesInDOM().find((t=>t.autoplay));Number(this.getOption("autoplay"))&&(e=this.getFirstInstanceInDOM()),e&&(e.node.classList.contains("wvpl-rendered")?e.play():e.playerInit(!0))}getCurrentIndex(t){return t=t||this.currentId,this.getVisibleInstancesInDOM().findIndex((e=>e.id===t))}getTrack(t){return this.getCurrentInstance().getTrack(t)}getCurrentTrack(){return this.getTrack()}getCurrentTrackIndex(){return this.getCurrentInstance().getCurrentTrackIndex()}getColorStyleFromPalette(t){const e=["fc","fc-s","bc","bc-s","hc","hc-s","wc","wc-s","pc","pc-s","cc","cc-s"];let s={};for(const i in e){const a=[parseInt(`0x${t[i].slice(0,2)}`),parseInt(`0x${t[i].slice(2,4)}`),parseInt(`0x${t[i].slice(4,6)}`)].join(", ");s[`--${e[i]}`]=a}return s}findTrack(t,e="id"){const s=this.instances.map((t=>t.tracks)).flat().filter((s=>String(s[e])===String(t)));return!!s.length&&s[0]}skip(t=!0){this.hasEnded?this.hasEnded=!1:this.trigger("skip");const e=this.getCurrentInstance(),s=this.prevInstance(),i=this.nextInstance(),a=this.isInstanceInDOM(),n=0===this.getInstancesInDOM().length;let r=Number.isInteger(t)?t:e.getCurrentTrackIndex()+(t?1:-1),o=e,l=!0;if(a||n)switch(!0){case r>=0&&r<e.getTrackCount():break;case t&&r>=e.getTrackCount()&&this.getOption("jump")&&!!i:r=0,o=i;break;case t&&r>=e.getTrackCount()&&!!e.repeat:r=0;break;case!t&&r<0&&this.getOption("jump")&&!!s:o=s,r=s.getTrackCount()-1;break;default:l=!1;break}else o=i,r=0;this.switched=e.id!==o.id,l?(o.mousePosition=-1,o.currentTrack>=0&&o.currentTrack<o.getTrackCount()&&e.updateStatistics(),o.currentTrack=r,o.loading(),this.node?.classList.add("loading"),this.pause().then((()=>{this.setSkipState(),this.switched?(e.stop(),e.reset(),this.getOption("auto_scroll_page")&&o.node.scrollIntoView({behavior:"smooth",block:"center"}),o.waveRedraw(),this.setCurrentInstance(o),o.preloadTrack(!0)):(o.getData("auto_scroll_playlist")&&o.scrollTo(r,t),o.preloadTrack(!0))}))):(o.stop(),o.reset())}applyTemplate(t,e){const s=document.querySelector("#tmpl-placeholders"),i=this;if(!s)return"";const{template:a}=this,n=this.getVar("currentUser");return t=(t=t.replace(/(\{[^\}]*\})/g,(function(t,s){var i=JSON.parse(s);for(let t in i){let s=i[t];"string"==typeof i[t]&&(i[t]=s.replace(/%([^%]+)%/g,(function(t,s){return e[s]?e[s]:""})))}return JSON.stringify(i)}))).replace(/%([^ %\{]*)(\{[^\}]*\})*%/g,(function(t,r,o){var l=r,d=jQuery.extend({class:"",showValue:1,text:"",raw:0,url:"",target:"_blank",icon:"",event:"",guests:!0},o?JSON.parse(o):"");try{return a(s.innerHTML)({key:l,attributes:d,track:e,loggedUser:n.ID>0,__:i.__,_n:i._n,likes:n.likes})}catch(t){return i.log(t),""}}))}toggleStickyPlayer(t=!1){if(!this.node)return;this.setSkipState();const e=document.querySelector("html");if(t&&e.classList.contains("has-sticky-player"))return;const s=this.getOption("sticky_player_position");e.classList.toggle("has-sticky-player"),e.classList.toggle(`has-sticky-player-${s}`)}hasStickyPlayer(){return document.querySelector("html").classList.contains("has-sticky-player")}updateStickyPlayerInfo(){this.switched=!1;const t=this.getCurrentInstance();if(!t)return;const e=this.node,s=this.getOption("sticky_template")||"%thumbnail% %title% %artist% %share%",i=t.getTrack();i&&e&&(e.classList.add("loading"),setTimeout((()=>{e.querySelector(".wvpl-duration").textContent=i.length_formatted,e.querySelector(".wvpl-position").textContent=this.secondsToTime(),i.length_formatted&&(e.querySelector(".wvpl-duration").style.width=`${i.length_formatted.length+1}ch`,e.querySelector(".wvpl-position").style.width=`${i.length_formatted.length+1}ch`);const t=e.querySelector(".wvpl-trackinfo");t&&(t.innerHTML=this.applyTemplate(s,i)),e.classList.remove("loading")}),WVPL_ANIMATION_TIME))}updateMediaSession(t){if("mediaSession"in navigator&&t){const e={title:t.title,artist:t.artist,album:t.album};t.poster&&(e.artwork=[{src:t.poster}]),navigator.mediaSession.metadata=new MediaMetadata(e)}}updateVariationForm(t){const e=this.variationPopup.querySelector(".wvpl-variation-form");this.variationPopupObserver.track=t,e.innerHTML=t.product_variations_form;const s=document.createElement("div");s.classList.add("close-button"),e.prepend(s);const i=jQuery(`<h4>${t.product_title}</h4>`).get(0);e.prepend(i),s.addEventListener("click",(e=>{document.body.classList.remove("wvpl-variation-popup"),this.trigger("variationForm:close",{track:t})})),this.trigger("variationForm:open",{track:t})}variationFormCallback(t,e){for(let s of t)if("childList"===s.type&&s.target.classList.contains("wvpl-variation-form")){const t=s.target.querySelector(".variations_form");if(t){jQuery(t).wc_variation_form();const s=jQuery(t).find("table");jQuery(t).find("a.reset_variations").insertAfter(s),e.disconnect(),requestAnimationFrame((()=>{e.observe(this.variationPopup,{attributes:!0,childList:!0,subtree:!0})}))}}}updateTrackCartStatus(t,e="add"){const s=this.instances.filter((e=>e.tracks.find((e=>e.product_id==t))));for(const i of s){const s=i.tracks.find((e=>e.product_id==t));s&&(s.in_cart="add"===e)}}setSkipState(){const t=this.node?.querySelector(".wvpl-prev"),e=this.node?.querySelector(".wvpl-next"),s=this.getCurrentInstance(),i=this.prevInstance()||s?.getCurrentTrackIndex()>0,a=this.nextInstance()||s?.getCurrentTrackIndex()<s?.getTrackCount()-1||s?.repeat;t?.classList.toggle("wvpl-disabled",!i),e?.classList.toggle("wvpl-disabled",!a),s?.setSkipState()}createAnalyser(){if(!this.isMediaElement()){this.analyser=this.audioCtx.createAnalyser(),this.analyser.smoothingTimeConstant=parseFloat(this.getOption("wave_animation")||1),this.analyser.maxDecibels=-30,this.analyser.minDecibels=-90;try{this.analyser.fftSize=8192}catch(t){this.analyser.fftSize=2048}this.analyserGain.connect(this.analyser)}}destroyAnalyser(){this.isMediaElement()||(this.analyserGain.disconnect(this.analyser),this.analyser=null,this.frequencyData=null)}createSource(){this.isMediaElement()||(this.source=this.audioCtx.createMediaElementSource(this.webAudio),this.source.connect(this.gain),this.source.connect(this.analyserGain),this.gain.connect(this.audioCtx.destination),this.createAnalyser())}getCurrentTrack(){return this.getCurrentInstance().getCurrentTrack()}audioProcess(){if(this.isPaused()||this.isDocumentHidden())return;this.afRequest=requestAnimationFrame(this.audioProcess.bind(this)),this.isWebAudio()&&this.analyser&&parseFloat(this.getOption("wave_animation"))<1&&(this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.analyser.getByteFrequencyData(this.frequencyData));this.getCurrentInstance()?.timeUpdate()}async ajaxCall(t,e={}){const s=this.vars.wvpl_ajax_url.replace("%%endpoint%%",t),i=Object.keys(e).map((t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t]))).join("&");try{const t=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=utf-8"},body:i});try{return await t.json()}catch(t){this.log(t)}}catch(t){this.log(t)}}async getAudioData(t,e,s){try{const e=await fetch(t);if(e.status>=400)return this.log(e.statusText),!1;const i=e.headers.get("Content-Length");if(i){const t=new Uint8Array(i);let a=0;const n=e.body.getReader();for(;;)try{const{done:e,value:r}=await n.read();if(e)break;t.set(r,a),a+=r.length,s(a,i)}catch(t){return this.log(t),!1}return t.buffer}return await e.arrayBuffer()}catch(t){return this.log(t),!1}}decodeAudioData(t,e,s){t instanceof ArrayBuffer!=!1?this.audioCtx.decodeAudioData(t,e.bind(this),s.bind(this)):this.log("decodeAudioData","Invalid data type")}extractPeaks(t){const e=t.numberOfChannels,s=t.length/this.peakLength,i=~~(s/10)||1,a=[];for(var n=0;n<e;n++){const e=[],p=t.getChannelData(n);for(var r=0;r<this.peakLength;r++){for(var o=~~(r*s),l=~~(o+s),d=p[0],c=p[0],h=o;h<l;h+=i){var u=p[h];u>c&&(c=u),u<d&&(d=u)}e[2*r]=c,e[2*r+1]=d,(0==n||c>a[2*r])&&(a[2*r]=Math.abs(c.toFixed(2))),(0==n||d<a[2*r+1])&&(a[2*r+1]=Math.abs(d.toFixed(2)))}}return a}readPeaks(t,e=!1){if(Array.isArray(t))return t;if(e)try{t=window.atob(t)}catch(t){}return"string"==typeof t&&t.split("").map((t=>(t.charCodeAt()-48)/100))}loadInstances(t){let e=(t=t?document.querySelector(t):document).querySelectorAll(".waveplayer:not(.active):not(.activating)");const s=document.querySelector("ul#instance_track_data");if(s&&!parseInt(s?.dataset?.preload_instances)){const t=[...new Set(Array.from(s.querySelectorAll("li")).map((t=>t?.dataset?.config_id)))].join();fetch(`${this.vars.rest_url.replace("%%endpoint%%","instances")}/${t}`).then((t=>t.json())).then((t=>{if(t){for(const e of t){Array.from(document.querySelectorAll(`.waveplayer[data-instance_id^="${e?.args?.config_id}"]`)).forEach((t=>{t.classList.add("activating");let s=e?.tracks??[];const i=e?.nonce??"";t&&s?.length>0&&(s=s.map((t=>(t.peaks=!!t.peaks&&this.readPeaks(t.peaks,!0),t))),this.queue.push({player:t,tracks:s,nonce:i}))}))}requestAnimationFrame((()=>this.processQueue()))}}))}else if(e.length){let t,i;for(let a of e){a.classList.add("activating");const e=a.dataset.instance_id.split("-")[0],n=s?.querySelector(`li[id^="data-${e}"]`);if(n?.dataset?.tracks)t=JSON.parse(window.atob(n.dataset.tracks)),i=n.dataset.nonce;else{if(!a?.dataset?.tracks)return void fetch(`${this.vars.rest_url.replace("%%endpoint%%","instance")}/${e}`).then((t=>t.json())).then((e=>{e?.tracks&&(t=e.tracks,i="",this.queue.push({player:a,tracks:t,nonce:i}),requestAnimationFrame((()=>this.processQueue())))}));t=JSON.parse(window.atob(a.dataset.tracks)),i=a.dataset?.nonce,a.removeAttribute("data-tracks")}t?.length>0&&this.queue.push({player:a,tracks:t,nonce:i})}requestAnimationFrame((()=>this.processQueue()))}}stickyPlayerInit(){if(!this.node)return;const t=this.node.querySelector("#wvpl-sticky-player .wvpl-waveform");if(!t)return;const e=document.createElement("canvas");t.innerHTML="",t.appendChild(e)}navigatorInit(){"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("play",(()=>{this.play()})),navigator.mediaSession.setActionHandler("pause",(()=>{this.pause()})),navigator.mediaSession.setActionHandler("previoustrack",(()=>{this.skip(!1)})),navigator.mediaSession.setActionHandler("nexttrack",(()=>{this.skip()})),navigator.mediaSession.setActionHandler("seekto",(({seekTime:t})=>{this.setCurrentTime(t)})))}isPaused(){return this.audio().paused}play(t){const e=this.getCurrentTrack();this.audioPaused=!1,this.updateMediaSession(e),this.switched||encodeURI(this.audio().src)!==encodeURI(e.file)?(this.persistentTrack=e,this.status=0,this.switched=!1,this.updateStickyPlayerInfo(),this.isWebAudio()&&(this.fadeTimeout&&(clearTimeout(this.fadeTimeout),this.gain.gain.cancelScheduledValues(this.audioCtx.currentTime)),this.analyserFadeTimeout&&(clearTimeout(this.analyserFadeTimeout),this.analyserGain.gain.cancelScheduledValues(this.audioCtx.currentTime))),this.audio().src=e.file,this.audio().play().then((()=>{this.thenPlay(t)})).catch((s=>{this.setAudioType("MediaElement"),this.audio().src=e.file,this.audio().play().then((()=>{this.thenPlay(t)})).catch((()=>{this.failedAttempts<5&&(this.failedAttempts++,this.tryReloadingTrack())}))}))):this.audio().play().then((()=>{this.thenPlay(t)}))}thenPlay(t){this.playing(),this.failedAttempts=0,t>=0&&this.setCurrentTime(t),this.toggleStickyPlayer(!0),this.isWebAudio()&&(this.trackLastStart=this.getCurrentTime(),this.fadeIn(this.getOption("fade_in")),this.analyserFadeIn(.3))}pause(){return new Promise(((t,e)=>{this.audioPaused=!0,this.lastTime=this.audio().currentTime,this.node?.classList.remove("playing"),this.status>0?(this.status=2,this.isWebAudio()?(this.fadeOut(this.getOption("fade_out")),this.analyserFadeOut(.3,(()=>{this.webAudio.pause(),this.setCurrentTime(this.lastTime),this.hasEnded||this.trigger("pause"),t()}))):(this.mediaElement.pause(),t())):t()}))}stop(){this.pause().then((()=>{this.status=0,this.setCurrentTime(0)}))}toggle(){const t=this.getCurrentInstance();this.isPaused()?t.play():t.pause()}resume(){this.audioCtx&&this.audioCtx.resume()}tryReloadingTrack(){const t=this.getInstanceById(),e=t.tracks[t.currentTrack];"soundcloud"===e?.type&&(e.file="",t.preloadTrack(!0))}getCurrentTime(){return this.audioPaused?this.lastTime:this.audio().currentTime}setCurrentTime(t,e=!1){this.trackLastStart=t,t>=0&&t<=this.getDuration()&&(this.audio().currentTime=t),this.isPaused()&&e&&this.play()}getDuration(){return this.audio().duration}getProgress(){return this.getCurrentTime()/this.getDuration()}getVolume(){return this.volume}setVolume(t){const e=[];this.isInstanceInDOM()&&e.push(this.getCurrentInstance().node),this.hasStickyPlayer()&&e.push(this.node);for(const s of e){const e=s.querySelector(".wvpl-volume-slider .value"),i=s.querySelector(".wvpl-volume-slider .handle");e&&(e.style.width=100*t+"%"),i&&(i.style.left=100*t+"%")}this.volume=t,this.isWebAudio()&&this.gain.gain.setValueAtTime(t,this.audioCtx.currentTime),this.muted=!(t>0)}mute(){this.isWebAudio()&&this.gain.gain.setValueAtTime(0,this.audioCtx.currentTime),this.muted=!0}unmute(){this.isWebAudio()&&this.gain.gain.setValueAtTime(this.volume,this.audioCtx.currentTime),this.muted=!1}toggleMute(){this.muted?this.unmute():this.mute()}isMuted(){return this.muted}fadeOut(t,e){this.isMediaElement()?e&&e():(this.gain.gain.setValueAtTime(this.volume,this.audioCtx.currentTime),this.gain.gain.linearRampToValueAtTime(0,this.audioCtx.currentTime+t),e&&(this.fadeTimeout=setTimeout(e,1e3*t)))}fadeIn(t,e){this.isMediaElement()?e&&e():(this.gain.gain.setValueAtTime(0,this.audioCtx.currentTime),this.gain.gain.linearRampToValueAtTime(this.volume,this.audioCtx.currentTime+t),e&&(this.fadeTimeout=setTimeout(e,1e3*t)))}analyserFadeOut(t,e){this.isMediaElement()?e&&e():(this.analyserGain.gain.linearRampToValueAtTime(0,this.audioCtx.currentTime),e&&(this.analyserFadeTimeout=setTimeout(e,1e3*t)))}analyserFadeIn(t,e){this.isMediaElement()?e&&e():(this.analyserGain.gain.linearRampToValueAtTime(this.volume,this.audioCtx.currentTime),e&&(this.analyserFadeTimeout=setTimeout(e,1e3*t)))}isLooped(){return this.audio().loop}loop(t){this.audio().loop=t}getSampleRate(){return this.audioCtx.sampleRate}setSmoothingTimeConstant(t){this.isMediaElement()||(this.analyser||this.createAnalyser(),this.analyser.smoothingTimeConstant=t)}redrawAllInstances(){for(const t of this.getInstancesInDOM())t.refresh();this.setSkipState()}playing(){this.audioProcess();const t=this.getCurrentInstance();t&&(t.playing(),t.node.classList.remove("seeking")),this.node&&(this.node.classList.remove("seeking"),this.node.classList.add("playing")),this.trigger("play"),this.status=1}seeking(){setTimeout((()=>{if(this.audio().seeking){this.getCurrentInstance()?.node.classList.add("seeking"),this.node?.classList.add("seeking"),this.trigger("seeking")}}),100)}seeked(){this.getCurrentInstance()?.node.classList.remove("seeking"),this.node?.classList.remove("seeking"),this.trigger("seeked")}addEvents(){this.onDocumentVisibilityChange(),this.onSeeking(),this.onSeeked(),this.onEnded(),this.onTimeUpdateFallback()}onDocumentVisibilityChange(){document.addEventListener("visibilitychange",(()=>{this.isPaused()||this.resume()}))}onSeeking(){this.webAudio.addEventListener("seeking",(t=>{this.seeking()})),this.mediaElement.addEventListener("seeking",(t=>{this.seeking()}))}onSeeked(){this.webAudio.addEventListener("seeked",(t=>{this.seeked()})),this.mediaElement.addEventListener("seeked",(t=>{this.seeked()}))}onEnded(){this.webAudio.addEventListener("ended",(t=>{this.hasEnded=!0,this.trigger("ended")})),this.mediaElement.addEventListener("ended",(t=>{this.hasEnded=!0,this.trigger("ended")}))}onTimeUpdateFallback(){this.mediaElement.addEventListener("timeupdate",(t=>{this.getCurrentInstance()?.timeUpdate()}))}gtmPushTimeData(t){window.dataLayer=window.dataLayer||[];const e=this.getCurrentInstance().getTrack(),s=this.round(this.getCurrentTime(),2);if(!e)return;const i={event:"track",action:t,type:"time",trackId:e.id||0,trackTitle:e.title||"",time:s||0};window.dataLayer.push(i)}gtmPushSegmentData(t){window.dataLayer=window.dataLayer||[];const e=this.getCurrentTrack(),s=this.round(this.getCurrentTime(),2);if(!e)return;const i={event:"track",action:t,type:"segment",trackId:e.id||0,trackTitle:e.title||"",time:s||0,from:this.round(this.trackLastStart,2),duration:this.round(s-this.trackLastStart)};window.dataLayer.push(i)}round(t,e){e=e||0;const s=Math.pow(10,e),i=Number.EPSILON||Math.pow(2,-52);return Math.round(t*s+i)/s}trigger(t,e){this.getCurrentInstance()&&this.getCurrentInstance().trigger(t,e)}secondsToTime(t){if(null==t)return"0:00";var e=(t=Math.round(t))%60,s=Math.floor(t/60)%60,i=Math.floor(t/3600);return(i>0?i+":":"")+(i>0&&s<10?"0":"")+s+":"+(e<10?"0":"")+e}timeToSeconds(t){const e=t.match(/((1*[0-2]|0*[0-9]):)?([0-5]*[0-9]):([0-5][0-9])/);if(e){let t=Number(e[4]);return e[3]&&(t+=60*Number(e[3])),e[2]&&(t+=3600*Number(e[2])),t}return!1}shortenNumber(t){if((t=Number(t))<1e3)return t.toFixed(0);let e=0;for(;t>=1e3;)t/=1e3,e++;return t.toFixed(1)+["","k","M","G","T","P","E"][e]}isDebugMode(){return this.vars.is_script_debug}log(...t){this.isDebugMode()}}const WVPL_STATUS_STOP=0,WVPL_STATUS_PLAY=1,WVPL_STATUS_PAUSE=2,WVPL_ANIMATION_TIME=300;class WVPLInstance{constructor(t,e,s,i){this.init(t,e,s,i)}init(t,e,s,i){this.id=t.dataset.instance_id,this.node=t,this.engine=i,this.tracks=e,this.currentTrack=0,this.nonce=s,this.waveformOptions=null,this.resetRuntime(),this.info=this.getData("info"),this.lastStart=0,this.scrolling=!1,this.timerOverlay,this.startOffset,this.startVol,this.mousePosition=-1,this.status=0,this.createObservers(),this.instanceInit()}getOption(t){return this.engine.getOption(t)||""}getData(t){let e=this.node.dataset[t];return void 0!==e&&0!==e.toString().length||(e=this.getOption(t)),e}support(t){const e=this.getData("skin");return this.engine.vars.skins[e]?.support?.indexOf(t)>-1}getStickyPlayerData(t){if(!this.engine.node)return;let e;return e=getComputedStyle(this.engine.node).getPropertyValue(`--${t}`).trim(),e}updateLength(){if(!this.getFirst(".wvpl-duration"))return;const t=this.getTrackData("length_formatted")||this.engine.secondsToTime(this.getTrackData("length"));this.getFirst(".wvpl-duration").textContent=t,this.getFirst(".wvpl-position").textContent=this.engine.secondsToTime(),t&&(this.getFirst(".wvpl-duration").style.width=`${t.length+1}ch`,this.getFirst(".wvpl-position").style.width=`${t.length+1}ch`)}getRealWaveformSize(t){const e=(t=t||this.node).querySelector(".wvpl-waveform");if(!e)return!1;getComputedStyle(e);let s=e.clientHeight,i=e.clientWidth;if(i*s>0)return{width:i,height:s};let a=e,n=a;for(;(n=n.parentNode)&&!(n.offsetWidth*n.offsetHeight>0);)a=n;if(n){let t=a.cloneNode(!0);t.style.display="block",n.append(t);let e=t.querySelector(".wvpl-waveform");e&&(i=e.offsetWidth,s=e.offsetHeight),t.remove()}return{width:i,height:s}}getWaveformOptions(t){const e=(t=t||this.node).querySelector(".wvpl-waveform");if(!e)return!1;const s=t===this.engine.node?this.getOption.bind(this):this.getData.bind(this);return{waveColor:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--wave").trim()+")":s("wave_color"),waveColor2:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--wave-shade").trim()+")":s("wave_color_2"),progressColor:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--progress").trim()+")":s("progress_color"),progressColor2:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--progress-shade").trim()+")":s("progress_color_2"),cursorColor:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--cursor").trim()+")":s("cursor_color"),cursorColor2:parseInt(s("override_wave_colors"))?"rgb("+getComputedStyle(t).getPropertyValue("--cursor-shade").trim()+")":s("cursor_color_2"),cursorWidth:parseInt(s("cursor_width")),hoverOpacity:parseInt(s("hover_opacity"))/100,barWidth:parseInt(s("wave_mode")),gapWidth:parseInt(s("gap_width")),compression:parseInt(s("wave_compression")),asymmetry:parseInt(s("wave_asymmetry")),normalization:parseInt(s("wave_normalization")),waveAnimation:parseFloat(this.getData("wave_animation")),ampFreqRatio:parseFloat(this.getData("amp_freq_ratio")),height:e.offsetHeight,bandwidth:2e4,bandwidthStart:100}}updateSize(t){const e=[];if(t||this.engine.isInstanceInDOM(this.id)){Array.from(this.getChildren("canvas")).filter((t=>t.offsetHeight>0)).length>0&&e.push({player:this.node,instance:this})}(t||this.engine.hasStickyPlayer())&&e.push({player:this.engine.node,instance:this.engine.getCurrentInstance()});for(const t of e){const e=t.player;if(!e||!e.querySelector(".wvpl-waveform"))continue;e.waveformOptions=this.getWaveformOptions(e),this.engine.setSmoothingTimeConstant(parseFloat(this.getData("wave_animation")||1));let s=e.querySelector(".wvpl-waveform canvas"),i=s.getContext("2d"),a=this.getRealWaveformSize(e);try{i.canvas.width=Math.round(a.width*window.devicePixelRatio),i.canvas.height=Math.round(a.height*window.devicePixelRatio),s.style.width=`${Math.round(a.width)}px`,s.style.height=`${Math.round(a.height)}px`}catch(t){this.log("updateSize",t)}this.prepareCanvas(e),this.getTrackData("peaks")&&this.calculateWaveParams(e)}}prepareCanvas(t){const e=(t=t||this.node).querySelector(".wvpl-waveform canvas"),s=e.getContext("2d");e.grdW=this.createGradient(s,s.canvas.height,t.waveformOptions.waveColor,t.waveformOptions.waveColor2,t.waveformOptions.asymmetry),e.grdP=this.createGradient(s,s.canvas.height,t.waveformOptions.progressColor,t.waveformOptions.progressColor2,t.waveformOptions.asymmetry),e.grdC=s.createLinearGradient(0,0,0,s.canvas.height);try{e.grdC.addColorStop(0,t.waveformOptions.cursorColor),e.grdC.addColorStop(1,t.waveformOptions.cursorColor2)}catch(t){this.log("prepareCanvas",t)}}createGradient(t,e,s,i,a){let n=t.createLinearGradient(0,0,0,e);try{n.addColorStop(0,s),n.addColorStop(a/(1+a)-1e-9,i),n.addColorStop(a/(1+a),s),n.addColorStop(1,i)}catch(t){this.log("createGradient",t)}return n}clearWave(t){let e=(t=t||this.node).querySelector(".wvpl-waveform canvas").getContext("2d");e.clearRect(0,0,e.canvas.width,e.canvas.height)}waveformInit(){let t=this.getFirst(".wvpl-waveform"),e=document.createElement("canvas");t&&(t.innerHTML="",t.appendChild(e))}processBuffer(t,e){if(!t||t.constructor!==ArrayBuffer)return!1;this.engine.decodeAudioData(t,(t=>{const s=this.engine.extractPeaks(t);this.getTrackData("length")||(this.setTrackData("length",t.duration),this.setTrackData("length_formatted",this.engine.secondsToTime(t.duration))),this.setTrackData("peaks",s),this.updateInfo(),this.trigger("peaksloaded",{peaks:s,id:e})}),(t=>{this.log("processBuffer",t)}))}progressCallback(t,e){const s=Math.floor(100*t/e);this.updateOverlay(s,"analyzing")}waveReset(){this.clearWave(),this.engine.node&&this.clearWave(this.engine.node)}calculateWaveParams(t){t=t||this.node;const e={},s=window.devicePixelRatio;e.canvas=t.querySelector(".wvpl-waveform canvas"),e.cCtx=e.canvas.getContext("2d"),e.width=e.canvas.width,e.height=e.canvas.height,e.barWidth=0==t.waveformOptions.barWidth?1*s:t.waveformOptions.barWidth*s,e.gapWidth=0==t.waveformOptions.gapWidth?0:t.waveformOptions.gapWidth*s,e.cursorWidth=t.waveformOptions.cursorWidth*s,e.compRatio=1/t.waveformOptions.compression,e.a=t.waveformOptions.asymmetry,e.stepSize=e.barWidth+e.gapWidth;const i=this.getTrackData("peaks");e.scale=e.width/i.length,e.max=1,i&&t.waveformOptions.normalization&&(e.max=Math.max(...i)),t.waveParams=e}drawWave(){const t=[];Array.from(this.getChildren("canvas")).filter((t=>t.offsetHeight>0)).length>0&&t.push({player:this.node,instance:this}),this.engine.hasStickyPlayer()&&t.push({player:this.engine.node,instance:this.engine.getCurrentInstance()});for(const i of t){const t=i.player,a=i.instance;if(!t||!a||!t.querySelector(".wvpl-waveform"))continue;const n=a.getTrackData("peaks"),r=0!==this.status?this.engine.getCurrentTime():0,o=0!==this.status?this.engine.getProgress():0;let l=0!==this.status?this.engine.frequencyData:null;if(!n)return;const d=t.querySelector(".wvpl-position");d&&(d.textContent=this.engine.secondsToTime(r));const c=t.waveParams,h=t.waveformOptions,u=t===this.node?this.mousePosition:-1,{scale:p,max:g}=c,m=o*c.width;let v=h.ampFreqRatio;1==h.waveAnimation&&(v=1/0);const f=h.bandwidthStart*c.width/h.bandwidth;c.width,c.width;c.cCtx.clearRect(0,0,c.width,c.height);const y=devicePixelRatio,w=1/(v+1),k=1-w;let T=0;for(var e=0;e<c.width-c.stepSize;e+=c.stepSize){const i=l?Math.round(Math.max(T,Math.pow(l.length,e/c.width))):0,a=l?g*l[i]/255:0,r=Math.pow(Math.abs(n[Math.floor(e/p)]),c.compRatio),o=Math.max(y,Math.abs(Math.ceil(c.height*(k*r+w*a)/g)));c.cCtx.fillStyle=c.canvas.grdW;var s=Math.ceil(c.a*(c.height-o)/(1+c.a));c.cCtx.globalAlpha=1,c.cCtx.fillRect(e,s,c.barWidth,o),e<Math.max(u,m)&&0!==this.status&&(c.cCtx.fillStyle=c.canvas.grdP,c.cCtx.globalAlpha=1,u>=0&&e>Math.min(u,m)&&t===this.node&&(c.cCtx.globalAlpha=h.hoverOpacity),c.cCtx.fillRect(e,s,c.barWidth,o)),T++}0!==this.status&&(c.cCtx.fillStyle=c.canvas.grdC,c.cCtx.fillRect(m,0,c.cursorWidth,c.height))}}waveRedraw(){this.updateSize(!0),this.drawWave(!0)}timeUpdate(){this.drawWave(),this.trigger("timeupdate")}createObservers(){const t={attributes:!0,childList:!1,subtree:!1,attributeOldValue:!0};this.mutationObserver=new MutationObserver(((e,s)=>{for(let t of e)if("attributes"===t.type&&t.oldValue!==this.node.getAttribute(t.attributeName)){this.refresh();break}s.disconnect(),requestAnimationFrame((()=>{s.observe(this.node,t)}))})),requestAnimationFrame((()=>{this.mutationObserver.observe(this.node,t)})),window.ResizeObserver&&(this.resizeObserver=new ResizeObserver((t=>{const e=t.find((t=>t.target.dataset.instance_id===this.id));this.currentWidth!==e?.target.offsetWidth&&(this.currentWidth=e?.target.offsetWidth,requestAnimationFrame((()=>{this.resizeObserver.observe(this.node)}))),this.resizeObserver.disconnect()})),requestAnimationFrame((()=>{this.resizeObserver.observe(this.node)}))),window.IntersectionObserver&&(this.intersectionObserver=new IntersectionObserver((t=>{!0!==t[0].isIntersecting||t[0].target.classList.contains("wvpl-rendered")||(this.intersectionObserver?.disconnect(),delete this.intersectionObserver,this.playerInit())}),{threshold:[0]}),setTimeout((()=>this.intersectionObserver.observe(this.node)),0))}instanceInit(){const t=this.getFirst(".wvpl-playlist-wrapper"),e=this.getFirst(".wvpl-position"),s=this.getFirst(".wvpl-duration");t&&(t.innerHTML="");let i=parseInt(this.getData("wave_asymmetry"));i=100*i/(1+i),e&&(e.style.top=i+"%",s.style.top=i+"%");let a=document.querySelectorAll(".waveplayer"),n=0;for(n=0;n<a.length&&a[n]!=this.node;n++);this.waveformInit(),this.autoplay=!!Number(this.getData("autoplay")),this.repeat=!!Number(this.getData("repeat")),this.shuffle=!!Number(this.getData("shuffle")),this.activated(),window.IntersectionObserver||this.playerInit()}playerInit(t){if(!this.node.classList.contains("wvpl-rendered"))if(this.refresh(),this.getTrackCount()>0){const e=this.getTrack(),s=e.id,i=(e.filesize,e.temp_file);this.node.classList.add("wvpl-rendered"),this.currentTrack=0,i?(this.analyzing(),this.engine.getAudioData(i,s,this.progressCallback.bind(this)).then((t=>{!1!==t&&this.processBuffer(t,s)}))):(this.setInfoState(),this.displayPlaylist(),this.preloadTrack(t)),this.initEvents()}else playBtn&&playBtn.classList.add("wvpl-disabled"),this.node.classList.add("wvpl-hidden")}getCurrentTime(){return this.engine.getCurrentTime()}setCurrentTime(t){if(t<0||t>this.engine.getDuration())return!1;this.engine.setCurrentTime(t)}maybeSwitch(){return new Promise(((t,e)=>{this.id!==this.engine.getCurrentId()?(this.trigger("skip"),this.engine.pause().then((()=>{this.engine.setCurrentInstance(this),this.preloadTrack(),t()}))):e()}))}play(){this.node?.classList.add("seeking"),this.engine?.node?.classList.add("seeking"),this.maybeSwitch().then((()=>(this.lastStart=(new Date).getTime(),this.engine.play())),(()=>(this.lastStart=(new Date).getTime(),this.engine.play()))).catch((()=>(this.lastStart=(new Date).getTime(),this.engine.play())))}pause(){this.engine.pause(),this.paused(),this.waveRedraw()}stop(){if(0==this.status)return!1;this.engine.stop(),this.paused(),this.getFirst(".wvpl-position")&&(this.getFirst(".wvpl-position").textContent=this.engine.secondsToTime(0)),this.status=0,this.waveRedraw()}skip(t=!0){this.clicked=!0;this.endOfPlaylist(t);this.stop(),this.endOfPlaylist(t)&&(this.currentTrack=0),this.engine.currentId!==this.id&&this.engine.setCurrentInstance(this),this.engine.skip(t)}skipTo(t){if(null==t||t<0||t>this.getTrackCount())return!1;if(t==this.currentTrack)return 1!==this.status&&this.play(),!0;const e=this.engine.getCurrentInstance();e&&e.node.id===this.node.id||(this.pause(),this.engine.setCurrentInstance(this)),this.skip(t)}endOfPlaylist(t=!0){return(!0===t&&this.currentTrack===this.tracks.length||!1===t&&1===this.currentTrack||1===this.tracks.length)&&!this.repeat}scrollTo(t,e){let s=this.getFirst(".wvpl-playlist-wrapper>ul");if(!s)return!1;let i=s.children,a=i.length&&i[t];if(!a)return!1;e?a.offsetTop+a.offsetHeight>s.scrollTop+s.offsetHeight&&s.scrollTo({top:a.offsetTop+a.offsetHeight-s.offsetHeight,behavior:"smooth"}):a.offsetTop<s.scrollTop&&s.scrollTo({top:a.offsetTop,behavior:"smooth"})}analyzing(){this.node.classList.remove("loading"),this.node.classList.add("analyzing"),this.trigger("analyzing")}analyzed(){this.node.classList.remove("analyzing"),this.updateOverlay(0,""),this.trigger("analyzed",{track:this.getTrack(),peaks:this.getTrackData("peaks")})}loading(){if(this.engine.switched)return!0;this.node.classList.add("loading"),this.trigger("loading")}loaded(){setTimeout((()=>{this.node.classList.remove("loading"),this.waveRedraw(),this.trigger("loaded")}),WVPL_ANIMATION_TIME)}playing(){this.status=1,this.removeClassFrom(".wvpl-playlist li","playing");let t=this.getChild(".wvpl-playlist-wrapper>ul>li",this.currentTrack);t&&t.classList.add("playing"),this.node.classList.add("playing")}paused(){this.status=2,this.updateRuntime(!1),this.node.classList.remove("playing","seeking"),this.engine.node?.classList.remove("playing","seeking"),this.removeClassFrom(".wvpl-playlist li","playing")}ready(){this.loaded(),this.trigger("ready",{instance:this,track:this.getTrack()})}activated(t=""){this.node.classList.add("active"),this.node.classList.remove("activating"),t&&this.node.classList.add(t),this.trigger("activated",{id:this.id})}resize(){const t=this.node.offsetWidth,e=[{width:400,class:"sqxxs"},{width:600,class:"sqxs"},{width:800,class:"sqsm"},{width:1e3,class:"sqmd"},{width:1200,class:"sqlg"},{width:1/0,class:"sqxl"}];let s="";const i=Number(getComputedStyle(this.node).getPropertyValue("--max-width").replace(/(px|em)/,""))||1200;for(const a of e)if(s=a.class,1200*t/i<a.width)break;this.node.classList.remove(...e.map((t=>`wvpl-${t.class}`))),this.node.classList.add(`wvpl-${s}`)}refresh(){this.setSkipState(),this.waveRedraw()}preloadTrack(t=!1){if(this.currentTrack<0&&(this.currentTrack=0),this.engine.loop(1==this.getTrackCount()&&this.repeat),"soundcloud"!==this.getTrackData("type")||this.getTrackData("file")){const e=this.getTrackData("peak_file");!this.getTrackData("peaks")&&e?fetch(e).then((t=>t.text())).then((e=>{let s=[];s="external"===this.getTrackData("type")?JSON.parse(e).peaks:e,s&&(s=this.engine.readPeaks(s),this.setTrackData("peaks",s),this.preloadFile(t))})):this.preloadFile(t)}else fetch(`${this.engine.vars.sc_api_url}tracks/${this.getTrackData("id")}/streams`,{headers:{Authorization:`OAuth ${this.engine.vars.sc_access_token}`}}).then((t=>t.json()),(t=>this.log(t))).then((e=>{void 0!==e?.http_mp3_128_url?(this.setTrackData("file",e?.http_mp3_128_url),this.preloadFile(t)):(this.log(`${e?.code}: ${e?.message}`),this.removeTrack(this.currentTrack),this.preloadTrack(t))}),(t=>this.log(t)))}updateOverlay(t,e){switch(e){case"creatingLocalCopy":e=this.engine.__("creating a local copy of the file&hellip;","waveplayer");break;case"savingPeaks":e=this.engine.__("saving the peak file&hellip;","waveplayer");break;case"analyzing":e=this.engine.__("audio analysis in progress&hellip;","waveplayer");break}const s=this.overlay||this.getFirst(".wvpl-overlay");s&&(s.querySelector(".percentage").innerHTML=t?`${t}%`:"&nbsp;",s.querySelector(".wvpl-loading>div").style.width=`${t}%`,s.querySelector(".message").innerHTML=e),this.overlay=s}preloadFile(t){if(this.updateInfo(),this.getTrackData("peaks"))(t||1===this.status)&&this.play();else{this.pause(),this.analyzing();const t=this.getTrack(),e=t.id,s=t.file;t.filesize,t.temp_file;if("external"!==this.getTrackData("type"))this.engine.getAudioData(s,e,this.progressCallback.bind(this)).then((t=>{!1!==t&&this.processBuffer(t,e)}));else{this.updateOverlay(0,"creatingLocalCopy");const t={nonce:this.engine.vars.ajax_nonce,url:s};this.engine.ajaxCall("create_local_copy",t).then((t=>{t?.success?(this.tracks[this.currentTrack]=t?.data?.track,this.engine.getAudioData(t?.data?.track?.temp_file,e,this.progressCallback.bind(this)).then((t=>{!1!==t&&this.processBuffer(t,e)}))):this.updateOverlay(0,t?.data?.message)}))}}}reload(){this.reset()}reset(){this.currentTrack=0,this.paused(),this.setSkipState(),this.preloadTrack()}toggle(){switch(this.status){case 1:this.pause();break;case 0:case 2:this.play();break}}setInfoState(){const t=this.getFirst(".wvpl-info"),e=this.getFirst(".wvpl-infobar"),s=this.getFirst(".wvpl-playlist"),i=["none","info"];this.getTrackCount()>1&&i.push("playlist");const a=i[(i.indexOf(this.info)+1)%i.length];switch(t?.classList.remove("wvpl-info-none","wvpl-info-info","wvpl-info-playlist"),t?.classList.add(`wvpl-info-${a}`),e?.classList.add("wvpl-hidden"),s?.classList.add("wvpl-hidden"),this?.node?.classList.add("wvpl-has-no-playlist"),this.info){case"none":break;case"info":e?.classList.remove("wvpl-hidden");break;case"playlist":e?.classList.remove("wvpl-hidden"),this.getTrackCount()>1&&(s?.classList.remove("wvpl-hidden"),this?.node?.classList.remove("wvpl-has-no-playlist"));break}}toggleInfoState(){const t=["none","info"];this.getTrackCount()>1&&t.push("playlist"),"playlist"==this.info&&1==this.getTrackCount()&&(this.info="info"),this.info=t[(t.indexOf(this.info)+1)%t.length],this.setInfoState()}setSkipState(){let t=this.getFirst(".wvpl-prev"),e=this.getFirst(".wvpl-next");switch(t?.classList.remove("wvpl-disabled"),e?.classList.remove("wvpl-disabled"),!0){case 1===this.getTrackCount():t?.classList.add("wvpl-disabled"),e?.classList.add("wvpl-disabled");break;case 0===this.currentTrack:t?.classList.add("wvpl-disabled");break;case this.currentTrack===this.getTrackCount()-1:e?.classList.add("wvpl-disabled");break}}updateInfo(){if(this.getCurrentTrackIndex>=this.getTrackCount()-1)return!1;this.loading();const t=JSON.parse(JSON.stringify(this.getTrack()));t.stats&&(t.stats.downloads=this.engine.shortenNumber(t.stats.downloads),t.stats.play_count=this.engine.shortenNumber(t.stats.play_count),t.stats.likes=this.engine.shortenNumber(t.stats.likes));const e=t.poster_thumbnail||this.getData("default_thumbnail");this.node.style.setProperty("--poster-image",`url(${e})`);const s=this.node.querySelector(".wvpl-poster"),i=s?s.offsetWidth:this.node.offsetWidth,a=s?s.offsetHeight:this.node.offsetHeight,n=t.poster_srcset||"",r=document.createElement("figure"),o=document.createElement("img");if(r.append(o),o.width=i,o.height=a,o.src=e,o.srcset=n,o.sizes=`${i}px`,setTimeout((()=>{s&&(s.innerHTML="",s.append(r))}),WVPL_ANIMATION_TIME),this.updateLength(),!this.support("infobar"))return void this.loaded();let l=this.getData("template");l+="soundcloud"===t.type?" %soundcloud%":"",setTimeout((()=>{l=null==l?t.title:this.engine.applyTemplate(l,t);const e=this.getFirst(".wvpl-playing-info .wvpl-infoblock");e&&(e.innerHTML=l,l||e.classList.add("wvpl-hidden")),this.loaded()}),WVPL_ANIMATION_TIME)}displayPlaylist(){if(!this.support("playlist"))return;let t=document.createElement("ul"),e=0;for(const s of this.tracks){let i=document.createElement("li");const a=JSON.parse(JSON.stringify(s));a.stats&&(a.stats.downloads=this.engine.shortenNumber(a.stats.downloads),a.stats.play_count=this.engine.shortenNumber(a.stats.play_count),a.stats.likes=this.engine.shortenNumber(a.stats.likes),e=Math.max(e,a.stats.downloads.length,a.stats.play_count.length,a.stats.likes.length)),i.innerHTML=this.engine.applyTemplate(this.getData("playlist_template"),a),t.append(i)}this.getFirst(".wvpl-playlist-wrapper")?.append(t),this.getFirst(".wvpl-playlist")?.style.setProperty("--stats-char-length",`${e}ch`)}updatePlaylistStats(t,e){if(!this.support("playlist"))return;const s=this.getChild(".wvpl-playlist li",t);for(const t of["play_count","downloads","runtime","likes"]){const i=s.querySelector(`.wvpl-${t} .wvpl-value`);i&&(i.innerHTML="runtime"===t?this.engine.secondsToTime(e[t]):this.engine.shortenNumber(e[t]))}}updateStatistics(){const t=this.currentTrack,e={nonce:this.engine.vars.ajax_nonce,id:this.getTrackData("id",t),length:this.getTrackData("length",t),runtime:this.updateRuntime()};e.runtime<1||(this.resetRuntime(),this.engine.ajaxCall("update_statistics",e).then((e=>{e?.success?(e?.data?.stats&&this.setTrackData("stats",e.data.stats,t),this.updatePlaylistStats(t,e.data.stats)):this.log(e?.data?.message)})))}getRuntime(){return this.runtime}updateRuntime(t=!0){if(this.lastStart>0){const e=Date.now();this.runtime+=e-this.lastStart,this.lastStart=t?e:0}return this.getRuntime()}resetRuntime(){this.runtime=0}updateLikes(t){if(0==this.engine.vars.currentUser.ID)return!1;const e=document.querySelectorAll('.wvpl-likes[data-id="'+t.dataset.id+'"]');for(const t of e)t.classList.add("wvpl-spin");const s={nonce:this.engine.vars.ajax_nonce,id:t.dataset.id};this.engine.ajaxCall("update_likes",s).then((s=>{if(s?.success){s?.data?.liked&&this.setTrackData("liked",s.data.liked,t.dataset.index),s?.data?.stats&&this.setTrackData("stats",s.data.stats,t.dataset.index);for(const i of e){i.dataset.event=s?.data?.liked?"unlike":"like",i.classList.toggle("liked",s?.data?.liked),i.classList.remove("wvpl-spin");const e=i.querySelector(".wvpl-value");e&&(e.textContent=this.engine.shortenNumber(this.getTrackData("stats",t.dataset.index).likes))}}else this.log(s?.data?.message)}))}addToCart(t){const e=t.dataset.product_id,s=this.tracks.find((t=>t.product_id==e));let i=document.querySelectorAll('.wvpl-cart[data-product_id="'+e+'"]');if(i)if(s?.product_variations)this.engine.updateVariationForm(s);else{const a={nonce:this.engine.vars.ajax_nonce,product_id:e};for(const t of i)t.classList.add("wvpl-spin");this.engine.ajaxCall("add_to_cart",a).then((e=>{if(e?.data?.fragments){s.in_cart=1;for(const t of i)t.title=this.engine.__("Already in cart: go to cart","waveplayer"),t.classList.remove("wvpl-spin","wvpl-add_to_cart"),t.classList.add("wvpl-in_cart"),t.dataset.event="goToCart",t.dataset.callback="goToCart";for(const t in e.fragments){let s=document.querySelector(t);s&&(s.outerHTML=e.data.fragments[t])}jQuery(document.body).trigger("wc_fragment_refresh"),jQuery(document.body).trigger("added_to_cart",[e.data.fragments,e.data.cart_hash,t]),this.engine.vars.ajax_nonce=e.data.ajax_nonce}else{for(const t of i)t.classList.remove("wvpl-spin");this.log("addToCart",e)}}))}}addVariationToCart(t,e){const s=this.engine.variationPopup.querySelector(".variations_button button.button"),i=document.querySelectorAll('.wvpl-cart[data-product_id="'+e+'"]'),a={nonce:this.engine.vars.ajax_nonce,product_id:t},n=this.tracks.find((t=>t.product_id==e));for(const t of i)t.classList.add("wvpl-spin");s.disabled=!0,this.engine.ajaxCall("add_to_cart",a).then((t=>{if(t.data.fragments){n&&(n.in_cart=1);for(const t of i)t.title=this.engine.__("Already in cart: go to cart","waveplayer"),t.classList.remove("wvpl-spin","wvpl-add_to_cart"),t.classList.add("wvpl-in_cart"),t.dataset.event="goToCart",t.dataset.callback="goToCart";for(const e in t.data.fragments){let s=document.querySelector(e);s&&(s.outerHTML=t.data.fragments[e])}jQuery(document.body).trigger("wc_fragment_refresh"),jQuery(document.body).trigger("added_to_cart",[t.data.fragments,t.data.cart_hash]),this.engine.vars.ajax_nonce=t.data.ajax_nonce}else{for(const t of i)t.classList.remove("wvpl-spin");this.log("addVariationToCart",t)}s.disabled=!1,document.body.classList.remove("wvpl-variation-popup")}))}goToCart(){window.location=this.getData("cartURL")}updateDownloads(t,e){const s=document.querySelectorAll('.wvpl-downloads[data-id="'+t.dataset.id+'"]');for(const t of s)t.classList.add("wvpl-spin");const i=t.querySelector("a.wvpl-link").href,a=this.engine.findTrack(t.dataset.id),n=a?`${a.artist} - ${a.title}.${a.fileformat}`:i;fetch(i).then((t=>t.blob())).then((t=>URL.createObjectURL(t))).then((t=>{const e=document.createElement("a");e.href=t,e.download=n,e.click()}));const r={nonce:this.engine.vars.ajax_nonce,id:t.dataset.id};this.engine.ajaxCall("update_downloads",r).then((e=>{if(e?.success){this.setTrackData("stats",e.data.stats,t.dataset.index),t.querySelector(".wvpl-value")&&(t.querySelector(".wvpl-value").textContent=this.engine.shortenNumber(e.data.stats.downloads));for(const e of s){const s=e.querySelector(".wvpl-value");s&&(s.textContent=this.engine.shortenNumber(this.getTrackData("stats",t.dataset.index).downloads))}}else this.log(e?.data?.message);for(const t of s)t.classList.remove("wvpl-spin")}))}socialShare(t,e){var s,i=encodeURIComponent(t.dataset.url),a=encodeURIComponent(t.dataset.title),n=encodeURIComponent(this.getData("site"));switch(e){case"fb":s="https://www.facebook.com/sharer/sharer.php?display=popup&u="+i;break;case"tw":s="https://twitter.com/intent/tweet?url="+i;break;case"ln":s="https://www.linkedin.com/shareArticle?mini=true&url="+i+"&title="+a+"&source="+n;break}window.open(s,"")}getChildren(t){const e=this.node.querySelectorAll(t);return e.length>0?e:[]}getChild(t,e){return this.getChildren(t)[e]}getFirst(t){return this.node.querySelector(t)}getCurrentTrackIndex(){return this.currentTrack}getCurrentTrack(){return!!this.tracks&&this.tracks[this.currentTrack]}getTrack(t){return null==t&&(t=this.currentTrack),!!this.tracks?.[t]&&this.tracks[t]}setTrack(t,e){null==e&&(e=this.currentTrack),this.tracks&&(this.tracks[e]=t)}removeTrack(t){void 0===t&&(t=this.currentTrack),this.tracks.splice(t,1);this.getChild(".wvpl-playlist-wrapper>ul>li",t)?.remove()}getTrackData(t,e){if(null==e&&(e=this.currentTrack),"peaks"===t){const s=this.tracks[e]?.[t];return"string"==typeof s?s.split("").map((t=>(t.charCodeAt()-48)/100)):Array.isArray(s)?s:null}return this?.tracks?.[e]?.[t]}setTrackData(t,e,s){null==s&&(s=this.currentTrack),this.tracks?.[s]&&(this.tracks[s][t]=e)}getTrackCount(){if(Array.isArray(this.tracks))return this.tracks.length}addClassTo(t,...e){let s=this.getChildren(t);for(let t of s)for(let s of e)t.classList.add(s)}removeClassFrom(t,...e){let s=this.getChildren(t);for(let t of s)for(let s of e)t.classList.remove(s)}addEventListener(t,e){this.node.addEventListener(t,e)}addEventListenerTo(t,e,s){for(let i of this.getChildren(t))i.addEventListener(e,s)}trigger(t,e){e=e||{instance:this,track:this.getTrack(),time:this.getCurrentTime()};let s=new CustomEvent(t,{detail:e,bubbles:!0});this.node.dispatchEvent(s);["play","pause"].includes(t)&&this.engine.gtmPushTimeData(t),["jump","skip","ended"].includes(t)&&this.engine.gtmPushSegmentData(t)}initEvents(){var t=this;this.addEventListenerTo(".wvpl-playing-info","mouseenter",(t=>{})),this.addEventListener("ended",(t=>{this.skip()})),this.addEventListener("peaksloaded",(e=>{const s=e.detail.peaks.join(",").replace(/0\./gi,".");this.updateOverlay(0,"savingPeaks");const i={nonce:t.engine.vars.ajax_nonce,peaks:s,temp_file:t.getTrackData("temp_file"),id:t.getTrackData("id"),type:t.getTrackData("type")||""};t.engine.ajaxCall("write_peaks",i).then((e=>{t.analyzed(),e?.success?(t.preloadTrack(t.clicked),t.getTrackData("temp_file")&&(e?.data?.id&&t.setTrackData("id",e.data.id),t.setTrackData("temp_file",null))):this.log(e?.data?.message)}))})),this.addEventListenerTo("canvas","mouseout",(e=>{1===t.status&&(t.mousePosition=-1)})),this.addEventListenerTo("canvas","mousemove",(e=>{1===t.status&&(t.mousePosition=window.devicePixelRatio*e.offsetX)})),this.addEventListenerTo(".wvpl-volume","mousedown",(e=>{e.preventDefault(),t.startOffset=e.clientX,t.node.querySelector(".wvpl-volume-overlay").innerHTML=Math.round(100*t.engine.getVolume());let s=e.target;t.timerVolumeOverlay=setTimeout((function(){t.volumeDragging=!0,t.addClassTo(".wvpl-volume-overlay","dragging"),t.addClassTo(".wvpl-controls","wvpl-inactive"),t.mouseMoveListener=function(e){e.preventDefault(),s.classList.add("dragging");var i=Math.round(100*(t.engine.getVolume()+(e.clientX-t.startOffset)/(t.getFirst(".wvpl-interface").offsetWidth*window.devicePixelRatio/2)))/100;i>=0&&i<=1&&(t.engine.setVolume(i),t.getFirst(".wvpl-volume-overlay").innerHTML=Math.round(100*i),s.classList.toggle("wvpl-volume_off",0==i))},t.mouseUpListener=function(s){e.preventDefault(),document.removeEventListener("mousemove",t.mouseMoveListener),document.removeEventListener("mouseup",t.mouseUpListener),t.node.querySelector(".dragging").classList.remove("dragging"),t.node.querySelector(".wvpl-controls").classList.remove("wvpl-inactive"),t.volumeDragging=!1},document.addEventListener("mousemove",t.mouseMoveListener),document.addEventListener("mouseup",t.mouseUpListener)}),150)})),this.addEventListenerTo(".wvpl-volume","mouseup",(e=>{clearTimeout(t.timerVolumeOverlay),t.volumeDragging||(this.engine.toggleMute(),e.currentTarget.classList.toggle("wvpl-volume_off",this.engine.isMuted()))}))}log(...t){this.engine.isDebugMode()}}document.addEventListener("readystatechange",(function(t){const e=window.wvplVars?.is_gutenberg?"interactive":"complete";if(document.readyState!==e)return!1;const s=jQuery;let i=window;for(;!i.wp;)i=i.parent;if(void 0===i.wvplVars)return!1;setTimeout((()=>new WVPLEngine(i)),0),s.fn.waveplayer=function(t,...e){return this.each((function(i,a){t=t||"init";var n=null,r=s(a).attr("data-instance_id");if(n=WavePlayer.getInstanceById(r))return"object"!=typeof e&&(e=[e]),void n[t].apply(n,e)}))}})),document.addEventListener("waveplayer.engine.starting",(t=>{window.WavePlayer=t.detail.engine;const e=jQuery,s=new CustomEvent("waveplayer.engine.ready",{detail:{engine:t.detail.engine}});document.dispatchEvent(s),document.addEventListener("click",(t=>{if(!document.querySelector(".waveplayer"))return!1;WavePlayer.resume();let e=t.target;const s=t.target.closest("li.wvpl-product-variation");if(s){const t=s.closest("#wvpl-variation-popup").dataset.instance;return void WavePlayer.getInstanceById(t).addVariationToCart(s.dataset.variation,s.dataset.product)}const i=e.closest(".waveplayer")||WavePlayer.node;if(!i)return;const a=WavePlayer.getInstanceById(i.dataset.instance_id);if(e.matches(".wvpl-share-popup li")){const t=e.closest(".wvpl-share"),s="share",i=e.dataset.social;a.trigger(s),a.socialShare.apply(a,[t,i])}if(e.matches(".wvpl-button")){if(!e.matches(".wvpl-downloads")&&e.querySelector("a.wvpl-link")&&e.click(),e.matches(".wvpl-product")){return void e.querySelector("a.wvpl-link")?.click()}const t=e.dataset.event;t&&a.trigger(t);const s=e.dataset.callback;if(!s)return;a[s].apply(a,[e])}else if(!e.matches(".wvpl-link")||!e.attributes.download){if(e.matches(".wvpl-info"))return t.preventDefault(),void a.toggleInfoState();if(e.matches(".wvpl-play"))return t.preventDefault(),void a.toggle();if(e.matches(".wvpl-prev:not(.wvpl-disabled), .wvpl-next:not(.wvpl-disabled)")){t.preventDefault();const s=e.classList.contains("wvpl-next");a.skip(s)}else{if(e.matches("canvas"))return t.preventDefault(),void(1==a.status?(a.updateRuntime(),a.trigger("jump"),WavePlayer.setCurrentTime(WavePlayer.getDuration()*t.offsetX/e.offsetWidth)):a.play());if(e.matches(".wvpl-playlist li")||e.matches(".wvpl-playlist li>*:not(.wvpl-icon)")){"LI"!==e.tagName&&(e=e.closest("li")),t.preventDefault();let s=0,i=e;for(s=0;i=i.previousSibling;s++);a.skipTo(s)}else if(e.matches("button.wvpl-sticky-player-toggle"))WavePlayer.toggleStickyPlayer();else{if(e.matches("#wvpl-sticky-player canvas"))return t.preventDefault(),void a.maybeSwitch().then((()=>{a.play()})).catch((()=>{if(1==a.status){const e=t.currentTarget;a.updateRuntime(),WavePlayer.setCurrentTime(WavePlayer.getDuration()*t.offsetX/e.offsetWidth)}else a.play()}));if(e.matches("#wvpl-sticky-player .wvpl-play"))a.toggle();else if(e.matches(".remove_from_cart_button")){const t=e.dataset.product_id,s=document.querySelectorAll('.wvpl-cart[data-product_id="'+t+'"]');for(const t of s)t.classList.add("wvpl-spin")}else if(e.matches("#wvpl-variation-popup .woocommerce-variation-add-to-cart button")){t.preventDefault();const s=e.closest(".woocommerce-variation-add-to-cart"),i=s.querySelector('input[name="product_id"]').value,n=s.querySelector("input.variation_id").value;n>0&&a.addVariationToCart(n,i)}else e.matches("#wvpl-variation-popup")&&document.body.classList.remove("wvpl-variation-popup")}}}})),document.addEventListener("click",(t=>{if(t.target.matches("[data-marker]")){t.preventDefault();const e=WavePlayer.timeToSeconds(t.target.dataset.marker);e&&WavePlayer.play(e)}else;})),window.addEventListener("resize",(t=>{window.frameElement||setTimeout((function(){WavePlayer.redrawAllInstances()}),50)})),document.addEventListener("visibilitychange",(t=>{if("hidden"===document.visibilityState){let t=WavePlayer.getCurrentInstance();t&&t.updateStatistics()}}));let i=!1;document.addEventListener("mousedown",(t=>{t.target.matches(".wvpl-volume-slider .touchable")&&(i=!0,WavePlayer.setVolume(t.offsetX/t.target.offsetWidth))})),document.addEventListener("mousemove",(t=>{t.target.matches(".wvpl-volume-slider .touchable")&&i&&"touchable"===t.target.className&&WavePlayer.setVolume(t.offsetX/t.target.offsetWidth)})),document.addEventListener("mouseup",(t=>{i=!1}));let a="";document.addEventListener("timeupdate",(t=>{if(t.target.matches(".waveplayer")){const e=document.querySelectorAll("[data-marker]"),s=WavePlayer.secondsToTime(t.detail.time);if(e.length&&s!==a){let t=e[0];for(let i=1;i<e.length&&!(WavePlayer.timeToSeconds(e[i].dataset.marker)>WavePlayer.timeToSeconds(s));i++)t=e[i];for(let t of e)t.classList.remove("current-time-marker");if(t.classList.add("current-time-marker"),WavePlayer.getOption("scroll_to_marker")){const e=t.dataset.behavior?t.dataset.behavior:"smooth",s=t.dataset.block?t.dataset.block:"center";t.scrollIntoView({behavior:e,block:s})}a=s}}})),e(document.body).on("added_to_cart",((t,s,i,a)=>{if(!a)return;const n=a.data("product_id");WavePlayer.updateTrackCartStatus(n,"add"),e(`.wvpl-cart[data-product_id=${n}]`).attr("title",WavePlayer.__("Already in cart: go to cart","waveplayer")).attr("data-event","goToCart").attr("data-callback","goToCart").addClass("wvpl-in_cart").removeClass("wvpl-add_to_cart").removeClass("wvpl-spin")})),e(document.body).on("removed_from_cart",((t,s,i,a)=>{if(!a)return;const n=a.data("product_id");WavePlayer.updateTrackCartStatus(n,"remove"),e(`.wvpl-cart[data-product_id=${n}]`).attr("title",WavePlayer.__("Add to cart","waveplayer")).attr("data-event","addToCart").attr("data-callback","addToCart").addClass("wvpl-add_to_cart").removeClass("wvpl-in_cart").removeClass("wvpl-spin")}))}));