@salla.sa/twilight 2.0.213 → 2.0.214
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/@salla.sa/twilight.min.js +12 -9
- package/dist/@salla.sa/twilight.min.js.map +1 -1
- package/dist/cjs/main.js +12 -9
- package/dist/cjs/main.js.map +1 -1
- package/dist/esm/main.js +12 -9
- package/dist/esm/main.js.map +1 -1
- package/package.json +1 -1
- package/types/api/cart.d.ts +27 -8
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).salla={})}(this,function(exports){"use strict";let notifier=function(e,t,s){return alert(e,t,s)},setNotifier=function(e){notifier=e},fire=function(e,t,s){return notifier(e,t,s)},error$1=function(e,t){return notifier(e,types.error,t)},info=function(e,t){return notifier(e,types.info,t)},success=function(e,t){return notifier(e,types.success,t)},logger=function(...e){return console.log(...e)},setLogger=function(e){logger=e},log=function(...e){return logger(...e)};var sallaInitiated=function(){var e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach(e=>{error$1(decodeURI(e.replace("?danger=","").replace("&danger=","")))})},types={error:"error",success:"success",info:"info"},Notify={fire:fire,setNotifier:setNotifier,log:log,setLogger:setLogger,error:error$1,success:success,info:info,sallaInitiated:sallaInitiated,types:types};class BaseEvent{constructor(e){this.parent=e,this.events={},this.namespace="";e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)})}createDynamicEventFuns(s){if(!this[s]){let t=this;this[s]=function(...e){return t.dispatch(s,...e)}}}createDynamicListenerFuns(s){var e="on"+s.charAt(0).toUpperCase()+s.slice(1);if(!this[e]){let t=this;this[e]=function(e){return t.on(s,e)}}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+this.parent.delimiter+e}dispatch(e,...t){return this.parent.dispatch(this.getEventName(e),...t)}on(e,t){this.parent.addListener(this.getEventName(e),t)}register(e,t){this.on(e,t)}registerEventTemporary(e,t,s){s=s||1,emitter.many(e,s,t)}}class CartEvents extends BaseEvent{constructor(e){super(e),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",summaryFetched:"summary.fetched",summaryNotFetched:"summary.not.fetched",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset"},this.after_init()}updated(e){return salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.offer.event.existed(e.offer),salla.storage.set("cart.summary",e={total:e.cart.total,items_total:e.cart.sub_total,total_discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e)):(salla.log("Cart summary not an object!",e),this.dispatch("updated"))}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}summaryFetched(e){this.updated(e)}fullSummaryFetched(e){this.updated(e)}clearCartSummary(){var e=salla.storage.get("cart_widget_summary");e&&(e.count||e.items||e.items_count)&&salla.cart.api.summary()}}class GiftEvents extends BaseEvent{constructor(e){super(e),this.namespace="gift",this.events={buyingSucceeded:"buying.succeeded",buyingFailed:"buying.failed"},this.after_init()}}class LoyaltyEvents extends BaseEvent{constructor(e){super(e),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed"},this.after_init()}}class AuthEvents extends BaseEvent{constructor(e){super(e),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",codeReSent:"code.re-sent",codeNotReSent:"code.not.re-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",tokenFetched:"token.fetched",refreshFailed:"refresh.failed"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null):this.next_event=null,this.dispatch("login",...arguments)}verified(e){return dataLayer&&(dataLayer[0].customer=e.customer),this.dispatch("verified",...arguments)}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}}class SearchEvents extends BaseEvent{constructor(e){super(e),this.namespace="search",this.events={finished:"finished",failed:"failed"},this.after_init()}}class WishlistEvents extends BaseEvent{constructor(e){super(e),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}}class CommentEvents extends BaseEvent{constructor(e){super(e),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}}class OrderEvents extends BaseEvent{constructor(e){super(e),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",reOrdered:"re.ordered",reOrderFailed:"re.order.failed"},this.after_init()}}class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class DocumentEvents extends BaseEvent{constructor(e){super(e),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init()}onClick(e,t){this.fireCallableFuns("click",e,t)}onChange(e,t){this.fireCallableFuns("change",e,t)}onSubmit(e,t){this.fireCallableFuns("submit",e,t)}onKeyup(e,t){this.fireCallableFuns("keyup",e,t)}fireCallableFuns(e,t,s){this.on(e,e=>{"function"!=typeof t?"function"==typeof s&&e.target.matches(t)&&s(e):t(e)})}fireEvent(e,t,...s){return this.fireEventForElements(e,t,!1,...s)}fireEventForAll(e,t,...s){return this.fireEventForElements(e,t,!0,...s)}fireEventForElements(e,t,s,...r){if("string"==typeof e){if(s)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,!1,...r));e=document.querySelector(e)}{if(e)return s=new CustomEvent(t,...r),e.dispatchEvent(s);salla.log("Faild To get element to fire event: "+t)}}}class ProductEvents extends BaseEvent{constructor(e){super(e),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed"},this.after_init()}}class OfferEvents extends BaseEvent{constructor(e){super(e),this.namespace="offer",this.events={existed:"existed",increased:"increase",increaseFailed:"increase.failed",fetchDetailsFailed:"fetch.details.failed",detailsFetched:"details.fetched"},this.after_init()}}class CouponEvents extends BaseEvent{constructor(e){super(e),this.namespace="coupon",this.events={added:"added",removed:"removed",addedFailed:"added.failed",removedFailed:"removed.failed"},this.after_init()}added(e,t){return salla.event.cart.updated(e.data),this.dispatch("added",e,t)}removed(e,t){return salla.event.cart.updated(e.data),this.dispatch("removed",e,t)}}class FeedbackEvents extends BaseEvent{constructor(e){super(e),this.namespace="feedback",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productRated:"product.rated",productFailed:"product.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init()}}class CurrencyEvents extends BaseEvent{constructor(e){super(e),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}changed(...e){return salla.cart.api.summary().then(()=>this.dispatch("changed",...e))}}class TwilightEvents extends BaseEvent{constructor(e){super(e),this.namespace="twilight",this.events={initiated:"initiated"},this.after_init()}}class ScopeEvents extends BaseEvent{constructor(e){super(e),this.namespace="scope",this.events={},this.after_init()}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},eventemitter2$1={exports:{}},eventemitter2=(!function(e){function h(){this._events={},this._conf&&t.call(this,this._conf)}function t(e){e&&((this._conf=e).delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==y&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function d(e,t){var s="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";this.verboseMemoryLeak&&(s+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning?((t=new Error(s)).name="MaxListenersExceededWarning",t.emitter=this,t.count=e,process.emitWarning(t)):(console.error(s),console.trace&&console.trace())}function c(e,t,s){var r=arguments.length;switch(r){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,s];default:for(var i=new Array(r);r--;)i[r]=arguments[r];return i}}function s(e,t){for(var s={},r=e.length,i=t?value.length:0,n=0;n<r;n++)s[e[n]]=n<i?t[n]:y;return s}function p(e,t,s){var r,i;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(s.on||s.off)&&(r=s.on,i=s.off),t.addEventListener?(r=t.addEventListener,i=t.removeEventListener):t.addListener?(r=t.addListener,i=t.removeListener):t.on&&(r=t.on,i=t.off),!r&&!i)throw Error("target does not implement any known event API");if("function"!=typeof r)throw TypeError("on method must be a function");if("function"!=typeof i)throw TypeError("off method must be a function");this._on=r,this._off=i;s=e._observers;s?s.push(this):e._observers=[this]}function f(e,t,s,r){var i=Object.assign({},t);if(!e)return i;if("object"!=typeof e)throw TypeError("options must be an object");var n,a,o,l=Object.keys(e),c=l.length;function u(e){throw Error('Invalid "'+n+'" option value'+(e?". Reason: "+e:""))}for(var h=0;h<c;h++){if(n=l[h],!r&&!b.call(t,n))throw Error('Unknown "'+n+'" option');(a=e[n])!==y&&(o=s[n],i[n]=o?o(a,u):a)}return i}function r(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function i(i){var n="value must be type of "+i.join("|"),a=i.length,r=i[0],o=i[1];return 1===a?function(e,t){if(typeof e===r)return e;t(n)}:2===a?function(e,t){var s=typeof e;if(s===r||s===o)return e;t(n)}:function(e,t){for(var s=typeof e,r=a;0<r--;)if(s===i[r])return e;t(n)}}function l(a,o,l){var c,u,h,d=0,p=new a(function(t,s,e){function r(){u=u&&null,d&&(clearTimeout(d),d=0)}l=f(l,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),c=!l.overload&&"function"==typeof a.prototype.cancel&&"function"==typeof e;function i(e){r(),t(e)}function n(e){r(),s(e)}c?o(i,n,e):(u=[function(e){n(e||Error("canceled"))}],o(i,n,function(e){if(h)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");u.push(e)}),h=!0),0<l.timeout&&(d=setTimeout(function(){var e=Error("timeout");e.code="ETIMEDOUT",d=0,p.cancel(e),s(e)},l.timeout))});return c||(p.cancel=function(e){if(u){for(var t=u.length,s=1;s<t;s++)u[s](e);u[0](e),u=null}}),p}function g(e){var t=this._observers;if(!t)return-1;for(var s=t.length,r=0;r<s;r++)if(t[r]._target===e)return r;return-1}function _(e,t,s,r,i){if(!s)return null;if(0===r){var n=typeof t;if("string"==n){var a,o,l=0,c=0,u=this.delimiter,h=u.length;if(-1!==(o=t.indexOf(u))){for(a=new Array(5);a[l++]=t.slice(c,o),-1!==(o=t.indexOf(u,c=o+h)););a[l++]=t.slice(c),t=a,i=l}else t=[t],i=1}else i="object"==n?t.length:(t=[t],1)}var d,p,f,g,m,v,y=null,b=t[r],w=t[r+1];if(r===i)s._listeners&&(y=("function"==typeof s._listeners?e&&e.push(s._listeners):e&&e.push.apply(e,s._listeners),[s]));else{if("*"===b){for(o=(m=A(s)).length;0<o--;)"_listeners"!==(d=m[o])&&(v=_(e,t,s[d],r+1,i))&&(y?y.push.apply(y,v):y=v);return y}if("**"===b){for((g=r+1===i||r+2===i&&"*"===w)&&s._listeners&&(y=_(e,t,s,i,i)),o=(m=A(s)).length;0<o--;)"_listeners"!==(d=m[o])&&((v="*"===d||"**"===d?(s[d]._listeners&&!g&&(v=_(e,t,s[d],i,i))&&(y?y.push.apply(y,v):y=v),_(e,t,s[d],r,i)):_(e,t,s[d],d===w?r+2:r,i))&&(y?y.push.apply(y,v):y=v));return y}s[b]&&(y=_(e,t,s[b],r+1,i))}if((n=s["*"])&&_(e,t,n,r+1,i),p=s["**"])if(r<i)for(p._listeners&&_(e,t,p,i,i),o=(m=A(p)).length;0<o--;)"_listeners"!==(d=m[o])&&(d===w?_(e,t,p[d],r+2,i):d===b?_(e,t,p[d],r+1,i):((f={})[d]=p[d],_(e,t,{"**":f},r+1,i)));else p._listeners?_(e,t,p,i,i):p["*"]&&p["*"]._listeners&&_(e,t,p["*"],i,i);return y}function u(e,t,s,r){for(var i,n,a,o=A(e),l=o.length,c=e._listeners;0<l--;)i=e[a=o[l]],n="_listeners"===a?s:s?s.concat(a):[a],a=r||"symbol"==typeof a,c&&t.push(a?n:n.join(this.delimiter)),"object"==typeof i&&u.call(this,i,t,n,a);return t}function m(e){for(var t,s,r,i=A(e),n=i.length;0<n--;)(t=e[s=i[n]])&&(r=!0,"_listeners"===s||m(t)||delete e[s]);return r}function v(e,t,s){this.emitter=e,this.event=t,this.listener=s}function n(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,t.call(this,e)}var y,b,w,S,E,a,x,A,o,k,L;b=Object.hasOwnProperty,w=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},S="object"==typeof process&&"function"==typeof process.nextTick,E="function"==typeof Symbol,a="object"==typeof Reflect,x="function"==typeof setImmediate?setImmediate:setTimeout,A=E?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys,Object.assign(p.prototype,{subscribe:function(s,r,i){function t(){var e=c.apply(null,arguments),t={data:e,name:r,original:s};i?!1!==i.call(a,t)&&o.emit.apply(o,[t.name].concat(e)):o.emit.apply(o,[r].concat(e))}var n=this,a=this._target,o=this._emitter,l=this._listeners;if(l[s])throw Error("Event '"+s+"' is already listening");this._listenersCount++,o._newListener&&o._removeListener&&!n._onNewListener?(this._onNewListener=function(e){e===r&&null===l[s]&&(l[s]=t,n._on.call(a,s,t))},o.on("newListener",this._onNewListener),this._onRemoveListener=function(e){e===r&&!o.hasListeners(e)&&l[s]&&(l[s]=null,n._off.call(a,s,t))},l[s]=null,o.on("removeListener",this._onRemoveListener)):(l[s]=t,n._on.call(a,s,t))},unsubscribe:function(e){var t,s,r,i=this,n=this._listeners,a=this._emitter,o=this._off,l=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function c(){i._onNewListener&&(a.off("newListener",i._onNewListener),a.off("removeListener",i._onRemoveListener),i._onNewListener=null,i._onRemoveListener=null);var e=g.call(a,i);a._observers.splice(e,1)}if(e)(t=n[e])&&(o.call(l,e,t),delete n[e],--this._listenersCount||c());else{for(r=(s=A(n)).length;0<r--;)e=s[r],o.call(l,e,n[e]);this._listeners={},this._listenersCount=0,c()}}}),o=i(["function"]),k=i(["object","function"]),v.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},(n.EventEmitter2=n).prototype.listenTo=function(c,e,u){if("object"!=typeof c)throw TypeError("target musts be an object");var h=this;function t(e){if("object"!=typeof e)throw TypeError("events must be an object");for(var t,s=u.reducers,r=g.call(h,c),i=-1===r?new p(h,c,u):h._observers[r],n=A(e),a=n.length,o="function"==typeof s,l=0;l<a;l++)t=n[l],i.subscribe(t,e[t]||t,o?s:s&&s[t])}return u=f(u,{on:y,off:y,reducers:y},{on:o,off:o,reducers:k}),w(e)?t(s(e)):t("string"==typeof e?s(e.split(/\s+/)):e),this},n.prototype.stopListeningTo=function(e,t){var s=this._observers;if(!s)return!1;var r,i=s.length,n=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;0<i--;)r=s[i],e&&r._target!==e||(r.unsubscribe(t),n=!0);return n},n.prototype.delimiter=".",n.prototype.setMaxListeners=function(e){e!==y&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},n.prototype.getMaxListeners=function(){return this._maxListeners},n.prototype.event="",n.prototype.once=function(e,t,s){return this._once(e,t,!1,s)},n.prototype.prependOnceListener=function(e,t,s){return this._once(e,t,!0,s)},n.prototype._once=function(e,t,s,r){return this._many(e,1,t,s,r)},n.prototype.many=function(e,t,s,r){return this._many(e,t,s,!1,r)},n.prototype.prependMany=function(e,t,s,r){return this._many(e,t,s,!0,r)},n.prototype._many=function(e,t,s,r,i){var n=this;if("function"!=typeof s)throw new Error("many only accepts instances of Function");function a(){return 0==--t&&n.off(e,a),s.apply(this,arguments)}return a._origin=s,this._on(e,a,r,i)},n.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,s,r,i,n,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return!1;if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(s=a.length,E)for(r=0;r<s;r++)if("symbol"==typeof a[r]){n=!0;break}n||(a=a.join(this.delimiter))}var l,c=arguments.length;if(this._all&&this._all.length)for(r=0,s=(l=this._all.slice()).length;r<s;r++)switch(this.event=a,c){case 1:l[r].call(this,a);break;case 2:l[r].call(this,a,arguments[1]);break;case 3:l[r].call(this,a,arguments[1],arguments[2]);break;default:l[r].apply(this,arguments)}if(o)_.call(this,l=[],e,this.listenerTree,0,s);else{if("function"==typeof(l=this._events[a])){switch(this.event=a,c){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(c-1),i=1;i<c;i++)t[i-1]=arguments[i];l.apply(this,t)}return!0}l=l&&l.slice()}if(l&&l.length){if(3<c)for(t=new Array(c-1),i=1;i<c;i++)t[i-1]=arguments[i];for(r=0,s=l.length;r<s;r++)switch(this.event=a,c){case 1:l[r].call(this);break;case 2:l[r].call(this,arguments[1]);break;case 3:l[r].call(this,arguments[1],arguments[2]);break;default:l[r].apply(this,t)}return!0}if(this.ignoreErrors||this._all||"error"!==a)return!!this._all;throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.")},n.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,s,r,i,n,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(r=a.length,E)for(i=0;i<r;i++)if("symbol"==typeof a[i]){t=!0;break}t||(a=a.join(this.delimiter))}var l,c=[],u=arguments.length;if(this._all)for(i=0,r=this._all.length;i<r;i++)switch(this.event=a,u){case 1:c.push(this._all[i].call(this,a));break;case 2:c.push(this._all[i].call(this,a,arguments[1]));break;case 3:c.push(this._all[i].call(this,a,arguments[1],arguments[2]));break;default:c.push(this._all[i].apply(this,arguments))}if(o?_.call(this,l=[],e,this.listenerTree,0):l=this._events[a],"function"==typeof l)switch(this.event=a,u){case 1:c.push(l.call(this));break;case 2:c.push(l.call(this,arguments[1]));break;case 3:c.push(l.call(this,arguments[1],arguments[2]));break;default:for(s=new Array(u-1),n=1;n<u;n++)s[n-1]=arguments[n];c.push(l.apply(this,s))}else if(l&&l.length){if(l=l.slice(),3<u)for(s=new Array(u-1),n=1;n<u;n++)s[n-1]=arguments[n];for(i=0,r=l.length;i<r;i++)switch(this.event=a,u){case 1:c.push(l[i].call(this));break;case 2:c.push(l[i].call(this,arguments[1]));break;case 3:c.push(l[i].call(this,arguments[1],arguments[2]));break;default:c.push(l[i].apply(this,s))}}else if(!this.ignoreErrors&&!this._all&&"error"===a)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(c)},n.prototype.on=function(e,t,s){return this._on(e,t,!1,s)},n.prototype.prependListener=function(e,t,s){return this._on(e,t,!0,s)},n.prototype.onAny=function(e){return this._onAny(e,!1)},n.prototype.prependAny=function(e){return this._onAny(e,!0)},n.prototype.addListener=n.prototype.on,n.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},n.prototype._on=function(e,t,s,r){if("function"==typeof e)return this._onAny(e,t),this;if("function"!=typeof t)throw new Error("on only accepts instances of Function");this._events||h.call(this);var i=this;return r!==y&&(t=(r=function(e,t,s){if(!0===s)i=!0;else if(!1===s)r=!0;else{if(!s||"object"!=typeof s)throw TypeError("options should be an object or true");var r=s.async,i=s.promisify,n=s.nextTick,a=s.objectify}if(r||n||i){var o=t,s=t._origin||t;if(n&&!S)throw Error("process.nextTick is not supported");i===y&&(i="AsyncFunction"===t.constructor.name),(t=function(){var e=arguments,t=this,s=this.event;return i?n?Promise.resolve():new Promise(function(e){x(e)}).then(function(){return t.event=s,o.apply(t,e)}):(n?process.nextTick:x)(function(){t.event=s,o.apply(t,e)})})._async=!0,t._origin=s}return[t,a?new v(this,e,t):this]}.call(this,e,t,r))[0],i=r[1]),this._newListener&&this.emit("newListener",e,t),this.wildcard?function(e,t,s){var r,i=0,n=0,a=this.delimiter,o=a.length;if("string"==typeof e)if(-1!==(u=e.indexOf(a))){for(r=new Array(5);r[i++]=e.slice(n,u),-1!==(u=e.indexOf(a,n=u+o)););r[i++]=e.slice(n)}else r=[e],i=1;else i=(r=e).length;if(1<i)for(u=0;u+1<i;u++)if("**"===r[u]&&"**"===r[u+1])return;for(var l,c=this.listenerTree,u=0;u<i;u++)if(c=c[l=r[u]]||(c[l]={}),u===i-1)return c._listeners?("function"==typeof c._listeners&&(c._listeners=[c._listeners]),s?c._listeners.unshift(t):c._listeners.push(t),!c._listeners.warned&&0<this._maxListeners&&c._listeners.length>this._maxListeners&&(c._listeners.warned=!0,d.call(this,c._listeners.length,l))):c._listeners=t,!0;return!0}.call(this,e,t,s):this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),s?this._events[e].unshift(t):this._events[e].push(t),!this._events[e].warned&&0<this._maxListeners&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,d.call(this,this._events[e].length,e))):this._events[e]=t,i},n.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var s=[];if(this.wildcard){var r="string"==typeof e?e.split(this.delimiter):e.slice();if(!(s=_.call(this,null,r,this.listenerTree,0)))return this}else{if(!this._events[e])return this;a=this._events[e],s.push({_listeners:a})}for(var i=0;i<s.length;i++){var n=s[i],a=n._listeners;if(w(a)){for(var o=-1,l=0,c=a.length;l<c;l++)if(a[l]===t||a[l].listener&&a[l].listener===t||a[l]._origin&&a[l]._origin===t){o=l;break}if(o<0)continue;return(this.wildcard?n._listeners:this._events[e]).splice(o,1),0===a.length&&(this.wildcard?delete n._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(a===t||a.listener&&a.listener===t||a._origin&&a._origin===t)&&(this.wildcard?delete n._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&m(this.listenerTree),this},n.prototype.offAny=function(e){var t,s=0,r=0;if(e&&this._all&&0<this._all.length){for(s=0,r=(t=this._all).length;s<r;s++)if(e===t[s])return t.splice(s,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(s=0,r=t.length;s<r;s++)this.emit("removeListenerAny",t[s]);this._all=[]}return this},n.prototype.removeListener=n.prototype.off,n.prototype.removeAllListeners=function(e){if(e===y)return this._events&&h.call(this),this;if(this.wildcard){var t,s=_.call(this,null,e,this.listenerTree,0);if(!s)return this;for(t=0;t<s.length;t++)s[t]._listeners=null;this.listenerTree&&m(this.listenerTree)}else this._events&&(this._events[e]=null);return this},n.prototype.listeners=function(e){var t,s,r,i,n,a=this._events;if(e===y){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!a)return[];for(i=(t=A(a)).length,r=[];0<i--;)"function"==typeof(s=a[t[i]])?r.push(s):r.push.apply(r,s);return r}if(this.wildcard){if(!(n=this.listenerTree))return[];var o=[],l="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,o,l,n,0),o}return a&&(s=a[e])?"function"==typeof s?[s]:s:[]},n.prototype.eventNames=function(e){var t=this._events;return this.wildcard?u.call(this,this.listenerTree,[],null,e):t?A(t):[]},n.prototype.listenerCount=function(e){return this.listeners(e).length},n.prototype.hasListeners=function(e){if(this.wildcard)return s=[],t="string"==typeof e?e.split(this.delimiter):e.slice(),_.call(this,s,t,this.listenerTree,0),0<s.length;var t=this._events,s=this._all;return!!(s&&s.length||t&&(e===y?A(t).length:t[e]))},n.prototype.listenersAny=function(){return this._all||[]},n.prototype.waitFor=function(i,n){var a=this,e=typeof n;return"number"==e?n={timeout:n}:"function"==e&&(n={filter:n}),l((n=f(n,{timeout:0,filter:y,handleError:!1,Promise:Promise,overload:!1},{filter:o,Promise:r})).Promise,function(t,s,e){function r(){var e=n.filter;e&&!e.apply(a,arguments)||(a.off(i,r),n.handleError?(e=arguments[0])?s(e):t(c.apply(null,arguments).slice(1)):t(c.apply(null,arguments)))}e(function(){a.off(i,r)}),a._on(i,r,!1)},{timeout:n.timeout,overload:n.overload})},L=n.prototype,Object.defineProperties(n,{defaultMaxListeners:{get:function(){return L._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");L._maxListeners=e},enumerable:!0},once:{value:function(a,o,e){return l((e=f(e,{Promise:Promise,timeout:0,overload:!1},{Promise:r})).Promise,function(e,t,s){var r;if("function"==typeof a.addEventListener)return r=function(){e(c.apply(null,arguments))},s(function(){a.removeEventListener(o,r)}),a.addEventListener(o,r,{once:!0});function i(){n&&a.removeListener("error",n),e(c.apply(null,arguments))}var n;"error"!==o&&(n=function(e){a.removeListener(o,i),t(e)},a.once("error",n)),s(function(){n&&a.removeListener("error",n),a.removeListener(o,i)}),a.once(o,i)},{timeout:e.timeout,overload:e.overload})},writable:!0,configurable:!0}}),Object.defineProperties(L,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=n}(eventemitter2$1),eventemitter2$1.exports);class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.cart=new CartEvents(this),this.gift=new GiftEvents(this),this.loyalty=new LoyaltyEvents(this),this.auth=new AuthEvents(this),this.search=new SearchEvents(this),this.wishlist=new WishlistEvents(this),this.comment=new CommentEvents(this),this.order=new OrderEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.document=new DocumentEvents(this),this.product=new ProductEvents(this),this.offer=new OfferEvents(this),this.coupon=new CouponEvents(this),this.feedback=new FeedbackEvents(this),this.currency=new CurrencyEvents(this),this.twilight=new TwilightEvents(this),this.scope=new ScopeEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let s=this;Object.keys(salla).forEach(t=>{"object"==typeof(t=salla[t])&&(s.callSallaInitiate(t),Object.keys(t).forEach(e=>{s.callSallaInitiate(t[e])}))})}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(s,...r){let t=s.split("::")[0],i=salla.api.apis[t],n=!1;if(i&&Object.keys(i.hooksSelectores).forEach(e=>{i.hooksSelectores[e]===s&&(salla.log(`'salla.${t}.${e}(...)' triggered using event '${s}'`),i[e].call(i,...r),n=!0)}),!n){this.emit(s,...r),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:s},...r.values())),this.ingoreLogEvents.includes(s)||!salla.config.get("debug")&&!this.logableEvents.includes(s)||salla.notify.log(s,...r);let t=this;Object.keys(this.globalListners).forEach(function(e){t.globalListners[e](s,...r)}),this.dispatchMobileEvent(s,{...r.values()})}}dispatchEvents(e){if(e&&"object"==typeof e)for(var[t,s]of Object.entries(e))this.dispatch(t,s);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e),console.log("The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e),console.log("The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.hooksSelectores={},this.endpointsMethods={},this.endpointsHeaders={};e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,s=null){let r=this,i=Array.isArray(e),n=i?this.getUrl(...e):this.getUrl(e);e=i?e[0]:e,s=s||this.endpointsMethods[e]||"post";var a,o=this.endpointsHeaders[e];"get"===s&&t instanceof FormData&&(a={},Array.from(t.entries()).forEach(function(e){a[e[0]]=e[1]}),t={params:a}),o&&"get"===s&&(t=t?Object.assign(t,o):o);let l={namespace:this.namespace,action:e,hook:this.hooksSelectores[e]||e,url:n,payload:t,method:s,headers:o};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise(()=>{throw e})}this.webEndpoints.includes(e)||"http"===n.substring(0,4)||(n=salla.config.get("store.api")+n);let c=event?.currentTarget,u=!1;return(u="SALLA-BUTTON"===c?.tagName?!0:u)&&c?.load(),this.parent[s](n,t,{headers:o}).then(e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),r.handleAfterResponseActions(e),e)).catch(e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),r.handleErrorResponse(e),e})}request(e,t,s=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,s)):this.normalRequest(e,t,s)}getUrl(e){let t=this.endpoints[e]||e;var s=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(s,arguments[e]);return t}withInjectData(e,t){return{element:e,data:e.getElementSallaData(t)}}handleAfterResponseActions(response){if(!response)return;let{data,googleTags=null}=response,withGoogleTags=data&&data.googleTags?data.googleTags:googleTags;if(dataLayer&&withGoogleTags&&dataLayer.push(withGoogleTags),this.renderSections(response),response.events||response.error&&response.error.events){let e=response.events||response.error.events;e=JSON.parse(e),Object.keys(e).forEach(function(t){salla.event.dispatch(t,e[t])})}if(this.showAlert(response),response.runJavascript)try{eval(response.runJavascript)}catch(e){salla.log(e)}response.token&&salla.event.auth.tokenFetched(response.token)}renderSections(s){s.sections&&Object.keys(s.sections).forEach(t=>{document.querySelectorAll(t.toSelector()).forEach(function(e){e.innerHTML=s.sections[t]})})}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.message&&e.hasOwnProperty("success")?salla.notify.fire(e.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let s=e.response.data.error.fields,r=[];Object.keys(s).forEach(e=>{let t=s[e];Array.isArray(t)?t.forEach(e=>r.push(e)):r.push(t)});var t=(1<r.length?"* ":"")+r.join("\n* ");salla.error(t,e)}event(){return salla.event[this.className]}getPossibleValue(s,r,e=!1){if(s){if("object"!=typeof s)return s;let t;for(let e=0;e<r.length&&!(t=s[r[e]])&&!(s instanceof FormData&&(t=s.get(r[e])));e++);return"object"!=typeof(t=t||s)||e?t:void 0}}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(s,r=!0){return new Promise((e,t)=>(r?e:t)(s))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!1)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",summary:"cart/{cart}/summary",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",status:"cart/{cart}/status"},this.endpointsMethods={latest:"get",details:"get",summary:"get",status:"get",updateItem:"put",deleteItem:"delete",deleteImage:"delete"},this.webEndpoints=["latest"],this.hooksSelectores={addItem:"cart::add.item",quickAdd:"cart::quick.add",deleteItem:"cart::delete.item",updateItem:"cart::update.item",submit:"cart::submit",deleteImage:"cart::delete.file",reset:"cart::reset"},this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}latest(){return this.request("latest",{params:{source:""}}).then(e=>(salla.storage.set("cart",e.data),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e})}async details(){var e=await this.getCurrentCartId();return this.request(["details",e]).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async summary(){var e=await this.getCurrentCartId();return this.request(["summary",e]).then(function(e){return salla.cart.event.summaryFetched(e),e}).catch(function(e){throw salla.cart.event.summaryNotFetched(e),e})}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemAddedFailed('There is no "id"!'),!1;var e=this.getPossibleValue(t.formData,["quantity","donating_amount"])?"addItem":"quickAdd",s=await this.getCurrentCartId();return this.request([e,s,t.id],t.formData).then(function(e){return salla.cart.event.itemAdded(e,t.id),e}).catch(function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e})}async deleteItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemDeletedFailed('There is no "id"!'),!1;e=await this.getCurrentCartId();return this.request(["deleteItem",e,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemUpdatedFailed('There is no "id"!'),!1;e=await this.getCurrentCartId();return this.request(["updateItem",e,t.id],t.formData).then(function(e){return salla.cart.event.itemUpdated(e,t.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e})}async deleteImage(t){if(!(t=this.getPossibleValue(t,["id","image_id","photo_id"])))return salla.cart.event.imageNotDeleted('There is no "id"!'),!1;var e=await this.getCurrentCartId();return this.request(["deleteImage",e,t]).then(function(e){return salla.cart.event.imageDeleted(e,t),e}).catch(function(e){throw salla.cart.event.imageNotDeleted(e,t),e})}async status(e){return this.request(["status",e||await this.getCurrentCartId()])}async submit({}){var e=await this.getCurrentCartId();this.status(e).then(e=>{if("checkout"===e.data.next_step.to)return window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":"");if("refresh"===e.data.next_step.to)return window.location.reload();if("login"===e.data.next_step.to)return salla.event.dispatch("login::show");throw"Can't find next_step );"}).catch(function(e){throw salla.cart.event.submitFailed(e),e})}getCartRequestData(e){let t=e?.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}handleAfterResponseActions(e){var t;if(403===e.status)throw salla.storage.remove("cart"),t=salla.lang.get("pages.checkout.try_again"),salla.error(t),t;super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}}class GiftApi extends BaseApi{constructor(e){super(e),this.namespace="gift",this.endpoints={buy:"{id}/buy-as-gift"},this.webEndpoints=["buy"],this.hooksSelectores={buy:"gift::buy"},this.after_init()}buy(e){let t=this.getGiftRequestData(e);return t.id?this.request(["buy",t.id],t.formData).then(function(e){return salla.gift.event.buyingSucceeded(e,t.id),e}).catch(function(e){throw salla.gift.event.buyingFailed(e,t.id),e}):(salla.gift.event.buyingFailed('There is no "id"!'),!1)}getGiftRequestData(e){let t=e.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}}class LoyalityApi extends BaseApi{constructor(e){super(e),this.namespace="loyalty",this.endpoints={exchange:"cart/prize/exchange_loyalty_point"},this.webEndpoints=["exchange"],this.hooksSelectores={exchange:"loyalty::exchange"},this.after_init()}exchange(e){let t=e.data||{id:e};return t.id?(t.loyalty_prize_id=t.id,this.request("exchange",t).then(function(e){return salla.loyalty.event.exchangeSucceeded(e,t.id),e}).catch(function(e){throw salla.loyalty.event.exchangeFailed(e,t.id),e})):(salla.loyalty.event.exchangeFailed('There is no "id"!'),!1)}}class AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["login","resend","verify","register","logout","profile/verify-mobile","auth/mobile/verify","auth/email/verify","refresh"],this.endpointsMethods={logout:"get"},this.hooksSelectores={login:"auth::login",resend:"auth::resend",verify:"auth::verify",register:"auth::register",logout:"auth::logout"},this.after_init()}login(t,e){let s;return t.data&&(s=t.element,e=t.data,t=this.getPossibleValue(e,["type"])),e||"object"!=typeof t||(e=t),(t=this.getPossibleValue(t,["type"]))?this.request(["login",t],e).then(function(e){return salla.auth.event.codeSent.call(s,e,t),e}).catch(function(e){throw salla.auth.event.codeNotSent.call(s,e,t),e}):(e="Failed to know what's login type!",salla.auth.event.codeNotSent(e),this.errorPromise(e))}verify(t,e){return t.data&&(e=t.data,t=this.getPossibleValue(e,["type"])),t?(salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request(["verify",t],e).then(function(e){return salla.auth.event.verified(e,t),e}).catch(function(e){throw salla.auth.event.verificationFailed(e,t),e})):(e="Failed to know what's login type!",salla.auth.event.verificationFailed(e),this.errorPromise(e))}resend(t){return(t=t.data||t).phone?t.country_code?(t.resend_by=t.resend_by||"sms",this.request("resend",t).then(function(e){return salla.auth.event.codeReSent(e,t),e}).catch(function(e){throw salla.auth.event.codeNotReSent(e,t),e})):(salla.auth.event.codeNotReSent("Failed to know what's country_code!",t),!1):(salla.auth.event.codeNotReSent("Failed to know what's phone!",t),!1)}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(function(e){return salla.auth.event.registered.call(t,e),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(t,e),e})}logout(){return this.request("logout").then(function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout(()=>location.reload(),100),e}).catch(function(e){throw salla.auth.event.failedLogout(e),e})}refresh(){return this.request("refresh").catch(function(e){throw salla.auth.event.refreshFailed(e),e})}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",reOrder:"reorder/{id}"},this.endpointsMethods={reOrder:"get"},this.hooksSelectores={cancel:"order::cancel",reOrder:"order::re.order",show:"order::show"},this.after_init()}show(e,t=null){salla.event.dispatch("mobile::order.placed",{order_id:e||salla.config.get("page.id")}),location.href=t||location.href.replace("thankyou","order")}cancel(t){return this.request(["cancel",t],{params:{has_apple_pay:!!window.ApplePaySession}}).then(function(e){return salla.event.order.canceled(e,t),e}).catch(function(e){throw salla.event.order.notCanceled(e,t),e})}reOrder(t){return this.request(["reOrder",t]).then(function(e){return salla.storage.set("cart_id",e.data.cart_id),salla.event.order.reOrdered(e,t),window.location.href=e.data.url,e}).catch(function(e){throw salla.event.order.reOrderFailed(e,t),e})}}class OfferApi extends BaseApi{constructor(e){super(e),this.namespace="offer",this.endpoints={popup:"products/special-offer-popup/{product_id}",increase:"products/special-offer-popup/{product_id}/increase",details:"products/{product_id}/specialoffer"},this.webEndpoints=["popup","increase"],this.endpointsMethods={increase:"get"},this.endpointsHeaders={popup:{"s-ajax-view":!0}},this.hooksSelectores={popup:"offer::popup",increase:"offer::increase",details:"offer::details"},this.after_init()}details(e){let t=e.data|e;return(e=this.getPossibleValue(t,["product_id"]))?this.request(["details",e],t).then(function(e){return salla.offer.event.detailsFetched(e,t),e}).catch(function(e){throw salla.offer.event.fetchDetailsFailed(e,t),e}):(salla.offer.event.fetchDetailsFailed('There is no "prodId"!'),!1)}increase(e){let t;return e.data&&(t=e.data,e=this.getPossibleValue(t,["id","product_id"])),e?this.request(["increase",e],t).then(function(e){return salla.offer.event.increased(e,t),e}).catch(function(e){throw salla.offer.event.increaseFailed(e,t),e}):(salla.offer.event.increaseFailed('There is no "prodId"!'),!1)}}class SearchApi extends BaseApi{constructor(e){super(e),this.namespace="search",this.endpoints={search:"products/search"},this.endpointsMethods={search:"get"},this.hooksSelectores={search:"search::products"},this.after_init()}search(t){let e=t.data||{params:{query:t}};var s;return(t=e instanceof FormData?e.get("query"):e.query||e.params.query)?t===this.previousQuery?(s="Query Same As Previous!",salla.search.event.failed(s),this.errorPromise(s)):(this.previousQuery=t,this.request("search",e).then(function(e){return salla.search.event.finished(e,t),e}).catch(function(e){throw salla.search.event.failed(e,t),e})):(s='There is no "query"!',salla.search.event.failed(s),this.errorPromise(s))}}class CouponApi extends BaseApi{constructor(e){super(e),this.namespace="coupon",this.endpoints={add:"cart/{id}/coupon",remove:"cart/{id}/coupon"},this.endpointsMethods={remove:"put"},this.hooksSelectores={add:"coupon::add",remove:"coupon::remove"},this.after_init()}async add(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.coupon.addedFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["add",t],{coupon:e}).then(function(e){return salla.event.coupon.added(e,t),e}).catch(function(e){throw salla.event.coupon.addedFailed(e,t),e})}async remove(){let t=await salla.cart.api.getCurrentCartId();return this.request(["remove",t],{}).then(function(e){return salla.event.coupon.removed(e,t),e}).catch(function(e){throw salla.event.coupon.removedFailed(e,t),e})}}class ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.endpoints={getPrice:"product-price/{id}",availabilitySubscribe:"products/{id}/availability-notify",purchaseNow:"checkout/quick-purchase/{id}"},this.webEndpoints=["getPrice","purchaseNow"],this.hooksSelectores={getPrice:"product::get.price",availabilitySubscribe:"product::availability.subscribe",purchaseNow:"product::purchase.now"},this.after_init()}getPrice(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["getPrice",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.priceUpdated(e,t),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,t),e})}availabilitySubscribe(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["availabilitySubscribe",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.availabilitySubscribed(e,t),e}).catch(function(e){throw salla.product.event.availabilitySubscribedFailed(e,t),e})}purchaseNow(e){if(salla.auth.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,s=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",s],"object"==typeof t?t:void 0).then(function(e){return e}).catch(function(e){throw e});salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",s],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={send:"{type}/{id}/comments"},this.hooksSelectores={send:"comment::send"},this.after_init()}send(e){let t;e?.data&&(t=e.element,e=e.data);let s,{id:r,type:i,comment:n}=Object.fromEntries(e);return r?i&&["products","pages","product","page"].includes(i)?n?(i+=["product","page"].includes(i)?"s":"",this.request(["send",i,r],{comment:n}).then(function(e){return salla.event.comment.added.call(t,e,r),e}).catch(function(e){throw salla.event.comment.additionFailed.call(t,e,r),e})):(salla.event.comment.additionFailed(s="can't find comment content!"),this.errorPromise(s)):(salla.event.comment.additionFailed(s="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(s)):(salla.event.comment.additionFailed(s="Failed to get id!"),this.errorPromise(s))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.hooksSelectores={change:"currency::change"},this.after_init()}change(t){var e;return(t=this.getPossibleValue(t.data||t,["currency","code"]))?this.request("change",{params:{change_currency:"",currency:t}}).then(function(e){return salla.currency.event.changed(e,t),e}).catch(function(e){throw salla.currency.event.failed(e,t),e}):(e="Can't find currency code!",salla.currency.event.failed(e),this.errorPromise(e))}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class FeedbackApi extends BaseApi{constructor(e){super(e),this.namespace="feedback",this.endpoints={store:"rating/store",product:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.hooksSelectores={store:"feedback::store",product:"feedback::product",shipping:"feedback::shipping",order:"feedback::order"},this.endpointsMethods={order:"get"},this.after_init()}order(t){var e="object"==typeof t?t:{};return(t=this.getPossibleValue(t,["order_id","id"]))?this.request(["order",t],e).then(function(e){return salla.event.feedback.orderFetched(e,t),e}).catch(function(e){throw salla.event.feedback.orderNotFetched(e,t),e}):(e='There is no "order_id"!',salla.event.feedback.orderNotFetched(e),this.errorPromise(e))}store(t){var e;return(t=t.data||t)?this.request("store",t).then(function(e){return salla.event.feedback.storeRated(e,t),e}).catch(function(e){throw salla.event.feedback.storeFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.storeFailed(e),this.errorPromise(e))}products(){return this.product(...arguments)}product(t){var e;return(t=t.data||t)?this.request("product",t).then(function(e){return salla.event.feedback.productRated(e,t),e}).catch(function(e){throw salla.event.feedback.productFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.productFailed(e),this.errorPromise(e))}shipping(t){var e;return(t=t.data||t)?this.request("shipping",t).then(function(e){return salla.event.feedback.shippingRated(e,t),e}).catch(function(e){throw salla.event.feedback.shippingFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.shippingFailed(e),this.errorPromise(e))}}class SallaInit{constructor(e){salla.config.merge(e),this.connectHooksWithElements(),this.initiated=!0,e&&(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),salla.lang.loadStoreTranslations()),salla.twilight.event.initiated(e)}injectMaintenanceAlert(){var e;salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.log("store-notify Existed before!"):((e=document.createElement("div")).classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.log("s-theme_preview_bar Existed before!"):salla.lang.onLoaded(()=>{let e=document.createElement("div");e.classList.add("s-theme-preview-bar","bg-red-400","text-white","py-2.5"),e.id="s-theme_preview_bar",e.innerHTML=`<div class="container flex justify-between items-center">
|
|
2
|
-
<
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
<a href="${
|
|
7
|
-
|
|
8
|
-
${salla.
|
|
9
|
-
</div>`,document.body.prepend(e)}))}connectHooksWithElements(e){let s=["click","change","submit","keyup"],r=salla.api.hooksPrefix,i=this;for(let e=0;e<4;e++)document.addEventListener(s[e],function(o){var t=s[e];if(salla.event.document[t](o),o.target.matches(".ajax")&&("click"==t&&o.target instanceof HTMLAnchorElement||"submit"==t&&o.target instanceof HTMLFormElement))i.handleElementAjaxRequest(o,o.target);else{let a=!0;for(let n=o["target"];n&&n!==this&&a;n=n.parentNode){let e=r+t,i=n.getAttribute(e);if(i){if(n.hasAttribute("data-auth-required")&&salla.auth.isGuest())return salla.auth.event.login({type:"none",next_event:i});let e=i.split("::")[0],r=salla.api.apis[e];if(r){let s=!1;Object.keys(r.hooksSelectores).forEach(t=>{if(r.hooksSelectores[t]===i){let e;s=!0,n.hasAttribute("data-allow-default")||o.preventDefault();try{e=r.withInjectData(n,i)}catch(e){return a=!1,void salla.log(`Error to execute "${i}"!`,e.message||e)}r[t].call(r,e)||o.stopPropagation(),a=!1}}),s||salla.event.dispatch(i,n)}else salla.event.dispatch(i,n)}}}})}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.log("trying to call ajax from non Element!!"),!1;e.preventDefault();let s=t.getAjaxFormData(e),r=s.method?s.method.toLowerCase():void 0;salla.api.document.request(s.url,s.formData,r).then(e=>(e.data&&e.request&&(e=e.data),salla.api.document.handleAfterResponseActions(e),this.callAjaxEvent(s.events.success,e,s.formData),e)).catch(e=>{throw salla.api.document.handleErrorResponse(e),this.callAjaxEvent(s.events.fail,e,s.formData),e})}callAjaxEvent(e,t,s){var r;e&&(s instanceof FormData&&(r={},Array.from(s.entries()).forEach(function(e){r[e[0]]=e[1]}),s=r),window[e]?window[e](t,s):salla.event.dispatch(e,t,s))}}class TwilightApi extends BaseApi{constructor(e){super(e),this.namespace="twilight",this.hooksSelectores={init:"twilight::init",api:"twilight::api"},this.after_init()}init(e){var t=e?.events;this.initiated||(delete e.events,new SallaInit(e)),t&&salla.event.dispatchEvents(t)}api(e){e=e?.events;e&&salla.event.dispatchEvents(e)}}class WishlistApi extends BaseApi{constructor(e){super(e),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.hooksSelectores={add:"wishlist::add",remove:"wishlist::remove"},this.after_init()}updateWishlistStorage(e,t=!0){let s=salla.storage.get("salla::wishlist",[]);t?s.push(e):s.splice(s.indexOf(e),1),salla.storage.set("salla::wishlist",s)}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(t){let e,s;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(e=salla.lang.get("common.messages.must_login")),salla.error(e),this.errorPromise(e)):(t.data&&(s=t.element,t=this.getPossibleValue(t.data,["id","prod_id"])),t?this.request(["add",t]).then(e=>(this.updateWishlistStorage(t),salla.wishlist.event.added.call(s,e,t),e)).catch(function(e){throw salla.wishlist.event.additionFailed.call(s,e,t),e}):(salla.wishlist.event.additionFailed(e="Failed to get product id!"),this.errorPromise(e)))}remove(t){let s;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(error=salla.lang.get("common.messages.must_login")),salla.error(error),this.errorPromise(error)):(t?.data&&(s=t.element,t=this.getPossibleValue(t.data,["id","prod_id"])),t?this.request(["remove",t]).then(e=>(this.updateWishlistStorage(t,!1),salla.wishlist.event.removed.call(s,e,t),e)).catch(function(e){throw salla.wishlist.event.removingFailed.call(s,e,t),e}):(salla.wishlist.event.removingFailed("Failed to get id!"),!1))}}class ScopeApi extends BaseApi{constructor(e){super(e),this.namespace="scope",this.endpoints={getAll:"/scopes",submit:"/scope"},this.webEndpoints=["getAll","submit"],this.endpointsMethods={getAll:"get"},this.after_init()}getAll(){return this.request("getAll",{from:"header"}).then(function(e){return console.log(e),e}).catch(function(e){throw e})}submit(e){return this.request("submit",e).then(function(e){return console.log(e),e}).catch(function(e){throw e})}}function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var s=String(t).replace(/=+$/,"");if(s.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,n=0,a=0,o="";i=s.charAt(a++);~i&&(r=n%4?64*r+i:i,n++%4)&&(o+=String.fromCharCode(255&r>>(-2*n&6))))i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return decodeURIComponent(r(t).replace(/(.)/g,function(e,t){t=t.charCodeAt(0).toString(16).toUpperCase();return"%"+(t=t.length<2?"0"+t:t)}))}catch(e){return r(t)}}function n(e){this.message=e}function o(e,s){if("string"!=typeof e)throw new n("Invalid token specified");s=!0===(s=s||{}).header?0:1;try{return JSON.parse(t(e.split(".")[s]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const axios=require("axios");class sallaRequest{constructor(e){return e.on("twilight::initiated",()=>this.initiateRequest()),e.on("auth::token.fetched",e=>this.handleToken(e)),axios.create({baseURL:window.baseUrl,headers:{common:{"X-Requested-With":"XMLHttpRequest"},"S-SOURCE":"twilight"}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.url",window.baseUrl),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.api.defaults.headers.common["accept-language"]=salla.config.get("user.language_code","ar"),this.injectTokenToTheRequests()}injectTokenToTheRequests(){var e=salla.storage.get("token"),t=salla.config.isGuest(),s=salla.storage.get("cart");if(s&&s.user_id!==salla.config.get("user.id"))return salla.log("Wrong cart!"),void salla.cart.api.reset();if(!t||e){if(t&&e)return salla.log("Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();s=o(e);return Date.now()/1e3>s.exp?(salla.log("An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):s.sub!==salla.config.get("user.id")?(salla.log("Wrong token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}}class SallaApi extends sallaRequest{constructor(e){super(e),this.apis={auth:new AuthApi(this),cart:new CartApi(this),gift:new GiftApi(this),loyalty:new LoyalityApi(this),order:new OrderApi(this),offer:new OfferApi(this),search:new SearchApi(this),coupon:new CouponApi(this),product:new ProductApi(this),comment:new CommentApi(this),currency:new CurrencyApi(this),document:new DocumentApi(this),feedback:new FeedbackApi(this),twilight:new TwilightApi(this),wishlist:new WishlistApi(this),scope:new ScopeApi(this)},this.hooksPrefix="data-on-",this.hooksSelectores=[],Object.assign(this,this.apis)}}class BaseAlias{constructor(s,r){return this.api=s,this.event=r,new Proxy(this,{get:function(e,t){return"event"==t?r:"api"==t?s:s&&s[t]||e[t]}})}}class Cart extends BaseAlias{}class Auth extends BaseAlias{isUser(){try{return!1===window.dataLayer[0].customer.isGuest}catch(e){return salla.log("Error::isUser",e),!1}}isGuest(){return!this.isGuest()}}class Order extends BaseAlias{}class Gift extends BaseAlias{}class Loyalty extends BaseAlias{}class Offer extends BaseAlias{}class Search extends BaseAlias{}class Coupon extends BaseAlias{}class Comment extends BaseAlias{}class Product extends BaseAlias{}class Currency extends BaseAlias{}class Document extends BaseAlias{}class Feedback extends BaseAlias{}class Twilight extends BaseAlias{}class Wishlist extends BaseAlias{}class Scope extends BaseAlias{}var js={exports:{}},core={exports:{}},evEmitter={exports:{}},utils=(!function(e){var t,s;t="undefined"!=typeof window?window:commonjsGlobal,s=function(){function e(){}let t=e.prototype;return t.on=function(e,t){if(!e||!t)return this;let s=this._events=this._events||{},r=s[e]=s[e]||[];return r.includes(t)||r.push(t),this},t.once=function(e,t){if(!e||!t)return this;this.on(e,t);let s=this._onceEvents=this._onceEvents||{};return(s[e]=s[e]||{})[t]=!0,this},t.off=function(e,t){let s=this._events&&this._events[e];if(!s||!s.length)return this;e=s.indexOf(t);return-1!=e&&s.splice(e,1),this},t.emitEvent=function(e,t){let s=this._events&&this._events[e];if(!s||!s.length)return this;s=s.slice(0),t=t||[];let r=this._onceEvents&&this._onceEvents[e];for(var i of s)r&&r[i]&&(this.off(e,i),delete r[i]),i.apply(this,t);return this},t.allOff=function(){return delete this._events,delete this._onceEvents,this},e},e.exports?e.exports=s():t.EvEmitter=s()}(evEmitter),{exports:{}}),pageLoad=(!function(e){var t,s;t=commonjsGlobal,s=function(t){let r={extend:function(e,t){return Object.assign(e,t)},modulo:function(e,t){return(e%t+t)%t},makeArray:function(e){return Array.isArray(e)?e:null==e?[]:"object"==typeof e&&"number"==typeof e.length?[...e]:[e]},removeFrom:function(e,t){t=e.indexOf(t);-1!=t&&e.splice(t,1)},getParent:function(e,t){for(;e.parentNode&&e!=document.body;)if((e=e.parentNode).matches(t))return e},getQueryElement:function(e){return"string"==typeof e?document.querySelector(e):e},handleEvent:function(e){var t="on"+e.type;this[t]&&this[t](e)},filterFindElements:function(e,s){return(e=r.makeArray(e)).filter(e=>e instanceof HTMLElement).reduce((e,t)=>{if(!s)return e.push(t),e;t.matches(s)&&e.push(t);t=t.querySelectorAll(s);return e.concat(...t)},[])},debounceMethod:function(e,t,s){s=s||100;let r=e.prototype[t],i=t+"Timeout";e.prototype[t]=function(){clearTimeout(this[i]);let e=arguments;this[i]=setTimeout(()=>{r.apply(this,e),delete this[i]},s)}},docReady:function(e){var t=document.readyState;"complete"==t||"interactive"==t?setTimeout(e):document.addEventListener("DOMContentLoaded",e)},toDashed:function(e){return e.replace(/(.)([A-Z])/g,function(e,t,s){return t+"-"+s}).toLowerCase()}},l=t.console;return r.htmlInit=function(a,o){r.docReady(function(){let i="data-"+r.toDashed(o),e=document.querySelectorAll(`[${i}]`),n=t.jQuery;[...e].forEach(e=>{let t,s=e.getAttribute(i);try{t=s&&JSON.parse(s)}catch(t){return void(l&&l.error(`Error parsing ${i} on ${e.className}: `+t))}var r=new a(e,t);n&&n.data(e,o,r)})})},r},e.exports?e.exports=s(t):t.fizzyUIUtils=s(t)}(utils),function(e){var t,s;t=window,s=function(t,e,r){let i=t.jQuery,n={};function a(t,s){var e=r.getQueryElement(t);if(e){if((t=e).infiniteScrollGUID){let e=n[t.infiniteScrollGUID];return e.option(s),e}this.element=t,this.options={...a.defaults},this.option(s),i&&(this.$element=i(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(e||t))}a.defaults={},a.create={},a.destroy={};let s=a.prototype,o=(Object.assign(s,e.prototype),0),l=(s.create=function(){var e=this.guid=++o;if(this.element.infiniteScrollGUID=e,(n[e]=this).pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath())for(var t in this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit(),a.create)a.create[t].call(this);else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(s,r,e){this.log(s,e);var t=r?[r].concat(e):e;if(this.emitEvent(s,t),i&&this.$element){let t=s+=".infiniteScroll";if(r){let e=i.Event(r);e.type=s,t=e}this.$element.trigger(t,e)}},{initialized:e=>"on "+e,request:e=>"URL: "+e,load:(e,t)=>`${e.title||""}. URL: `+t,error:(e,t)=>e+". URL: "+t,append:(e,t,s)=>s.length+" items. URL: "+t,last:(e,t)=>"URL: "+t,history:(e,t)=>"URL: "+t,pageIndex:function(e,t){return`current page determined to be: ${e} from `+t}}),c=(s.log=function(s,r){if(this.options.debug){let e="[InfiniteScroll] "+s,t=l[s];t&&(e+=". "+t.apply(this,r)),console.log(e)}},s.updateMeasurements=function(){this.windowHeight=t.innerHeight;var e=this.element.getBoundingClientRect();this.top=e.top+t.scrollY},s.updateScroller=function(){var e=this.options.elementScroll;if(e){if(this.scroller=!0===e?this.element:r.getQueryElement(e),!this.scroller)throw new Error("Unable to find elementScroll: "+e)}else this.scroller=t},s.updateGetPath=function(){let e=this.options.path;var t;e?"function"!=(t=typeof e)?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e:console.error("InfiniteScroll path option required. Set as: "+e)},s.updateGetPathTemplate=function(t){this.getPath=()=>{var e=this.pageIndex+1;return t.replace("{{#}}",e)};var e=t.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),e=new RegExp(e),e=location.href.match(e);e&&(this.pageIndex=parseInt(e[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))},[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/]),u=a.getPathParts=function(e){if(e)for(var t of c){var s,r,t=e.match(t);if(t)return[,t,s,r]=t,{begin:t,index:s,end:r}}},h=(s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(t){var s=t.getAttribute("href"),r=u(s);if(r){let{begin:e,index:t,end:s}=r;this.isPathSelector=!0,this.getPath=()=>e+(this.pageIndex+1)+s,this.pageIndex=parseInt(t,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])}else console.error("InfiniteScroll unable to parse next link href: "+s)}else console.error("Bad InfiniteScroll path option. Next link not found: "+e)},s.updateGetAbsolutePath=function(){let i=this.getPath();if(i.match(/^http/)||i.match(/^\//))this.getAbsolutePath=this.getPath;else{let e=location["pathname"],t=i.match(/^\?/),s=e.substring(0,e.lastIndexOf("/")),r=t?e:s+"/";this.getAbsolutePath=()=>r+this.getPath()}},a.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},a.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){for(var e in this.allOff(),a.destroy)a.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],i&&this.$element&&i.removeData(this.element,"infiniteScroll")},a.throttle=function(r,i){let n,a;return i=i||200,function(){let e=+new Date,t=arguments,s=()=>{n=e,r.apply(this,t)};n&&e<n+i?(clearTimeout(a),a=setTimeout(s,i)):s()}},a.data=function(e){e=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return e&&n[e]},a.setJQuery=function(e){i=e},r.htmlInit(a,"infinite-scroll"),s._init=function(){},t)["jQueryBridget"];return i&&h&&h("infiniteScroll",a,i),a},e.exports?e.exports=s(t,evEmitter.exports,utils.exports):t.InfiniteScroll=s(t,t.EvEmitter,t.fizzyUIUtils)}(core),{exports:{}}),scrollWatch=(!function(e){var t,s;t=window,s=function(t,i){let e=i.prototype,n=(Object.assign(i.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),i.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},e.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()},new DOMParser);function u(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return e.loadNextPage=function(){if(!this.isLoading&&this.canLoad){let{responseBody:s,domParseResponse:r,fetchOptions:e}=this.options,i=this.getAbsolutePath();this.isLoading=!0,"function"==typeof e&&(e=e());var t=fetch(i,e).then(t=>{var e;return t.ok?t[s]().then(e=>("text"==s&&r&&(e=n.parseFromString(e,"text/html")),204==t.status?(this.lastPageReached(e,i),{body:e,response:t}):this.onPageLoad(e,i,t))):(e=new Error(t.statusText),this.onPageError(e,i,t),{response:t})}).catch(e=>{this.onPageError(e,i)});return this.dispatchEvent("request",null,[i,t]),t}},e.onPageLoad=function(e,t,s){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,s]),this.appendNextPage(e,t,s)},e.appendNextPage=function(e,t,s){var{append:r,responseBody:i,domParseResponse:n}=this.options;if("text"!=i||!n||!r)return{body:e,response:s};let a=e.querySelectorAll(r),o={body:e,response:s,items:a};if(!a||!a.length)return this.lastPageReached(e,t),o;let l=u(a),c=()=>(this.appendItems(a,l),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,a,s]),o);return this.options.outlayer?this.appendOutlayerItems(l,c):c()},e.appendItems=function(e,t){if(e&&e.length){var s;for(s of(t=t||u(e)).querySelectorAll("script")){let e=document.createElement("script"),t=s.attributes;for(var r of t)e.setAttribute(r.name,r.value);e.innerHTML=s.innerHTML,s.parentNode.replaceChild(e,s)}this.element.appendChild(t)}},e.appendOutlayerItems=function(e,s){let r=i.imagesLoaded||t.imagesLoaded;return r?new Promise(function(t){r(e,function(){var e=s();t(e)})}):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},e.onAppendOutlayer=function(e,t,s){this.options.outlayer.appended(s)},e.checkLastPage=function(e,t){let s,{checkLastPage:r,path:i}=this.options;r&&("function"!=typeof i||this.getPath()?("string"==typeof r?s=r:this.isPathSelector&&(s=i),s&&e.querySelector&&(e.querySelector(s)||this.lastPageReached(e,t))):this.lastPageReached(e,t))},e.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},e.onPageError=function(e,t,s){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,s]),e},i.create.prefill=function(){var e;this.options.prefill&&((e=this.options.append)?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error("append option required for prefill. Set as :"+e))},e.prefill=function(){var e=this.getPrefillDistance();this.isPrefilling=0<=e,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},e.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},e.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},i},e.exports?e.exports=s(t,core.exports):s(t,t.InfiniteScroll)}(pageLoad),{exports:{}}),history$1=(!function(e){var t,s;t=window,s=function(s,e,t){let r=e.prototype;return Object.assign(e.defaults,{scrollThreshold:400}),e.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);var e=this.options.scrollThreshold;!e&&0!==e||this.enableScrollWatch()},e.destroy.scrollWatch=function(){this.disableScrollWatch()},r.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},r.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},r.bindScrollWatchEvents=function(e){e=e?"addEventListener":"removeEventListener";this.scroller[e]("scroll",this.pageScrollHandler),s[e]("resize",this.resizeHandler)},r.onPageScroll=e.throttle(function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")}),r.getBottomDistance=function(){let e,t;return t=this.options.elementScroll?(e=this.scroller.scrollHeight,this.scroller.scrollTop+this.scroller.clientHeight):(e=this.top+this.element.clientHeight,s.scrollY+this.windowHeight),e-t},r.onResize=function(){this.updateMeasurements()},t.debounceMethod(e,"onResize",150),e},e.exports?e.exports=s(t,core.exports,utils.exports):s(t,t.InfiniteScroll,t.fizzyUIUtils)}(scrollWatch),{exports:{}}),button=(!function(e){var t,s;t=window,s=function(r,e,t){let s=e.prototype,i=(Object.assign(e.defaults,{history:"replace"}),document.createElement("a"));return e.create.history=function(){this.options.history&&(i.href=this.getAbsolutePath(),(i.origin||i.protocol+"//"+i.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${i.origin} on ${location.origin} . History behavior disabled.`))},s.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},s.bindHistoryAppendEvents=function(e){e=e?"addEventListener":"removeEventListener";this.scroller[e]("scroll",this.scrollHistoryHandler),r[e]("unload",this.unloadHandler)},s.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},e.destroy.history=s.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},s.onAppendHistory=function(e,t,s){s&&s.length&&(s=s[0],s=this.getElementScrollY(s),i.href=t,this.scrollPages.push({top:s,path:i.href,title:e.title}))},s.getElementScrollY=function(e){return this.options.elementScroll?e.offsetTop-this.top:e.getBoundingClientRect().top+r.scrollY},s.onScrollHistory=function(){var e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},t.debounceMethod(e,"onScrollHistory",150),s.getClosestScrollPage=function(){let e,t;e=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:r.scrollY+this.windowHeight/2;for(var s of this.scrollPages){if(s.top>=e)break;t=s}return t},s.setHistory=function(e,t){var s=this.options.history;s&&history[s+"State"]&&(history[s+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},s.onUnload=function(){var e;0!==this.scrollPage.top&&(e=r.scrollY-this.scrollPage.top+this.top,this.destroyHistory(),scrollTo(0,e))},s.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},e},e.exports?e.exports=s(t,core.exports,utils.exports):s(t,t.InfiniteScroll,t.fizzyUIUtils)}(history$1),{exports:{}}),status=(!function(e){var t,s;t=window,s=function(e,t,s){class r{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){var e=s.getQueryElement(this.options.button);e&&(this.button=new r(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=r,t},e.exports?e.exports=s(0,core.exports,utils.exports):s(0,t.InfiniteScroll,t.fizzyUIUtils)}(button),{exports:{}}),TheInfinitScroll=(!function(e){var t,s;t=window,s=function(e,t,s){let r=t.prototype;function i(e){a(e,"none")}function n(e){a(e,"block")}function a(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=s.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},r.bindHideStatus=function(e){var t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},r.showRequestStatus=function(){this.showStatus("request")},r.showErrorStatus=function(){this.showStatus("error")},r.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},r.showStatus=function(e){n(this.statusElement),this.hideStatusEventElements(),n(this.statusEventElements[e])},r.hideAllStatus=function(){i(this.statusElement),this.hideStatusEventElements()},r.hideStatusEventElements=function(){for(var e in this.statusEventElements)i(this.statusEventElements[e])},t},e.exports?e.exports=s(0,core.exports,utils.exports):s(0,t.InfiniteScroll,t.fizzyUIUtils)}(status),function(e){window,e.exports&&(e.exports=(e=core.exports,pageLoad.exports,scrollWatch.exports,history$1.exports,button.exports,status.exports,e))}(js),js.exports);class InfiniteScroll extends BaseAlias{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},this.instances=[]}initiate(e,t,s){s=this.getCustomOptions(t,s);t="string"!=typeof e?e:document.querySelector(e),e=s.path;if(t&&e&&("string"!=typeof e||document.querySelector(e))){let e=new TheInfinitScroll(t,s);return e.on("scrollThreshold",salla.infiniteScroll.event.scrollThreshold),e.on("request",salla.infiniteScroll.event.request),e.on("load",salla.infiniteScroll.event.load),e.on("append",salla.infiniteScroll.event.append),e.on("error",salla.infiniteScroll.event.error),e.on("last",salla.infiniteScroll.event.last),e.on("history",salla.infiniteScroll.event.history),this.instances.push(e),e}salla.log(t?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!")}getCustomOptions(e,t){return(t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}function injectValueToFromData(e,t,s){return e instanceof FormData?e.append(t,s):e[t]=s,e}function number(t,e=!1){t+="";var s,r=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],n=(e=e||!salla.config.get("store.settings.arabic_numbers_enabled"))?r:i,a=e?i:r;for(let e=0;e<n.length;e++)s=new RegExp(n[e],"g"),t=t.replace(s,a[e]);return t}function digitsOnly(e){return number(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")}function inputDigitsOnly(t,s=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach(e=>inputDigitsOnly(e,s));if(t){let e=salla.helpers.digitsOnly(t.value);return t.min&&e<t.min?t.value=t.min:t.max&&e>t.max?t.value=t.max:1<=t.maxLength&&e.toString().length>t.maxLength?t.value=e.toString().substring(0,t.maxLength):t.value=s||t.dataset.hasOwnProperty("digitsWithDecimal")?getOnlyDecimal(e):e.replace(/\D/g,"")}salla.log("Can't find Object With Id: "+t)}function getOnlyDecimal(e){var t=(e.match(/\./g)||[]).length;return t&&1!==t?getOnlyDecimal(e.replace(/\.(.+)\./g,".$1")):e}function money(e){return number(e?.amount|e)+" "+salla.config.currency(e?.currency).symbol}function debounce(s,t){t=t||100;let r,i=[];return function(...e){return clearTimeout(r),r=setTimeout(()=>{let t=s(...e);i.forEach(e=>e(t)),i=[]},t),new Promise(e=>i.push(e))}}function getInputDataWithName(t,s,r={}){if(t.includes("[")){let e=t.split("]").join("").split("[");return{name:e[0],value:getLeveledData(e.slice(1),s,r[e[0]])}}return{name:t,value:s}}function getLeveledData(e,t,s){var r=e[0];return s&&0==e.length?Array.isArray(s)?(s.push(t),s):[s,t]:Array.isArray(s)?(s.push(t),s):"string"==typeof s?[s,t]:s?(s[r]=getLeveledData(e.slice(1),t,s[r]),s):r?{[r]:getLeveledData(e.slice(1),t)}:""===r?[t]:t}function setNested(e,t,s){let r=e,i=t.split("."),n=i.length;for(let e=0;e<n-1;e++){var a=i[e];r[a]||(r[a]={}),r=r[a]}return r[i[n-1]]=s,e}function getNested(e,t,s){var r;for(r of t.split("."))if(!(e=e.hasOwnProperty(r)?e[r]:s||void 0))return e;return e}function url(e){return salla.config.get("store.url","/")+e}function addParamToUrl(e,t){if(!t||!e)return window.location.href;let s=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),r=window.location.href.replace(s,"$1").replace(/&$|\?$/,"");return(r+=(r.includes("?")?"&":"?")+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")})},String.prototype.toDatasetName=function(){return(this.startsWith("data-")?this.substr(5):this).toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var s,r=this,i=0;i<e.length;i++)s=new RegExp(e[i],"g"),r=r.replace(s,t[i]);return r},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement}}),Element.prototype.getElementSallaData=function(r,...i){if(this.getAttribute){if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(r){}var n=this.getAttribute("data-function");if(n&&window[n])return"function"==typeof window[n]?this.getFilteredData(window[n].call(this,...i)):this.getFilteredData(window[n]);let e=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if((e="FORM"!==this.tagName&&(e||this.closest("form")||this.closest("[salla-form-data]"))||this)&&"FORM"===e.tagName)return this.getFilteredData(new FormData(e),null,e);let t=e.querySelectorAll("[name]");if(!t.length)return this.getFilteredData();let s=Object.assign({},this.dataset);return t.forEach(t=>{if(!["checkbox","radio"].includes(t.type)||t.checked)try{var e=salla.helpers.inputData(t.name,t.value,s);s[e.name]=e.value}catch(e){salla.log(t.name+" can't be send")}}),this.getFilteredData(s)}},Element.prototype.canEventFireHook=function(e){return!!this.hasAttribute&&this.hasAttribute(salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(t,s){t=t.toLowerCase();for(var r=0;r<this.attributes.length;r++){let e=this.attributes[r].name.toLowerCase();if(0===e.indexOf(t))return!s||e}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]'),s=(t.forEach(e=>{e.files.length||e.setAttribute("disabled","")}),new FormData(this));return t.forEach(e=>{e.files.length||e.removeAttribute("disabled")}),{formData:this.getFilteredData(s,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(s=null,r=null,i=null){return s=s||i?.dataset||this.dataset,i&&this.name&&void 0!==this.value&&(s=injectValueToFromData(s,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach(e=>{e=i?.dataset[e]||this.dataset[e];if(e){var t=window[e];if("function"==typeof t){if(!t(s,i||this,r)&&s)throw`Data failed to be pass verify function window.${e}(formData, element, event)!`;return t(s,i||this,r)}salla.log("window."+e+"() not found!")}}),s},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return{formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},window.onbeforeunload=function(e){if(salla.document.event.leaving(e),!salla.config.get("canLeave"))return e.preventDefault(),!1};var Helpers={digitsOnly:digitsOnly,inputDigitsOnly:inputDigitsOnly,number:number,money:money,setNested:setNested,getNested:getNested,inputData:getInputDataWithName,url:url,addParamToUrl:addParamToUrl,debounce:debounce};class AppHelpers{toggleClassIf(e,t,s,r){return document.querySelectorAll(e).forEach(e=>this.toggleElementClassIf(e,t,s,r)),this}toggleElementClassIf(e,t,s,r){t=Array.isArray(t)?t:t.split(" "),s=Array.isArray(s)?s:s.split(" ");r=r(e);return e?.classList.remove(...r?s:t),e?.classList.add(...r?t:s),this}isValidEmail(e){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return"object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach(e=>this.watchElement(e[0],e[1])),this}on(t,e,s,r={}){return"object"==typeof e?this.element(e).addEventListener(t,s,r):document.querySelectorAll(e).forEach(e=>e.addEventListener(t,s,r)),this}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,e=>13===e.keyCode&&t(e)),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e){return this.debounce_||(this.debounce_=salla.helpers.debounce((e,...t)=>e(...t),500)),this.debounce_(e,...Array.from(arguments).slice(1))}}class Form{submit(e,t=null){t=t||event;let s,r=!1;if("SubmitEvent"===t?.constructor?.name){if(salla.log("Event Object",event),t.preventDefault(),!t.target||"FORM"!==t.target.tagName)return console.error("Failed find the target element for submit action. make sure you submit a form element"),new Promise(()=>{throw"Failed find the target element for submit action. make sure you submit a form element"});(r=t?.submitter&&t.submitter?.parentElement&&"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName?!0:r)&&t?.submitter?.parentElement.load(),s=t.target.getElementSallaData(),salla.log("Data from element",s)}else s=t;if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.twilight.request(e,s,"post").finally(()=>{r&&t?.submitter?.parentElement.stop()});let i=e.split("."),n=i.splice(-1);return salla.call(i.join("."))[n](s).finally(()=>{r&&t?.submitter?.parentElement.stop()})}}class SallaCookie{constructor(e){e.on("cookies::remove",e=>this.remove(e)),e.on("cookies::add",(e,t)=>this.set(e,t))}get(t){return document.cookie.split("; ").find(e=>e.startsWith(t+"="))?.split("=")[1]}set(e,t="",s=10){let r="";if(s){let e=new Date;e.setTime(e.getTime()+24*s*60*60*1e3),r="; expires="+e.toUTCString()}return document.cookie=`${e}=${t}${r}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=e+"=; Max-Age=0; path=/;",this}}class SallaConfig{constructor(e){this.triedToGetCurrencies_=!1,this.languages_=[],this.triedToGetLanguages_=!1,this.currencies_=[],this.properties_=e||{debug:"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}}}merge(e){return Object.assign(this.properties_,e),this}set(e,t){return e.includes(".")?salla.helpers.setNested(this.properties_,e,t):this.properties_[e]=t,this}get(e,t=null){return e.includes(".")?salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]:t||void 0}isUser(){return"user"===this.get("user.type")}isGuest(){return!this.isUser()}async languages(e=!0){if(this.languages_.length||this.triedToGetLanguages_)return this.languages_;if(this.languages_=Object.values(this.get("languages",{})),!e||this.languages_.length)return this.languages_;this.triedToGetLanguages_=!0;let t=await salla.document.api.request("languages",null,"get"),s=salla.url("");return this.languages_=t&&t.data?t.data.map(e=>(e.code=e.code||e.iso_code,e.url=s+e.code,e.is_rtl=e.is_rtl||e.rtl,e)):[]}async currencies(){if(this.triedToGetCurrencies_)return this.currencies_;this.triedToGetCurrencies_=!0;let e=await salla.currency.api.list();return this.currencies_=e&&e.data?e.data.map(e=>(e.country_code=e.code.substr(0,2).toLowerCase(),e)):[]}currency(e){return this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}}var lang={exports:{}},Lang=(lang.exports=function(){function l(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}function e(e){this.locale=(e=e||{}).locale||function(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}()||t,this.fallback=e.fallback,this.messages=e.messages}var c=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,u=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,t="en";return e.prototype.setMessages=function(e){this.messages=e},e.prototype.getLocale=function(){return this.locale||this.fallback},e.prototype.setLocale=function(e){this.locale=e},e.prototype.getFallback=function(){return this.fallback},e.prototype.setFallback=function(e){this.fallback=e},e.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},e.prototype.get=function(e,t,s){if(!this.has(e,s))return e;s=this._getMessage(e,s);return null===s?e:s=t?this._applyReplacements(s,t):s},e.prototype.trans=function(e,t){return this.get(e,t)},e.prototype.choice=function(e,t,s,r){(s=void 0!==s?s:{}).count=t;s=this.get(e,s,r);if(null==s)return s;for(var i,n=s.split("|"),a=[],o=0;o<n.length;o++)n[o]=n[o].trim(),u.test(n[o])&&(i=n[o].split(/\s/),a.push(i.shift()),n[o]=i.join(" "));if(1===n.length)return s;for(var l=0;l<a.length;l++)if(this._testInterval(t,a[l]))return n[l];return r=r||this._getLocale(e),n[this._getPluralForm(t,r)]},e.prototype.transChoice=function(e,t,s){return this.choice(e,t,s)},e.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var e=e.split("."),s=e[0].replace(/\//g,".");return{source:t+"."+s,sourceFallback:this.getFallback()+"."+s,entries:e.slice(1)}},e.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var s=this.messages[e.source],r=e.entries.slice(),i=r.join(".");if("string"!=typeof(s=void 0!==s?this._getValueInKey(s,i):void 0)&&this.messages[e.sourceFallback])for(s=this.messages[e.sourceFallback],r=e.entries.slice(),i="";r.length&&void 0!==s;)s[i=i?i.concat(".",r.shift()):r.shift()]&&(s=s[i],i="");return"string"!=typeof s?null:s},e.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var s=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),r=0,i=s.length;r<i;++r){var n=s.slice(0,r+1).join("."),a=s.slice(r+1,s.length).join(".");if(e[n])return this._getValueInKey(e[n],a)}return e},e.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},e.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var s=e.join(".");if(t[s]){t=t[s];break}t=t[e.shift()]}return t},e.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},e.prototype._applyReplacements=function(e,r){return Object.keys(r).sort(this._sortReplacementKeys).forEach(function(s){e=e.replace(new RegExp(":"+s,"gi"),function(e){var t=r[s];return e===e.toUpperCase()?t.toUpperCase():e===e.replace(/\w/i,function(e){return e.toUpperCase()})?t.charAt(0).toUpperCase()+t.slice(1):t})}),e},e.prototype._testInterval=function(e,t){if("string"!=typeof t)throw"Invalid interval: should be a string.";var s,r,i,n=(t=t.trim()).match(c);if(!n)throw"Invalid interval: "+t;if(!n[2])return t=(n=n.filter(function(e){return!!e}))[1],(s=l(n[2]))===1/0&&(s=-1/0),r=l(n[3]),i=n[4],("["===t?s<=e:s<e)&&("]"===i?e<=r:e<r);for(var a=n[2].split(","),o=0;o<a.length;o++)if(parseInt(a[o],10)===e)return!0;return!1},e.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:2<=e%10&&e%10<=4&&(e%100<10||20<=e%100)?1:2;case"cs":case"sk":return 1==e?0:2<=e&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:2<=e%10&&(e%100<10||20<=e%100)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||1<e%100&&e%100<11?1:10<e%100&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:2<=e%10&&e%10<=4&&(e%100<12||14<e%100)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||0<e%100&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:3<=e%100&&e%100<=10?3:11<=e%100&&e%100<=99?4:5}},e}(),lang.exports);class SallaLang extends Lang{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||window.locale||"en",e.fallback=e.fallback||"en",super(e),this.translationsLoaded=!1}onLoaded(e){this.translationsLoaded?e():salla.event.on("languages::translations.loaded",e)}loadStoreTranslations(){var e=salla.config.get("store.url")?.rtrim("/");if(!e)return salla.lang.messages&&salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0,void salla.log("There is no `store.url` to auto loading translations from it!");let t=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),s=document.createElement("script");s.src=e+`/languages/assets/${t}.js`,s.onload=()=>{if(window.translations)return this.setMessages(window.translations),salla.event.dispatch("languages::translations.loaded"),void(this.translationsLoaded=!0);console.warn('You should load Salla Translations Before!\nUse: <script src="{{ link("languages/assets/{theme.translations_hash}.js") }}"><\/script>\nor: salla.lang.setMessages({....}), see https://github.com/rmariuzzo/Lang.js for more informations.')},document.head.appendChild(s)}get(e,t,s){return window.translations&&(e="trans."+e),super.get(e,t,s)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}}var assign=make_assign(),create$1=make_create(),trim$1=make_trim(),Global$5="undefined"!=typeof window?window:commonjsGlobal,util$6={assign:assign,create:create$1,trim:trim$1,bind:bind$1,slice:slice$1,each:each$7,map:map,pluck:pluck$1,isList:isList$1,isFunction:isFunction$1,isObject:isObject$1,Global:Global$5};function make_assign(){return Object.assign||function(s,e,t,r){for(var i=1;i<arguments.length;i++)each$7(Object(arguments[i]),function(e,t){s[t]=e});return s}}function make_create(){return Object.create?function(e,t,s,r){var i=slice$1(arguments,1);return assign.apply(this,[Object.create(e)].concat(i))}:function(e,t,s,r){var i=slice$1(arguments,1);return n.prototype=e,assign.apply(this,[new n].concat(i))};function n(){}}function make_trim(){return String.prototype.trim?function(e){return String.prototype.trim.call(e)}:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}}function bind$1(e,t){return function(){return t.apply(e,Array.prototype.slice.call(arguments,0))}}function slice$1(e,t){return Array.prototype.slice.call(e,t||0)}function each$7(e,s){pluck$1(e,function(e,t){return s(e,t),!1})}function map(e,s){var r=isList$1(e)?[]:{};return pluck$1(e,function(e,t){return r[t]=s(e,t),!1}),r}function pluck$1(e,t){if(isList$1(e)){for(var s=0;s<e.length;s++)if(t(e[s],s))return e[s]}else for(var r in e)if(e.hasOwnProperty(r)&&t(e[r],r))return e[r]}function isList$1(e){return null!=e&&"function"!=typeof e&&"number"==typeof e.length}function isFunction$1(e){return e&&"[object Function]"==={}.toString.call(e)}function isObject$1(e){return e&&"[object Object]"==={}.toString.call(e)}var util$5=util$6,slice=util$5.slice,pluck=util$5.pluck,each$6=util$5.each,bind=util$5.bind,create=util$5.create,isList=util$5.isList,isFunction=util$5.isFunction,isObject=util$5.isObject,storeEngine={createStore:createStore},storeAPI={version:"2.0.12",enabled:!1,get:function(e,t){e=this.storage.read(this._namespacePrefix+e);return this._deserialize(e,t)},set:function(e,t){return void 0===t?this.remove(e):(this.storage.write(this._namespacePrefix+e,this._serialize(t)),t)},remove:function(e){this.storage.remove(this._namespacePrefix+e)},each:function(s){var r=this;this.storage.each(function(e,t){s.call(r,r._deserialize(e),(t||"").replace(r._namespaceRegexp,""))})},clearAll:function(){this.storage.clearAll()},hasNamespace:function(e){return this._namespacePrefix=="__storejs_"+e+"_"},createStore:function(){return createStore.apply(this,arguments)},addPlugin:function(e){this._addPlugin(e)},namespace:function(e){return createStore(this.storage,this.plugins,e)}};function _warn(){var e="undefined"==typeof console?null:console;e&&(e.warn||e.log).apply(e,arguments)}function createStore(e,t,s){s=s||"",e&&!isList(e)&&(e=[e]),t&&!isList(t)&&(t=[t]);var r=s?"__storejs_"+s+"_":"",i=s?new RegExp("^"+r):null;if(!/^[a-zA-Z0-9_\-]*$/.test(s))throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes");var n=create({_namespacePrefix:r,_namespaceRegexp:i,_testStorage:function(e){try{var t="__storejs__test__",s=(e.write(t,t),e.read(t)===t);return e.remove(t),s}catch(e){return!1}},_assignPluginFnProp:function(r,e){var i=this[e];this[e]=function(){var s=slice(arguments,0),e=this;var t=[function(){if(i)return each$6(arguments,function(e,t){s[t]=e}),i.apply(e,s)}].concat(s);return r.apply(e,t)}},_serialize:function(e){return JSON.stringify(e)},_deserialize:function(e,t){if(!e)return t;var s="";try{s=JSON.parse(e)}catch(t){s=e}return void 0!==s?s:t},_addStorage:function(e){this.enabled||this._testStorage(e)&&(this.storage=e,this.enabled=!0)},_addPlugin:function(s){var r=this;if(isList(s))each$6(s,function(e){r._addPlugin(e)});else if(!pluck(this.plugins,function(e){return s===e})){if(this.plugins.push(s),!isFunction(s))throw new Error("Plugins must be function values that return objects");var e=s.call(this);if(!isObject(e))throw new Error("Plugins must return an object of function properties");each$6(e,function(e,t){if(!isFunction(e))throw new Error("Bad plugin property: "+t+" from plugin "+s.name+". Plugins should only return functions.");r._assignPluginFnProp(e,t)})}},addStorage:function(e){_warn("store.addStorage(storage) is deprecated. Use createStore([storages])"),this._addStorage(e)}},storeAPI,{plugins:[]});return n.raw={},each$6(n,function(e,t){isFunction(e)&&(n.raw[t]=bind(n,e))}),each$6(e,function(e){n._addStorage(e)}),each$6(t,function(e){n._addPlugin(e)}),n}var util$4=util$6,Global$4=util$4.Global,localStorage_1={name:"localStorage",read:read$5,write:write$5,each:each$5,remove:remove$5,clearAll:clearAll$5};function localStorage(){return Global$4.localStorage}function read$5(e){return localStorage().getItem(e)}function write$5(e,t){return localStorage().setItem(e,t)}function each$5(e){for(var t=localStorage().length-1;0<=t;t--){var s=localStorage().key(t);e(read$5(s),s)}}function remove$5(e){return localStorage().removeItem(e)}function clearAll$5(){return localStorage().clear()}var util$3=util$6,Global$3=util$3.Global,oldFFGlobalStorage={name:"oldFF-globalStorage",read:read$4,write:write$4,each:each$4,remove:remove$4,clearAll:clearAll$4},globalStorage=Global$3.globalStorage;function read$4(e){return globalStorage[e]}function write$4(e,t){globalStorage[e]=t}function each$4(e){for(var t=globalStorage.length-1;0<=t;t--){var s=globalStorage.key(t);e(globalStorage[s],s)}}function remove$4(e){return globalStorage.removeItem(e)}function clearAll$4(){each$4(function(e,t){delete globalStorage[e]})}var util$2=util$6,Global$2=util$2.Global,oldIEUserDataStorage={name:"oldIE-userDataStorage",write:write$3,read:read$3,each:each$3,remove:remove$3,clearAll:clearAll$3},storageName="storejs",doc$1=Global$2.document,_withStorageEl=_makeIEStorageElFunction(),disable=(Global$2.navigator?Global$2.navigator.userAgent:"").match(/ (MSIE 8|MSIE 9|MSIE 10)\./);function write$3(e,t){var s;disable||(s=fixKey(e),_withStorageEl(function(e){e.setAttribute(s,t),e.save(storageName)}))}function read$3(e){var t,s;if(!disable)return t=fixKey(e),s=null,_withStorageEl(function(e){s=e.getAttribute(t)}),s}function each$3(i){_withStorageEl(function(e){for(var t=e.XMLDocument.documentElement.attributes,s=t.length-1;0<=s;s--){var r=t[s];i(e.getAttribute(r.name),r.name)}})}function remove$3(e){var t=fixKey(e);_withStorageEl(function(e){e.removeAttribute(t),e.save(storageName)})}function clearAll$3(){_withStorageEl(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(storageName);for(var s=t.length-1;0<=s;s--)e.removeAttribute(t[s].name);e.save(storageName)})}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function fixKey(e){return e.replace(/^\d/,"___$&").replace(forbiddenCharsRegex,"___")}function _makeIEStorageElFunction(){if(!doc$1||!doc$1.documentElement||!doc$1.documentElement.addBehavior)return null;var s,e,r;try{(e=new ActiveXObject("htmlfile")).open(),e.write('<script>document.w=window<\/script><iframe src="/favicon.ico"></iframe>'),e.close(),s=e.w.frames[0].document,r=s.createElement("div")}catch(e){r=doc$1.createElement("div"),s=doc$1.body}return function(e){var t=[].slice.call(arguments,0);t.unshift(r),s.appendChild(r),r.addBehavior("#default#userData"),r.load(storageName),e.apply(this,t),s.removeChild(r)}}var util$1=util$6,Global$1=util$1.Global,trim=util$1.trim,cookieStorage={name:"cookieStorage",read:read$2,write:write$2,each:each$2,remove:remove$2,clearAll:clearAll$2},doc=Global$1.document;function read$2(e){if(!e||!_has(e))return null;e="(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(doc.cookie.replace(new RegExp(e),"$1"))}function each$2(e){for(var t,s,r=doc.cookie.split(/; ?/g),i=r.length-1;0<=i;i--)trim(r[i])&&(t=r[i].split("="),s=unescape(t[0]),e(unescape(t[1]),s))}function write$2(e,t){e&&(doc.cookie=escape(e)+"="+escape(t)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/")}function remove$2(e){e&&_has(e)&&(doc.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function clearAll$2(){each$2(function(e,t){remove$2(t)})}function _has(e){return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(doc.cookie)}var util=util$6,Global=util.Global,sessionStorage_1={name:"sessionStorage",read:read$1,write:write$1,each:each$1,remove:remove$1,clearAll:clearAll$1};function sessionStorage(){return Global.sessionStorage}function read$1(e){return sessionStorage().getItem(e)}function write$1(e,t){return sessionStorage().setItem(e,t)}function each$1(e){for(var t=sessionStorage().length-1;0<=t;t--){var s=sessionStorage().key(t);e(read$1(s),s)}}function remove$1(e){return sessionStorage().removeItem(e)}function clearAll$1(){return sessionStorage().clear()}var memoryStorage_1={name:"memoryStorage",read:read,write:write,each:each,remove:remove,clearAll:clearAll},memoryStorage={};function read(e){return memoryStorage[e]}function write(e,t){memoryStorage[e]=t}function each(e){for(var t in memoryStorage)memoryStorage.hasOwnProperty(t)&&e(memoryStorage[t],t)}function remove(e){delete memoryStorage[e]}function clearAll(e){memoryStorage={}}var all=[localStorage_1,oldFFGlobalStorage,oldIEUserDataStorage,cookieStorage,sessionStorage_1,memoryStorage_1],json2=("object"!=typeof JSON&&(JSON={}),function(){var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/g,rx_escapable=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta,rep;function f(e){return e<10?"0"+e:e}function this_value(){return this.valueOf()}function quote(e){return rx_escapable.lastIndex=0,rx_escapable.test(e)?'"'+e.replace(rx_escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var s,r,i,n,a,o=gap,l=t[e];switch(l&&"object"==typeof l&&"function"==typeof l.toJSON&&(l=l.toJSON(e)),typeof(l="function"==typeof rep?rep.call(t,e,l):l)){case"string":return quote(l);case"number":return isFinite(l)?String(l):"null";case"boolean":case"null":return String(l);case"object":if(!l)return"null";if(gap+=indent,a=[],"[object Array]"===Object.prototype.toString.apply(l)){for(n=l.length,s=0;s<n;s+=1)a[s]=str(s,l)||"null";return i=0===a.length?"[]":gap?"[\n"+gap+a.join(",\n"+gap)+"\n"+o+"]":"["+a.join(",")+"]",gap=o,i}if(rep&&"object"==typeof rep)for(n=rep.length,s=0;s<n;s+=1)"string"==typeof rep[s]&&(i=str(r=rep[s],l))&&a.push(quote(r)+(gap?": ":":")+i);else for(r in l)Object.prototype.hasOwnProperty.call(l,r)&&(i=str(r,l))&&a.push(quote(r)+(gap?": ":":")+i);return i=0===a.length?"{}":gap?"{\n"+gap+a.join(",\n"+gap)+"\n"+o+"}":"{"+a.join(",")+"}",gap=o,i}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value),"function"!=typeof JSON.stringify&&(meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(e,t,s){var r;if(indent=gap="","number"==typeof s)for(r=0;r<s;r+=1)indent+=" ";else"string"==typeof s&&(indent=s);if(!(rep=t)||"function"==typeof t||"object"==typeof t&&"number"==typeof t.length)return str("",{"":e});throw new Error("JSON.stringify")}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){var j;function walk(e,t){var s,r,i=e[t];if(i&&"object"==typeof i)for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&(void 0!==(r=walk(i,s))?i[s]=r:delete i[s]);return reviver.call(e,t,i)}if(text=String(text),rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),rx_one.test(text.replace(rx_two,"@").replace(rx_three,"]").replace(rx_four,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),json2Plugin);function json2Plugin(){return{}}var engine=storeEngine,storages=all,plugins=[json2],store_legacy=engine.createStore(storages,plugins);class SallaStorage{constructor(e){e.on("storage::item.remove",e=>this.remove(e)),e.on("storage::item.set",(e,t)=>this.set(e,t)),this.store=store_legacy}set(e,t){var s,r;return e.includes(".")?(r={[s=e.split(".")[0]]:store_legacy.get(s)},r=salla.helpers.setNested(r,e,t),store_legacy.set(s,r[s])):store_legacy.set(e,t)}remove(e){return store_legacy.remove(e)}get(e,t){var s;return e.includes(".")?(s=e.split(".")[0],salla.helpers.getNested({[s]:store_legacy.get(s)},e)):store_legacy.get(e,t)}}let event$1=new sallaEmitter,api=new SallaApi(event$1);window.Salla=window.salla={notify:Notify,api:api,event:event$1,infiniteScroll:new InfiniteScroll(void 0,event$1.infiniteScroll),helpers:Helpers,config:new SallaConfig,storage:new SallaStorage(event$1),cookie:new SallaCookie(event$1),lang:new SallaLang,cart:new Cart(api.cart,event$1.cart),auth:new Auth(api.auth,event$1.auth),gift:new Gift(api.gift,event$1.gift),order:new Order(api.order,event$1.order),offer:new Offer(api.offer,event$1.offer),search:new Search(api.search,event$1.search),coupon:new Coupon(api.coupon,event$1.coupon),comment:new Comment(api.comment,event$1.comment),loyalty:new Loyalty(api.loyalty,event$1.loyalty),product:new Product(api.product,event$1.product),currency:new Currency(api.currency,event$1.currency),document:new Document(api.document,event$1.document),feedback:new Feedback(api.feedback,event$1.feedback),twilight:new Twilight(api.twilight,event$1.twilight),form:new Form,wishlist:new Wishlist(api.wishlist,event$1.wishlist),scope:new Scope(api.scope,event$1.scope),init:e=>api.twilight.init(e),log:Notify.log,success:Notify.success,error:Notify.error,onReady:e=>document.addEventListener("DOMContentLoaded",e),AppHelpers:AppHelpers,money:Helpers.money,url:Helpers.url,call:e=>{let t=salla,s=e.split(".");for(;s.length&&(t=t[s.shift()]););return t}};var salla$1=salla;exports.default=salla$1});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).salla={})}(this,function(exports){"use strict";let notifier=function(e,t,s){return alert(e,t,s)},setNotifier=function(e){notifier=e},fire=function(e,t,s){return notifier(e,t,s)},error$1=function(e,t){return notifier(e,types.error,t)},info=function(e,t){return notifier(e,types.info,t)},success=function(e,t){return notifier(e,types.success,t)},logger=function(...e){return console.log(console.trace()),console.log(...["%cTwilight","color: white;background:#040c20;font-weight: bold; font-size:10px; padding:2px 6px; border-radius: 5px"].concat(...e))},setLogger=function(e){logger=e},log=function(...e){return logger(...e)};var sallaInitiated=function(){var e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach(e=>{error$1(decodeURI(e.replace("?danger=","").replace("&danger=","")))})},types={error:"error",success:"success",info:"info"},Notify={fire:fire,setNotifier:setNotifier,log:log,setLogger:setLogger,error:error$1,success:success,info:info,sallaInitiated:sallaInitiated,types:types};class BaseEvent{constructor(e){this.parent=e,this.events={},this.namespace="";e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)})}createDynamicEventFuns(s){if(!this[s]){let t=this;this[s]=function(...e){return t.dispatch(s,...e)}}}createDynamicListenerFuns(s){var e="on"+s.charAt(0).toUpperCase()+s.slice(1);if(!this[e]){let t=this;this[e]=function(e){return t.on(s,e)}}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+this.parent.delimiter+e}dispatch(e,...t){return this.parent.dispatch(this.getEventName(e),...t)}on(e,t){this.parent.addListener(this.getEventName(e),t)}register(e,t){this.on(e,t)}registerEventTemporary(e,t,s){s=s||1,emitter.many(e,s,t)}}class CartEvents extends BaseEvent{constructor(e){super(e),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",summaryFetched:"summary.fetched",summaryNotFetched:"summary.not.fetched",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset"},this.after_init()}updated(e){return salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.offer.event.existed(e.offer),salla.storage.set("cart.summary",e={total:e.cart.total,items_total:e.cart.sub_total,total_discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e)):(salla.log("Cart summary not an object!",e),this.dispatch("updated"))}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}summaryFetched(e){this.updated(e)}fullSummaryFetched(e){this.updated(e)}clearCartSummary(){var e=salla.storage.get("cart_widget_summary");e&&(e.count||e.items||e.items_count)&&salla.cart.api.summary()}}class GiftEvents extends BaseEvent{constructor(e){super(e),this.namespace="gift",this.events={buyingSucceeded:"buying.succeeded",buyingFailed:"buying.failed"},this.after_init()}}class LoyaltyEvents extends BaseEvent{constructor(e){super(e),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed"},this.after_init()}}class AuthEvents extends BaseEvent{constructor(e){super(e),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",codeReSent:"code.re-sent",codeNotReSent:"code.not.re-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",tokenFetched:"token.fetched",refreshFailed:"refresh.failed"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null):this.next_event=null,this.dispatch("login",...arguments)}verified(e){return dataLayer&&(dataLayer[0].customer=e.customer),this.dispatch("verified",...arguments)}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}}class SearchEvents extends BaseEvent{constructor(e){super(e),this.namespace="search",this.events={finished:"finished",failed:"failed"},this.after_init()}}class WishlistEvents extends BaseEvent{constructor(e){super(e),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}}class CommentEvents extends BaseEvent{constructor(e){super(e),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}}class OrderEvents extends BaseEvent{constructor(e){super(e),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",reOrdered:"re.ordered",reOrderFailed:"re.order.failed"},this.after_init()}}class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class DocumentEvents extends BaseEvent{constructor(e){super(e),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init()}onClick(e,t){this.fireCallableFuns("click",e,t)}onChange(e,t){this.fireCallableFuns("change",e,t)}onSubmit(e,t){this.fireCallableFuns("submit",e,t)}onKeyup(e,t){this.fireCallableFuns("keyup",e,t)}fireCallableFuns(e,t,s){this.on(e,e=>{"function"!=typeof t?"function"==typeof s&&e.target.matches(t)&&s(e):t(e)})}fireEvent(e,t,...s){return this.fireEventForElements(e,t,!1,...s)}fireEventForAll(e,t,...s){return this.fireEventForElements(e,t,!0,...s)}fireEventForElements(e,t,s,...r){if("string"==typeof e){if(s)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,!1,...r));e=document.querySelector(e)}{if(e)return s=new CustomEvent(t,...r),e.dispatchEvent(s);salla.log("Failed To get element to fire event: "+t)}}}class ProductEvents extends BaseEvent{constructor(e){super(e),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed"},this.after_init()}}class OfferEvents extends BaseEvent{constructor(e){super(e),this.namespace="offer",this.events={existed:"existed",increased:"increase",increaseFailed:"increase.failed",fetchDetailsFailed:"fetch.details.failed",detailsFetched:"details.fetched"},this.after_init()}}class CouponEvents extends BaseEvent{constructor(e){super(e),this.namespace="coupon",this.events={added:"added",removed:"removed",addedFailed:"added.failed",removedFailed:"removed.failed"},this.after_init()}added(e,t){return salla.event.cart.updated(e.data),this.dispatch("added",e,t)}removed(e,t){return salla.event.cart.updated(e.data),this.dispatch("removed",e,t)}}class FeedbackEvents extends BaseEvent{constructor(e){super(e),this.namespace="feedback",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productRated:"product.rated",productFailed:"product.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init()}}class CurrencyEvents extends BaseEvent{constructor(e){super(e),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}changed(...e){return salla.cart.api.summary().then(()=>this.dispatch("changed",...e))}}class TwilightEvents extends BaseEvent{constructor(e){super(e),this.namespace="twilight",this.events={initiated:"initiated"},this.after_init()}}class ScopeEvents extends BaseEvent{constructor(e){super(e),this.namespace="scope",this.events={},this.after_init()}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},eventemitter2$1={exports:{}},eventemitter2=(!function(e){function h(){this._events={},this._conf&&t.call(this,this._conf)}function t(e){e&&((this._conf=e).delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==y&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function d(e,t){var s="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";this.verboseMemoryLeak&&(s+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning?((t=new Error(s)).name="MaxListenersExceededWarning",t.emitter=this,t.count=e,process.emitWarning(t)):(console.error(s),console.trace&&console.trace())}function c(e,t,s){var r=arguments.length;switch(r){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,s];default:for(var i=new Array(r);r--;)i[r]=arguments[r];return i}}function s(e,t){for(var s={},r=e.length,i=t?value.length:0,n=0;n<r;n++)s[e[n]]=n<i?t[n]:y;return s}function p(e,t,s){var r,i;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(s.on||s.off)&&(r=s.on,i=s.off),t.addEventListener?(r=t.addEventListener,i=t.removeEventListener):t.addListener?(r=t.addListener,i=t.removeListener):t.on&&(r=t.on,i=t.off),!r&&!i)throw Error("target does not implement any known event API");if("function"!=typeof r)throw TypeError("on method must be a function");if("function"!=typeof i)throw TypeError("off method must be a function");this._on=r,this._off=i;s=e._observers;s?s.push(this):e._observers=[this]}function f(e,t,s,r){var i=Object.assign({},t);if(!e)return i;if("object"!=typeof e)throw TypeError("options must be an object");var n,a,o,l=Object.keys(e),c=l.length;function u(e){throw Error('Invalid "'+n+'" option value'+(e?". Reason: "+e:""))}for(var h=0;h<c;h++){if(n=l[h],!r&&!b.call(t,n))throw Error('Unknown "'+n+'" option');(a=e[n])!==y&&(o=s[n],i[n]=o?o(a,u):a)}return i}function r(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function i(i){var n="value must be type of "+i.join("|"),a=i.length,r=i[0],o=i[1];return 1===a?function(e,t){if(typeof e===r)return e;t(n)}:2===a?function(e,t){var s=typeof e;if(s===r||s===o)return e;t(n)}:function(e,t){for(var s=typeof e,r=a;0<r--;)if(s===i[r])return e;t(n)}}function l(a,o,l){var c,u,h,d=0,p=new a(function(t,s,e){function r(){u=u&&null,d&&(clearTimeout(d),d=0)}l=f(l,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),c=!l.overload&&"function"==typeof a.prototype.cancel&&"function"==typeof e;function i(e){r(),t(e)}function n(e){r(),s(e)}c?o(i,n,e):(u=[function(e){n(e||Error("canceled"))}],o(i,n,function(e){if(h)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");u.push(e)}),h=!0),0<l.timeout&&(d=setTimeout(function(){var e=Error("timeout");e.code="ETIMEDOUT",d=0,p.cancel(e),s(e)},l.timeout))});return c||(p.cancel=function(e){if(u){for(var t=u.length,s=1;s<t;s++)u[s](e);u[0](e),u=null}}),p}function g(e){var t=this._observers;if(!t)return-1;for(var s=t.length,r=0;r<s;r++)if(t[r]._target===e)return r;return-1}function _(e,t,s,r,i){if(!s)return null;if(0===r){var n=typeof t;if("string"==n){var a,o,l=0,c=0,u=this.delimiter,h=u.length;if(-1!==(o=t.indexOf(u))){for(a=new Array(5);a[l++]=t.slice(c,o),-1!==(o=t.indexOf(u,c=o+h)););a[l++]=t.slice(c),t=a,i=l}else t=[t],i=1}else i="object"==n?t.length:(t=[t],1)}var d,p,f,g,m,v,y=null,b=t[r],w=t[r+1];if(r===i)s._listeners&&(y=("function"==typeof s._listeners?e&&e.push(s._listeners):e&&e.push.apply(e,s._listeners),[s]));else{if("*"===b){for(o=(m=A(s)).length;0<o--;)"_listeners"!==(d=m[o])&&(v=_(e,t,s[d],r+1,i))&&(y?y.push.apply(y,v):y=v);return y}if("**"===b){for((g=r+1===i||r+2===i&&"*"===w)&&s._listeners&&(y=_(e,t,s,i,i)),o=(m=A(s)).length;0<o--;)"_listeners"!==(d=m[o])&&((v="*"===d||"**"===d?(s[d]._listeners&&!g&&(v=_(e,t,s[d],i,i))&&(y?y.push.apply(y,v):y=v),_(e,t,s[d],r,i)):_(e,t,s[d],d===w?r+2:r,i))&&(y?y.push.apply(y,v):y=v));return y}s[b]&&(y=_(e,t,s[b],r+1,i))}if((n=s["*"])&&_(e,t,n,r+1,i),p=s["**"])if(r<i)for(p._listeners&&_(e,t,p,i,i),o=(m=A(p)).length;0<o--;)"_listeners"!==(d=m[o])&&(d===w?_(e,t,p[d],r+2,i):d===b?_(e,t,p[d],r+1,i):((f={})[d]=p[d],_(e,t,{"**":f},r+1,i)));else p._listeners?_(e,t,p,i,i):p["*"]&&p["*"]._listeners&&_(e,t,p["*"],i,i);return y}function u(e,t,s,r){for(var i,n,a,o=A(e),l=o.length,c=e._listeners;0<l--;)i=e[a=o[l]],n="_listeners"===a?s:s?s.concat(a):[a],a=r||"symbol"==typeof a,c&&t.push(a?n:n.join(this.delimiter)),"object"==typeof i&&u.call(this,i,t,n,a);return t}function m(e){for(var t,s,r,i=A(e),n=i.length;0<n--;)(t=e[s=i[n]])&&(r=!0,"_listeners"===s||m(t)||delete e[s]);return r}function v(e,t,s){this.emitter=e,this.event=t,this.listener=s}function n(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,t.call(this,e)}var y,b,w,S,E,a,x,A,o,k,L;b=Object.hasOwnProperty,w=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},S="object"==typeof process&&"function"==typeof process.nextTick,E="function"==typeof Symbol,a="object"==typeof Reflect,x="function"==typeof setImmediate?setImmediate:setTimeout,A=E?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys,Object.assign(p.prototype,{subscribe:function(s,r,i){function t(){var e=c.apply(null,arguments),t={data:e,name:r,original:s};i?!1!==i.call(a,t)&&o.emit.apply(o,[t.name].concat(e)):o.emit.apply(o,[r].concat(e))}var n=this,a=this._target,o=this._emitter,l=this._listeners;if(l[s])throw Error("Event '"+s+"' is already listening");this._listenersCount++,o._newListener&&o._removeListener&&!n._onNewListener?(this._onNewListener=function(e){e===r&&null===l[s]&&(l[s]=t,n._on.call(a,s,t))},o.on("newListener",this._onNewListener),this._onRemoveListener=function(e){e===r&&!o.hasListeners(e)&&l[s]&&(l[s]=null,n._off.call(a,s,t))},l[s]=null,o.on("removeListener",this._onRemoveListener)):(l[s]=t,n._on.call(a,s,t))},unsubscribe:function(e){var t,s,r,i=this,n=this._listeners,a=this._emitter,o=this._off,l=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function c(){i._onNewListener&&(a.off("newListener",i._onNewListener),a.off("removeListener",i._onRemoveListener),i._onNewListener=null,i._onRemoveListener=null);var e=g.call(a,i);a._observers.splice(e,1)}if(e)(t=n[e])&&(o.call(l,e,t),delete n[e],--this._listenersCount||c());else{for(r=(s=A(n)).length;0<r--;)e=s[r],o.call(l,e,n[e]);this._listeners={},this._listenersCount=0,c()}}}),o=i(["function"]),k=i(["object","function"]),v.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},(n.EventEmitter2=n).prototype.listenTo=function(c,e,u){if("object"!=typeof c)throw TypeError("target musts be an object");var h=this;function t(e){if("object"!=typeof e)throw TypeError("events must be an object");for(var t,s=u.reducers,r=g.call(h,c),i=-1===r?new p(h,c,u):h._observers[r],n=A(e),a=n.length,o="function"==typeof s,l=0;l<a;l++)t=n[l],i.subscribe(t,e[t]||t,o?s:s&&s[t])}return u=f(u,{on:y,off:y,reducers:y},{on:o,off:o,reducers:k}),w(e)?t(s(e)):t("string"==typeof e?s(e.split(/\s+/)):e),this},n.prototype.stopListeningTo=function(e,t){var s=this._observers;if(!s)return!1;var r,i=s.length,n=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;0<i--;)r=s[i],e&&r._target!==e||(r.unsubscribe(t),n=!0);return n},n.prototype.delimiter=".",n.prototype.setMaxListeners=function(e){e!==y&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},n.prototype.getMaxListeners=function(){return this._maxListeners},n.prototype.event="",n.prototype.once=function(e,t,s){return this._once(e,t,!1,s)},n.prototype.prependOnceListener=function(e,t,s){return this._once(e,t,!0,s)},n.prototype._once=function(e,t,s,r){return this._many(e,1,t,s,r)},n.prototype.many=function(e,t,s,r){return this._many(e,t,s,!1,r)},n.prototype.prependMany=function(e,t,s,r){return this._many(e,t,s,!0,r)},n.prototype._many=function(e,t,s,r,i){var n=this;if("function"!=typeof s)throw new Error("many only accepts instances of Function");function a(){return 0==--t&&n.off(e,a),s.apply(this,arguments)}return a._origin=s,this._on(e,a,r,i)},n.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,s,r,i,n,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return!1;if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(s=a.length,E)for(r=0;r<s;r++)if("symbol"==typeof a[r]){n=!0;break}n||(a=a.join(this.delimiter))}var l,c=arguments.length;if(this._all&&this._all.length)for(r=0,s=(l=this._all.slice()).length;r<s;r++)switch(this.event=a,c){case 1:l[r].call(this,a);break;case 2:l[r].call(this,a,arguments[1]);break;case 3:l[r].call(this,a,arguments[1],arguments[2]);break;default:l[r].apply(this,arguments)}if(o)_.call(this,l=[],e,this.listenerTree,0,s);else{if("function"==typeof(l=this._events[a])){switch(this.event=a,c){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(c-1),i=1;i<c;i++)t[i-1]=arguments[i];l.apply(this,t)}return!0}l=l&&l.slice()}if(l&&l.length){if(3<c)for(t=new Array(c-1),i=1;i<c;i++)t[i-1]=arguments[i];for(r=0,s=l.length;r<s;r++)switch(this.event=a,c){case 1:l[r].call(this);break;case 2:l[r].call(this,arguments[1]);break;case 3:l[r].call(this,arguments[1],arguments[2]);break;default:l[r].apply(this,t)}return!0}if(this.ignoreErrors||this._all||"error"!==a)return!!this._all;throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.")},n.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,s,r,i,n,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(r=a.length,E)for(i=0;i<r;i++)if("symbol"==typeof a[i]){t=!0;break}t||(a=a.join(this.delimiter))}var l,c=[],u=arguments.length;if(this._all)for(i=0,r=this._all.length;i<r;i++)switch(this.event=a,u){case 1:c.push(this._all[i].call(this,a));break;case 2:c.push(this._all[i].call(this,a,arguments[1]));break;case 3:c.push(this._all[i].call(this,a,arguments[1],arguments[2]));break;default:c.push(this._all[i].apply(this,arguments))}if(o?_.call(this,l=[],e,this.listenerTree,0):l=this._events[a],"function"==typeof l)switch(this.event=a,u){case 1:c.push(l.call(this));break;case 2:c.push(l.call(this,arguments[1]));break;case 3:c.push(l.call(this,arguments[1],arguments[2]));break;default:for(s=new Array(u-1),n=1;n<u;n++)s[n-1]=arguments[n];c.push(l.apply(this,s))}else if(l&&l.length){if(l=l.slice(),3<u)for(s=new Array(u-1),n=1;n<u;n++)s[n-1]=arguments[n];for(i=0,r=l.length;i<r;i++)switch(this.event=a,u){case 1:c.push(l[i].call(this));break;case 2:c.push(l[i].call(this,arguments[1]));break;case 3:c.push(l[i].call(this,arguments[1],arguments[2]));break;default:c.push(l[i].apply(this,s))}}else if(!this.ignoreErrors&&!this._all&&"error"===a)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(c)},n.prototype.on=function(e,t,s){return this._on(e,t,!1,s)},n.prototype.prependListener=function(e,t,s){return this._on(e,t,!0,s)},n.prototype.onAny=function(e){return this._onAny(e,!1)},n.prototype.prependAny=function(e){return this._onAny(e,!0)},n.prototype.addListener=n.prototype.on,n.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},n.prototype._on=function(e,t,s,r){if("function"==typeof e)return this._onAny(e,t),this;if("function"!=typeof t)throw new Error("on only accepts instances of Function");this._events||h.call(this);var i=this;return r!==y&&(t=(r=function(e,t,s){if(!0===s)i=!0;else if(!1===s)r=!0;else{if(!s||"object"!=typeof s)throw TypeError("options should be an object or true");var r=s.async,i=s.promisify,n=s.nextTick,a=s.objectify}if(r||n||i){var o=t,s=t._origin||t;if(n&&!S)throw Error("process.nextTick is not supported");i===y&&(i="AsyncFunction"===t.constructor.name),(t=function(){var e=arguments,t=this,s=this.event;return i?n?Promise.resolve():new Promise(function(e){x(e)}).then(function(){return t.event=s,o.apply(t,e)}):(n?process.nextTick:x)(function(){t.event=s,o.apply(t,e)})})._async=!0,t._origin=s}return[t,a?new v(this,e,t):this]}.call(this,e,t,r))[0],i=r[1]),this._newListener&&this.emit("newListener",e,t),this.wildcard?function(e,t,s){var r,i=0,n=0,a=this.delimiter,o=a.length;if("string"==typeof e)if(-1!==(u=e.indexOf(a))){for(r=new Array(5);r[i++]=e.slice(n,u),-1!==(u=e.indexOf(a,n=u+o)););r[i++]=e.slice(n)}else r=[e],i=1;else i=(r=e).length;if(1<i)for(u=0;u+1<i;u++)if("**"===r[u]&&"**"===r[u+1])return;for(var l,c=this.listenerTree,u=0;u<i;u++)if(c=c[l=r[u]]||(c[l]={}),u===i-1)return c._listeners?("function"==typeof c._listeners&&(c._listeners=[c._listeners]),s?c._listeners.unshift(t):c._listeners.push(t),!c._listeners.warned&&0<this._maxListeners&&c._listeners.length>this._maxListeners&&(c._listeners.warned=!0,d.call(this,c._listeners.length,l))):c._listeners=t,!0;return!0}.call(this,e,t,s):this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),s?this._events[e].unshift(t):this._events[e].push(t),!this._events[e].warned&&0<this._maxListeners&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,d.call(this,this._events[e].length,e))):this._events[e]=t,i},n.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var s=[];if(this.wildcard){var r="string"==typeof e?e.split(this.delimiter):e.slice();if(!(s=_.call(this,null,r,this.listenerTree,0)))return this}else{if(!this._events[e])return this;a=this._events[e],s.push({_listeners:a})}for(var i=0;i<s.length;i++){var n=s[i],a=n._listeners;if(w(a)){for(var o=-1,l=0,c=a.length;l<c;l++)if(a[l]===t||a[l].listener&&a[l].listener===t||a[l]._origin&&a[l]._origin===t){o=l;break}if(o<0)continue;return(this.wildcard?n._listeners:this._events[e]).splice(o,1),0===a.length&&(this.wildcard?delete n._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(a===t||a.listener&&a.listener===t||a._origin&&a._origin===t)&&(this.wildcard?delete n._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&m(this.listenerTree),this},n.prototype.offAny=function(e){var t,s=0,r=0;if(e&&this._all&&0<this._all.length){for(s=0,r=(t=this._all).length;s<r;s++)if(e===t[s])return t.splice(s,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(s=0,r=t.length;s<r;s++)this.emit("removeListenerAny",t[s]);this._all=[]}return this},n.prototype.removeListener=n.prototype.off,n.prototype.removeAllListeners=function(e){if(e===y)return this._events&&h.call(this),this;if(this.wildcard){var t,s=_.call(this,null,e,this.listenerTree,0);if(!s)return this;for(t=0;t<s.length;t++)s[t]._listeners=null;this.listenerTree&&m(this.listenerTree)}else this._events&&(this._events[e]=null);return this},n.prototype.listeners=function(e){var t,s,r,i,n,a=this._events;if(e===y){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!a)return[];for(i=(t=A(a)).length,r=[];0<i--;)"function"==typeof(s=a[t[i]])?r.push(s):r.push.apply(r,s);return r}if(this.wildcard){if(!(n=this.listenerTree))return[];var o=[],l="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,o,l,n,0),o}return a&&(s=a[e])?"function"==typeof s?[s]:s:[]},n.prototype.eventNames=function(e){var t=this._events;return this.wildcard?u.call(this,this.listenerTree,[],null,e):t?A(t):[]},n.prototype.listenerCount=function(e){return this.listeners(e).length},n.prototype.hasListeners=function(e){if(this.wildcard)return s=[],t="string"==typeof e?e.split(this.delimiter):e.slice(),_.call(this,s,t,this.listenerTree,0),0<s.length;var t=this._events,s=this._all;return!!(s&&s.length||t&&(e===y?A(t).length:t[e]))},n.prototype.listenersAny=function(){return this._all||[]},n.prototype.waitFor=function(i,n){var a=this,e=typeof n;return"number"==e?n={timeout:n}:"function"==e&&(n={filter:n}),l((n=f(n,{timeout:0,filter:y,handleError:!1,Promise:Promise,overload:!1},{filter:o,Promise:r})).Promise,function(t,s,e){function r(){var e=n.filter;e&&!e.apply(a,arguments)||(a.off(i,r),n.handleError?(e=arguments[0])?s(e):t(c.apply(null,arguments).slice(1)):t(c.apply(null,arguments)))}e(function(){a.off(i,r)}),a._on(i,r,!1)},{timeout:n.timeout,overload:n.overload})},L=n.prototype,Object.defineProperties(n,{defaultMaxListeners:{get:function(){return L._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");L._maxListeners=e},enumerable:!0},once:{value:function(a,o,e){return l((e=f(e,{Promise:Promise,timeout:0,overload:!1},{Promise:r})).Promise,function(e,t,s){var r;if("function"==typeof a.addEventListener)return r=function(){e(c.apply(null,arguments))},s(function(){a.removeEventListener(o,r)}),a.addEventListener(o,r,{once:!0});function i(){n&&a.removeListener("error",n),e(c.apply(null,arguments))}var n;"error"!==o&&(n=function(e){a.removeListener(o,i),t(e)},a.once("error",n)),s(function(){n&&a.removeListener("error",n),a.removeListener(o,i)}),a.once(o,i)},{timeout:e.timeout,overload:e.overload})},writable:!0,configurable:!0}}),Object.defineProperties(L,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=n}(eventemitter2$1),eventemitter2$1.exports);class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.cart=new CartEvents(this),this.gift=new GiftEvents(this),this.loyalty=new LoyaltyEvents(this),this.auth=new AuthEvents(this),this.search=new SearchEvents(this),this.wishlist=new WishlistEvents(this),this.comment=new CommentEvents(this),this.order=new OrderEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.document=new DocumentEvents(this),this.product=new ProductEvents(this),this.offer=new OfferEvents(this),this.coupon=new CouponEvents(this),this.feedback=new FeedbackEvents(this),this.currency=new CurrencyEvents(this),this.twilight=new TwilightEvents(this),this.scope=new ScopeEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let s=this;Object.keys(salla).forEach(t=>{"object"==typeof(t=salla[t])&&(s.callSallaInitiate(t),Object.keys(t).forEach(e=>{s.callSallaInitiate(t[e])}))})}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(s,...r){let t=s.split("::")[0],i=salla.api.apis[t],n=!1;if(i&&Object.keys(i.hooksSelectores).forEach(e=>{i.hooksSelectores[e]===s&&(salla.log(`'salla.${t}.${e}(...)' triggered using event '${s}'`),i[e].call(i,...r),n=!0)}),!n){this.emit(s,...r),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:s},...r.values())),this.ingoreLogEvents.includes(s)||!salla.config.get("debug")&&!this.logableEvents.includes(s)||salla.notify.log(s,...r);let t=this;Object.keys(this.globalListners).forEach(function(e){t.globalListners[e](s,...r)}),this.dispatchMobileEvent(s,{...r.values()})}}dispatchEvents(e){if(e&&"object"==typeof e)for(var[t,s]of Object.entries(e))this.dispatch(t,s);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e),console.log("The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e),console.log("The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.hooksSelectores={},this.endpointsMethods={},this.endpointsHeaders={};e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,s=null){let r=this,i=Array.isArray(e),n=i?this.getUrl(...e):this.getUrl(e);e=i?e[0]:e,s=s||this.endpointsMethods[e]||"post";var a,o=this.endpointsHeaders[e];"get"===s&&t instanceof FormData&&(a={},Array.from(t.entries()).forEach(function(e){a[e[0]]=e[1]}),t={params:a}),o&&"get"===s&&(t=t?Object.assign(t,o):o);let l={namespace:this.namespace,action:e,hook:this.hooksSelectores[e]||e,url:n,payload:t,method:s,headers:o};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise(()=>{throw e})}this.webEndpoints.includes(e)||"http"===n.substring(0,4)||(n=salla.config.get("store.api")+n);let c=event?.currentTarget,u=!1;return(u="SALLA-BUTTON"===c?.tagName?!0:u)&&c?.load(),this.parent[s](n,t,{headers:o}).then(e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),r.handleAfterResponseActions(e),e)).catch(e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),r.handleErrorResponse(e),e})}request(e,t,s=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,s)):this.normalRequest(e,t,s)}getUrl(e){let t=this.endpoints[e]||e;var s=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(s,arguments[e]);return t}withInjectData(e,t){return{element:e,data:e.getElementSallaData(t)}}handleAfterResponseActions(response){if(!response)return;let{data,googleTags=null}=response,withGoogleTags=data&&data.googleTags?data.googleTags:googleTags;if(dataLayer&&withGoogleTags&&dataLayer.push(withGoogleTags),this.renderSections(response),response.events||response.error&&response.error.events){let e=response.events||response.error.events;e=JSON.parse(e),Object.keys(e).forEach(function(t){salla.event.dispatch(t,e[t])})}if(this.showAlert(response),response.runJavascript)try{eval(response.runJavascript)}catch(e){salla.log(e)}response.token&&salla.event.auth.tokenFetched(response.token)}renderSections(s){s.sections&&Object.keys(s.sections).forEach(t=>{document.querySelectorAll(t.toSelector()).forEach(function(e){e.innerHTML=s.sections[t]})})}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.message&&e.hasOwnProperty("success")?salla.notify.fire(e.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let s=e.response.data.error.fields,r=[];Object.keys(s).forEach(e=>{let t=s[e];Array.isArray(t)?t.forEach(e=>r.push(e)):r.push(t)});var t=(1<r.length?"* ":"")+r.join("\n* ");salla.error(t,e)}event(){return salla.event[this.className]}getPossibleValue(s,r,e=!1){if(s){if("object"!=typeof s)return s;let t;for(let e=0;e<r.length&&!(t=s[r[e]])&&!(s instanceof FormData&&(t=s.get(r[e])));e++);return"object"!=typeof(t=t||s)||e?t:void 0}}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(s,r=!0){return new Promise((e,t)=>(r?e:t)(s))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!1)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",summary:"cart/{cart}/summary",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",status:"cart/{cart}/status"},this.endpointsMethods={latest:"get",details:"get",summary:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete"},this.webEndpoints=["latest"],this.hooksSelectores={addItem:"cart::add.item",quickAdd:"cart::quick.add",deleteItem:"cart::delete.item",updateItem:"cart::update.item",submit:"cart::submit",deleteImage:"cart::delete.file",reset:"cart::reset"},this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}latest(){return this.request("latest",{params:{source:""}}).then(e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e})}async details(){var e=await this.getCurrentCartId();return this.request(["details",e]).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async summary(){var e=await this.getCurrentCartId();return this.request(["summary",e]).then(function(e){return salla.cart.event.summaryFetched(e),e}).catch(function(e){throw salla.cart.event.summaryNotFetched(e),e})}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemAddedFailed('There is no product "id"!'),!1;var e=this.getPossibleValue(t.formData,["quantity","donating_amount"])?"addItem":"quickAdd",s=await this.getCurrentCartId();return this.request([e,s,t.id],t.formData).then(function(e){return salla.cart.event.itemAdded(e,t.id),e}).catch(function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e})}async deleteItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemDeletedFailed('There is no "id"!'),!1;e=await this.getCurrentCartId();return this.request(["deleteItem",e,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){let t=this.getCartRequestData(e);if(!t.id)return salla.cart.event.itemUpdatedFailed('There is no "id"!'),!1;e=await this.getCurrentCartId();return"object"==typeof t.formData&&("Object"===t.formData.constructor?.name?t.formData._method="PUT":t.formData.append("_method","PUT")),this.request(["updateItem",e,t.id],t.formData).then(function(e){return salla.cart.event.itemUpdated(e,t.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e})}async deleteImage(t){if(!(t=this.getPossibleValue(t,["id","image_id","photo_id"])))return salla.cart.event.imageNotDeleted('There is no "id"!'),!1;var e=await this.getCurrentCartId();return this.request(["deleteImage",e,t]).then(function(e){return salla.cart.event.imageDeleted(e,t),e}).catch(function(e){throw salla.cart.event.imageNotDeleted(e,t),e})}async status(e){return this.request(["status",e||await this.getCurrentCartId()])}async submit({}){var e=await this.getCurrentCartId();this.status(e).then(e=>{if("checkout"===e.data.next_step.to)return window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":"");if("refresh"===e.data.next_step.to)return window.location.reload();if("login"===e.data.next_step.to)return salla.event.dispatch("login::show");throw"Can't find next_step );"}).catch(function(e){throw salla.cart.event.submitFailed(e),e})}getCartRequestData(e){let t=e?.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}handleAfterResponseActions(e){var t;if(403===e.status)throw salla.storage.remove("cart"),t=salla.lang.get("pages.checkout.try_again"),salla.error(t),t;super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}}class GiftApi extends BaseApi{constructor(e){super(e),this.namespace="gift",this.endpoints={buy:"{id}/buy-as-gift"},this.webEndpoints=["buy"],this.hooksSelectores={buy:"gift::buy"},this.after_init()}buy(e){let t=this.getGiftRequestData(e);return t.id?this.request(["buy",t.id],t.formData).then(function(e){return salla.gift.event.buyingSucceeded(e,t.id),e}).catch(function(e){throw salla.gift.event.buyingFailed(e,t.id),e}):(salla.gift.event.buyingFailed('There is no "id"!'),!1)}getGiftRequestData(e){let t=e.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}}class LoyalityApi extends BaseApi{constructor(e){super(e),this.namespace="loyalty",this.endpoints={exchange:"cart/prize/exchange_loyalty_point"},this.webEndpoints=["exchange"],this.hooksSelectores={exchange:"loyalty::exchange"},this.after_init()}exchange(e){let t=e.data||{id:e};return t.id?(t.loyalty_prize_id=t.id,this.request("exchange",t).then(function(e){return salla.loyalty.event.exchangeSucceeded(e,t.id),e}).catch(function(e){throw salla.loyalty.event.exchangeFailed(e,t.id),e})):(salla.loyalty.event.exchangeFailed('There is no "id"!'),!1)}}class AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["login","resend","verify","register","logout","profile/verify-mobile","auth/mobile/verify","auth/email/verify","refresh"],this.endpointsMethods={logout:"get"},this.hooksSelectores={login:"auth::login",resend:"auth::resend",verify:"auth::verify",register:"auth::register",logout:"auth::logout"},this.after_init()}login(t,e){let s;return t.data&&(s=t.element,e=t.data,t=this.getPossibleValue(e,["type"])),e||"object"!=typeof t||(e=t),(t=this.getPossibleValue(t,["type"]))?this.request(["login",t],e).then(function(e){return salla.auth.event.codeSent.call(s,e,t),e}).catch(function(e){throw salla.auth.event.codeNotSent.call(s,e,t),e}):(e="Failed to know what's login type!",salla.auth.event.codeNotSent(e),this.errorPromise(e))}verify(t,e){return t.data&&(e=t.data,t=this.getPossibleValue(e,["type"])),t?(salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request(["verify",t],e).then(function(e){return salla.auth.event.verified(e,t),e}).catch(function(e){throw salla.auth.event.verificationFailed(e,t),e})):(e="Failed to know what's login type!",salla.auth.event.verificationFailed(e),this.errorPromise(e))}resend(t){return(t=t.data||t).phone?t.country_code?(t.resend_by=t.resend_by||"sms",this.request("resend",t).then(function(e){return salla.auth.event.codeReSent(e,t),e}).catch(function(e){throw salla.auth.event.codeNotReSent(e,t),e})):(salla.auth.event.codeNotReSent("Failed to know what's country_code!",t),!1):(salla.auth.event.codeNotReSent("Failed to know what's phone!",t),!1)}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(function(e){return salla.auth.event.registered.call(t,e),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(t,e),e})}logout(){return this.request("logout").then(function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout(()=>location.reload(),100),e}).catch(function(e){throw salla.auth.event.failedLogout(e),e})}refresh(){return this.request("refresh").catch(function(e){throw salla.auth.event.refreshFailed(e),e})}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",reOrder:"reorder/{id}"},this.endpointsMethods={reOrder:"get"},this.hooksSelectores={cancel:"order::cancel",reOrder:"order::re.order",show:"order::show"},this.after_init()}show(e,t=null){salla.event.dispatch("mobile::order.placed",{order_id:e||salla.config.get("page.id")}),location.href=t||location.href.replace("thankyou","order")}cancel(t){return this.request(["cancel",t],{params:{has_apple_pay:!!window.ApplePaySession}}).then(function(e){return salla.event.order.canceled(e,t),e}).catch(function(e){throw salla.event.order.notCanceled(e,t),e})}reOrder(t){return this.request(["reOrder",t]).then(function(e){return salla.storage.set("cart",{id:e.data.cart_id,user_id:salla.config.get("user.id")}),salla.event.order.reOrdered(e,t),window.location.href=e.data.url,e}).catch(function(e){throw salla.event.order.reOrderFailed(e,t),e})}}class OfferApi extends BaseApi{constructor(e){super(e),this.namespace="offer",this.endpoints={popup:"products/special-offer-popup/{product_id}",increase:"products/special-offer-popup/{product_id}/increase",details:"products/{product_id}/specialoffer"},this.webEndpoints=["popup","increase"],this.endpointsMethods={increase:"get"},this.endpointsHeaders={popup:{"s-ajax-view":!0}},this.hooksSelectores={popup:"offer::popup",increase:"offer::increase",details:"offer::details"},this.after_init()}details(e){let t=e.data|e;return(e=this.getPossibleValue(t,["product_id"]))?this.request(["details",e],t).then(function(e){return salla.offer.event.detailsFetched(e,t),e}).catch(function(e){throw salla.offer.event.fetchDetailsFailed(e,t),e}):(salla.offer.event.fetchDetailsFailed('There is no "prodId"!'),!1)}increase(e){let t;return e.data&&(t=e.data,e=this.getPossibleValue(t,["id","product_id"])),e?this.request(["increase",e],t).then(function(e){return salla.offer.event.increased(e,t),e}).catch(function(e){throw salla.offer.event.increaseFailed(e,t),e}):(salla.offer.event.increaseFailed('There is no "prodId"!'),!1)}}class SearchApi extends BaseApi{constructor(e){super(e),this.namespace="search",this.endpoints={search:"products/search"},this.endpointsMethods={search:"get"},this.hooksSelectores={search:"search::products"},this.after_init()}search(t){let e=t.data||{params:{query:t}};var s;return(t=e instanceof FormData?e.get("query"):e.query||e.params.query)?t===this.previousQuery?(s="Query Same As Previous!",salla.search.event.failed(s),this.errorPromise(s)):(this.previousQuery=t,this.request("search",e).then(function(e){return salla.search.event.finished(e,t),e}).catch(function(e){throw salla.search.event.failed(e,t),e})):(s='There is no "query"!',salla.search.event.failed(s),this.errorPromise(s))}}class CouponApi extends BaseApi{constructor(e){super(e),this.namespace="coupon",this.endpoints={add:"cart/{id}/coupon",remove:"cart/{id}/coupon"},this.endpointsMethods={remove:"put"},this.hooksSelectores={add:"coupon::add",remove:"coupon::remove"},this.after_init()}async add(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.coupon.addedFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["add",t],{coupon:e}).then(function(e){return salla.event.coupon.added(e,t),e}).catch(function(e){throw salla.event.coupon.addedFailed(e,t),e})}async remove(){let t=await salla.cart.api.getCurrentCartId();return this.request(["remove",t],{}).then(function(e){return salla.event.coupon.removed(e,t),e}).catch(function(e){throw salla.event.coupon.removedFailed(e,t),e})}}class ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.endpoints={getPrice:"product-price/{id}",availabilitySubscribe:"products/{id}/availability-notify",purchaseNow:"checkout/quick-purchase/{id}"},this.webEndpoints=["getPrice","purchaseNow"],this.hooksSelectores={getPrice:"product::get.price",availabilitySubscribe:"product::availability.subscribe",purchaseNow:"product::purchase.now"},this.after_init()}getPrice(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["getPrice",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.priceUpdated(e,t),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,t),e})}availabilitySubscribe(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["availabilitySubscribe",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.availabilitySubscribed(e,t),e}).catch(function(e){throw salla.product.event.availabilitySubscribedFailed(e,t),e})}purchaseNow(e){if(salla.auth.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,s=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",s],"object"==typeof t?t:void 0).then(function(e){return e}).catch(function(e){throw e});salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",s],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={send:"{type}/{id}/comments"},this.hooksSelectores={send:"comment::send"},this.after_init()}send(e){let t;e?.data&&(t=e.element,e=e.data);let s,{id:r,type:i,comment:n}=Object.fromEntries(e);return r?i&&["products","pages","product","page"].includes(i)?n?(i+=["product","page"].includes(i)?"s":"",this.request(["send",i,r],{comment:n}).then(function(e){return salla.event.comment.added.call(t,e,r),e}).catch(function(e){throw salla.event.comment.additionFailed.call(t,e,r),e})):(salla.event.comment.additionFailed(s="can't find comment content!"),this.errorPromise(s)):(salla.event.comment.additionFailed(s="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(s)):(salla.event.comment.additionFailed(s="Failed to get id!"),this.errorPromise(s))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.hooksSelectores={change:"currency::change"},this.after_init()}change(t){var e;return(t=this.getPossibleValue(t.data||t,["currency","code"]))?this.request("change",{params:{change_currency:"",currency:t}}).then(function(e){return salla.currency.event.changed(e,t),e}).catch(function(e){throw salla.currency.event.failed(e,t),e}):(e="Can't find currency code!",salla.currency.event.failed(e),this.errorPromise(e))}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class FeedbackApi extends BaseApi{constructor(e){super(e),this.namespace="feedback",this.endpoints={store:"rating/store",product:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.hooksSelectores={store:"feedback::store",product:"feedback::product",shipping:"feedback::shipping",order:"feedback::order"},this.endpointsMethods={order:"get"},this.after_init()}order(t){var e="object"==typeof t?t:{};return(t=this.getPossibleValue(t,["order_id","id"]))?this.request(["order",t],e).then(function(e){return salla.event.feedback.orderFetched(e,t),e}).catch(function(e){throw salla.event.feedback.orderNotFetched(e,t),e}):(e='There is no "order_id"!',salla.event.feedback.orderNotFetched(e),this.errorPromise(e))}store(t){var e;return(t=t.data||t)?this.request("store",t).then(function(e){return salla.event.feedback.storeRated(e,t),e}).catch(function(e){throw salla.event.feedback.storeFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.storeFailed(e),this.errorPromise(e))}products(){return this.product(...arguments)}product(t){var e;return(t=t.data||t)?this.request("product",t).then(function(e){return salla.event.feedback.productRated(e,t),e}).catch(function(e){throw salla.event.feedback.productFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.productFailed(e),this.errorPromise(e))}shipping(t){var e;return(t=t.data||t)?this.request("shipping",t).then(function(e){return salla.event.feedback.shippingRated(e,t),e}).catch(function(e){throw salla.event.feedback.shippingFailed(e,t),e}):(e='There is no "data"!',salla.event.feedback.shippingFailed(e),this.errorPromise(e))}}class SallaInit{constructor(e){salla.config.merge(e),this.connectHooksWithElements(),this.initiated=!0,e&&(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),salla.lang.loadStoreTranslations()),salla.twilight.event.initiated(e)}injectMaintenanceAlert(){var e;salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.log("store-notify Existed before!"):((e=document.createElement("div")).classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.log("s-theme_preview_bar Existed before!"):salla.lang.onLoaded(()=>{let e=document.createElement("div");e.id="s-theme_preview_bar",e.style={display:"flex",justifyContent:"space-between",textAlign:"center",backgroundColor:"#232323",color:"#fff",padding:"10px",fontSize:"0.875rem",lineHeight:"1.25rem",position:"relative"},e.innerHTML=`
|
|
2
|
+
<div style="display:flex; align-items:center;">
|
|
3
|
+
<img width="32" src="https://assets.salla.sa/cp/assets/images/logo-new.png">
|
|
4
|
+
<span style="margin:0 10px;">${salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${salla.config.get("theme.name")}</span></span>
|
|
5
|
+
</div>
|
|
6
|
+
<a href="${salla.url("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>
|
|
7
|
+
`,document.body.prepend(e)}))}injectEditAlert(){let t=salla.config.get("edit");t&&(document.querySelector("#s-edit-alert")?salla.log("s-edit-alert Existed before!"):salla.lang.onLoaded(()=>{let e=document.createElement("div");e.id="s-edit-alert",e.innerHTML=`
|
|
8
|
+
<a href="${t}" style="display:block; background-color:${salla.config.get("theme.color.primary","#5cd5c4")}; color:${salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">
|
|
9
|
+
<i class="sicon-edit"></i>
|
|
10
|
+
${salla.lang.get("pages.products.quick_edit")}
|
|
11
|
+
</a>
|
|
12
|
+
`,document.body.prepend(e)}))}connectHooksWithElements(e){}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.log("trying to call ajax from non Element!!"),!1;e.preventDefault();let s=t.getAjaxFormData(e),r=s.method?s.method.toLowerCase():void 0;salla.api.document.request(s.url,s.formData,r).then(e=>(e.data&&e.request&&(e=e.data),salla.api.document.handleAfterResponseActions(e),this.callAjaxEvent(s.events.success,e,s.formData),e)).catch(e=>{throw salla.api.document.handleErrorResponse(e),this.callAjaxEvent(s.events.fail,e,s.formData),e})}callAjaxEvent(e,t,s){var r;e&&(s instanceof FormData&&(r={},Array.from(s.entries()).forEach(function(e){r[e[0]]=e[1]}),s=r),window[e]?window[e](t,s):salla.event.dispatch(e,t,s))}}class TwilightApi extends BaseApi{constructor(e){super(e),this.namespace="twilight",this.hooksSelectores={init:"twilight::init",api:"twilight::api"},this.after_init()}init(e){var t=e?.events;this.initiated||(delete e.events,new SallaInit(e)),t&&salla.event.dispatchEvents(t)}api(e){e=e?.events;e&&salla.event.dispatchEvents(e)}}class WishlistApi extends BaseApi{constructor(e){super(e),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.hooksSelectores={add:"wishlist::add",remove:"wishlist::remove"},this.after_init()}updateWishlistStorage(e,t=!0){let s=salla.storage.get("salla::wishlist",[]);t?s.push(e):s.splice(s.indexOf(e),1),salla.storage.set("salla::wishlist",s)}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(t){let e,s;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(e=salla.lang.get("common.messages.must_login")),salla.error(e),this.errorPromise(e)):(t.data&&(s=t.element,t=this.getPossibleValue(t.data,["id","prod_id"])),t?this.request(["add",t]).then(e=>(this.updateWishlistStorage(t),salla.wishlist.event.added.call(s,e,t),e)).catch(function(e){throw salla.wishlist.event.additionFailed.call(s,e,t),e}):(salla.wishlist.event.additionFailed(e="Failed to get product id!"),this.errorPromise(e)))}remove(t){let s;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(error=salla.lang.get("common.messages.must_login")),salla.error(error),this.errorPromise(error)):(t?.data&&(s=t.element,t=this.getPossibleValue(t.data,["id","prod_id"])),t?this.request(["remove",t]).then(e=>(this.updateWishlistStorage(t,!1),salla.wishlist.event.removed.call(s,e,t),e)).catch(function(e){throw salla.wishlist.event.removingFailed.call(s,e,t),e}):(salla.wishlist.event.removingFailed("Failed to get id!"),!1))}}class ScopeApi extends BaseApi{constructor(e){super(e),this.namespace="scope",this.endpoints={getAll:"/scopes",submit:"/scope"},this.webEndpoints=["getAll","submit"],this.endpointsMethods={getAll:"get"},this.after_init()}getAll(){return this.request("getAll",{from:"header"}).then(function(e){return console.log(e),e}).catch(function(e){throw e})}submit(e){return this.request("submit",e).then(function(e){return console.log(e),e}).catch(function(e){throw e})}}function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var s=String(t).replace(/=+$/,"");if(s.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i,n=0,a=0,o="";i=s.charAt(a++);~i&&(r=n%4?64*r+i:i,n++%4)&&(o+=String.fromCharCode(255&r>>(-2*n&6))))i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return decodeURIComponent(r(t).replace(/(.)/g,function(e,t){t=t.charCodeAt(0).toString(16).toUpperCase();return"%"+(t=t.length<2?"0"+t:t)}))}catch(e){return r(t)}}function n(e){this.message=e}function o(e,s){if("string"!=typeof e)throw new n("Invalid token specified");s=!0===(s=s||{}).header?0:1;try{return JSON.parse(t(e.split(".")[s]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const axios=require("axios");class sallaRequest{constructor(e){return e.on("twilight::initiated",()=>this.initiateRequest()),e.on("auth::token.fetched",e=>this.handleToken(e)),axios.create({baseURL:window.baseUrl,headers:{common:{"X-Requested-With":"XMLHttpRequest"},"S-SOURCE":"twilight"}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.url",window.baseUrl),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.api.defaults.headers.common["accept-language"]=salla.config.get("user.language_code","ar"),this.injectTokenToTheRequests()}injectTokenToTheRequests(){var e=salla.storage.get("token"),t=salla.config.isGuest(),s=salla.storage.get("cart");if(s&&s.user_id!==salla.config.get("user.id"))return salla.log("Auth:: The cart is not belong to current user!"),void salla.cart.api.reset();if(!t||e){if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();s=o(e);return Date.now()/1e3>s.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):s.sub!==salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}}class SallaApi extends sallaRequest{constructor(e){super(e),this.apis={auth:new AuthApi(this),cart:new CartApi(this),gift:new GiftApi(this),loyalty:new LoyalityApi(this),order:new OrderApi(this),offer:new OfferApi(this),search:new SearchApi(this),coupon:new CouponApi(this),product:new ProductApi(this),comment:new CommentApi(this),currency:new CurrencyApi(this),document:new DocumentApi(this),feedback:new FeedbackApi(this),twilight:new TwilightApi(this),wishlist:new WishlistApi(this),scope:new ScopeApi(this)},this.hooksPrefix="data-on-",this.hooksSelectores=[],Object.assign(this,this.apis)}}class BaseAlias{constructor(s,r){return this.api=s,this.event=r,new Proxy(this,{get:function(e,t){return"event"==t?r:"api"==t?s:s&&s[t]||e[t]}})}}class Cart extends BaseAlias{}class Auth extends BaseAlias{isUser(){try{return!1===window.dataLayer[0].customer.isGuest}catch(e){return salla.log("Error::isUser",e),!1}}isGuest(){return!this.isGuest()}}class Order extends BaseAlias{}class Gift extends BaseAlias{}class Loyalty extends BaseAlias{}class Offer extends BaseAlias{}class Search extends BaseAlias{}class Coupon extends BaseAlias{}class Comment extends BaseAlias{}class Product extends BaseAlias{}class Currency extends BaseAlias{}class Document extends BaseAlias{}class Feedback extends BaseAlias{}class Twilight extends BaseAlias{}class Wishlist extends BaseAlias{}class Scope extends BaseAlias{}var js={exports:{}},core={exports:{}},evEmitter={exports:{}},utils=(!function(e){var t,s;t="undefined"!=typeof window?window:commonjsGlobal,s=function(){function e(){}let t=e.prototype;return t.on=function(e,t){if(!e||!t)return this;let s=this._events=this._events||{},r=s[e]=s[e]||[];return r.includes(t)||r.push(t),this},t.once=function(e,t){if(!e||!t)return this;this.on(e,t);let s=this._onceEvents=this._onceEvents||{};return(s[e]=s[e]||{})[t]=!0,this},t.off=function(e,t){let s=this._events&&this._events[e];if(!s||!s.length)return this;e=s.indexOf(t);return-1!=e&&s.splice(e,1),this},t.emitEvent=function(e,t){let s=this._events&&this._events[e];if(!s||!s.length)return this;s=s.slice(0),t=t||[];let r=this._onceEvents&&this._onceEvents[e];for(var i of s)r&&r[i]&&(this.off(e,i),delete r[i]),i.apply(this,t);return this},t.allOff=function(){return delete this._events,delete this._onceEvents,this},e},e.exports?e.exports=s():t.EvEmitter=s()}(evEmitter),{exports:{}}),pageLoad=(!function(e){var t,s;t=commonjsGlobal,s=function(t){let r={extend:function(e,t){return Object.assign(e,t)},modulo:function(e,t){return(e%t+t)%t},makeArray:function(e){return Array.isArray(e)?e:null==e?[]:"object"==typeof e&&"number"==typeof e.length?[...e]:[e]},removeFrom:function(e,t){t=e.indexOf(t);-1!=t&&e.splice(t,1)},getParent:function(e,t){for(;e.parentNode&&e!=document.body;)if((e=e.parentNode).matches(t))return e},getQueryElement:function(e){return"string"==typeof e?document.querySelector(e):e},handleEvent:function(e){var t="on"+e.type;this[t]&&this[t](e)},filterFindElements:function(e,s){return(e=r.makeArray(e)).filter(e=>e instanceof HTMLElement).reduce((e,t)=>{if(!s)return e.push(t),e;t.matches(s)&&e.push(t);t=t.querySelectorAll(s);return e.concat(...t)},[])},debounceMethod:function(e,t,s){s=s||100;let r=e.prototype[t],i=t+"Timeout";e.prototype[t]=function(){clearTimeout(this[i]);let e=arguments;this[i]=setTimeout(()=>{r.apply(this,e),delete this[i]},s)}},docReady:function(e){var t=document.readyState;"complete"==t||"interactive"==t?setTimeout(e):document.addEventListener("DOMContentLoaded",e)},toDashed:function(e){return e.replace(/(.)([A-Z])/g,function(e,t,s){return t+"-"+s}).toLowerCase()}},l=t.console;return r.htmlInit=function(a,o){r.docReady(function(){let i="data-"+r.toDashed(o),e=document.querySelectorAll(`[${i}]`),n=t.jQuery;[...e].forEach(e=>{let t,s=e.getAttribute(i);try{t=s&&JSON.parse(s)}catch(t){return void(l&&l.error(`Error parsing ${i} on ${e.className}: `+t))}var r=new a(e,t);n&&n.data(e,o,r)})})},r},e.exports?e.exports=s(t):t.fizzyUIUtils=s(t)}(utils),function(e){var t,s;t=window,s=function(t,e,r){let i=t.jQuery,n={};function a(t,s){var e=r.getQueryElement(t);if(e){if((t=e).infiniteScrollGUID){let e=n[t.infiniteScrollGUID];return e.option(s),e}this.element=t,this.options={...a.defaults},this.option(s),i&&(this.$element=i(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(e||t))}a.defaults={},a.create={},a.destroy={};let s=a.prototype,o=(Object.assign(s,e.prototype),0),l=(s.create=function(){var e=this.guid=++o;if(this.element.infiniteScrollGUID=e,(n[e]=this).pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath())for(var t in this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit(),a.create)a.create[t].call(this);else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(s,r,e){this.log(s,e);var t=r?[r].concat(e):e;if(this.emitEvent(s,t),i&&this.$element){let t=s+=".infiniteScroll";if(r){let e=i.Event(r);e.type=s,t=e}this.$element.trigger(t,e)}},{initialized:e=>"on "+e,request:e=>"URL: "+e,load:(e,t)=>`${e.title||""}. URL: `+t,error:(e,t)=>e+". URL: "+t,append:(e,t,s)=>s.length+" items. URL: "+t,last:(e,t)=>"URL: "+t,history:(e,t)=>"URL: "+t,pageIndex:function(e,t){return`current page determined to be: ${e} from `+t}}),c=(s.log=function(s,r){if(this.options.debug){let e="[InfiniteScroll] "+s,t=l[s];t&&(e+=". "+t.apply(this,r)),console.log(e)}},s.updateMeasurements=function(){this.windowHeight=t.innerHeight;var e=this.element.getBoundingClientRect();this.top=e.top+t.scrollY},s.updateScroller=function(){var e=this.options.elementScroll;if(e){if(this.scroller=!0===e?this.element:r.getQueryElement(e),!this.scroller)throw new Error("Unable to find elementScroll: "+e)}else this.scroller=t},s.updateGetPath=function(){let e=this.options.path;var t;e?"function"!=(t=typeof e)?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e:console.error("InfiniteScroll path option required. Set as: "+e)},s.updateGetPathTemplate=function(t){this.getPath=()=>{var e=this.pageIndex+1;return t.replace("{{#}}",e)};var e=t.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),e=new RegExp(e),e=location.href.match(e);e&&(this.pageIndex=parseInt(e[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))},[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/]),u=a.getPathParts=function(e){if(e)for(var t of c){var s,r,t=e.match(t);if(t)return[,t,s,r]=t,{begin:t,index:s,end:r}}},h=(s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(t){var s=t.getAttribute("href"),r=u(s);if(r){let{begin:e,index:t,end:s}=r;this.isPathSelector=!0,this.getPath=()=>e+(this.pageIndex+1)+s,this.pageIndex=parseInt(t,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])}else console.error("InfiniteScroll unable to parse next link href: "+s)}else console.error("Bad InfiniteScroll path option. Next link not found: "+e)},s.updateGetAbsolutePath=function(){let i=this.getPath();if(i.match(/^http/)||i.match(/^\//))this.getAbsolutePath=this.getPath;else{let e=location["pathname"],t=i.match(/^\?/),s=e.substring(0,e.lastIndexOf("/")),r=t?e:s+"/";this.getAbsolutePath=()=>r+this.getPath()}},a.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},a.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){for(var e in this.allOff(),a.destroy)a.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],i&&this.$element&&i.removeData(this.element,"infiniteScroll")},a.throttle=function(r,i){let n,a;return i=i||200,function(){let e=+new Date,t=arguments,s=()=>{n=e,r.apply(this,t)};n&&e<n+i?(clearTimeout(a),a=setTimeout(s,i)):s()}},a.data=function(e){e=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return e&&n[e]},a.setJQuery=function(e){i=e},r.htmlInit(a,"infinite-scroll"),s._init=function(){},t)["jQueryBridget"];return i&&h&&h("infiniteScroll",a,i),a},e.exports?e.exports=s(t,evEmitter.exports,utils.exports):t.InfiniteScroll=s(t,t.EvEmitter,t.fizzyUIUtils)}(core),{exports:{}}),scrollWatch=(!function(e){var t,s;t=window,s=function(t,i){let e=i.prototype,n=(Object.assign(i.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),i.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},e.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()},new DOMParser);function u(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return e.loadNextPage=function(){if(!this.isLoading&&this.canLoad){let{responseBody:s,domParseResponse:r,fetchOptions:e}=this.options,i=this.getAbsolutePath();this.isLoading=!0,"function"==typeof e&&(e=e());var t=fetch(i,e).then(t=>{var e;return t.ok?t[s]().then(e=>("text"==s&&r&&(e=n.parseFromString(e,"text/html")),204==t.status?(this.lastPageReached(e,i),{body:e,response:t}):this.onPageLoad(e,i,t))):(e=new Error(t.statusText),this.onPageError(e,i,t),{response:t})}).catch(e=>{this.onPageError(e,i)});return this.dispatchEvent("request",null,[i,t]),t}},e.onPageLoad=function(e,t,s){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,s]),this.appendNextPage(e,t,s)},e.appendNextPage=function(e,t,s){var{append:r,responseBody:i,domParseResponse:n}=this.options;if("text"!=i||!n||!r)return{body:e,response:s};let a=e.querySelectorAll(r),o={body:e,response:s,items:a};if(!a||!a.length)return this.lastPageReached(e,t),o;let l=u(a),c=()=>(this.appendItems(a,l),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,a,s]),o);return this.options.outlayer?this.appendOutlayerItems(l,c):c()},e.appendItems=function(e,t){if(e&&e.length){var s;for(s of(t=t||u(e)).querySelectorAll("script")){let e=document.createElement("script"),t=s.attributes;for(var r of t)e.setAttribute(r.name,r.value);e.innerHTML=s.innerHTML,s.parentNode.replaceChild(e,s)}this.element.appendChild(t)}},e.appendOutlayerItems=function(e,s){let r=i.imagesLoaded||t.imagesLoaded;return r?new Promise(function(t){r(e,function(){var e=s();t(e)})}):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},e.onAppendOutlayer=function(e,t,s){this.options.outlayer.appended(s)},e.checkLastPage=function(e,t){let s,{checkLastPage:r,path:i}=this.options;r&&("function"!=typeof i||this.getPath()?("string"==typeof r?s=r:this.isPathSelector&&(s=i),s&&e.querySelector&&(e.querySelector(s)||this.lastPageReached(e,t))):this.lastPageReached(e,t))},e.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},e.onPageError=function(e,t,s){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,s]),e},i.create.prefill=function(){var e;this.options.prefill&&((e=this.options.append)?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error("append option required for prefill. Set as :"+e))},e.prefill=function(){var e=this.getPrefillDistance();this.isPrefilling=0<=e,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},e.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},e.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},i},e.exports?e.exports=s(t,core.exports):s(t,t.InfiniteScroll)}(pageLoad),{exports:{}}),history$1=(!function(e){var t,s;t=window,s=function(s,e,t){let r=e.prototype;return Object.assign(e.defaults,{scrollThreshold:400}),e.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);var e=this.options.scrollThreshold;!e&&0!==e||this.enableScrollWatch()},e.destroy.scrollWatch=function(){this.disableScrollWatch()},r.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},r.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},r.bindScrollWatchEvents=function(e){e=e?"addEventListener":"removeEventListener";this.scroller[e]("scroll",this.pageScrollHandler),s[e]("resize",this.resizeHandler)},r.onPageScroll=e.throttle(function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")}),r.getBottomDistance=function(){let e,t;return t=this.options.elementScroll?(e=this.scroller.scrollHeight,this.scroller.scrollTop+this.scroller.clientHeight):(e=this.top+this.element.clientHeight,s.scrollY+this.windowHeight),e-t},r.onResize=function(){this.updateMeasurements()},t.debounceMethod(e,"onResize",150),e},e.exports?e.exports=s(t,core.exports,utils.exports):s(t,t.InfiniteScroll,t.fizzyUIUtils)}(scrollWatch),{exports:{}}),button=(!function(e){var t,s;t=window,s=function(r,e,t){let s=e.prototype,i=(Object.assign(e.defaults,{history:"replace"}),document.createElement("a"));return e.create.history=function(){this.options.history&&(i.href=this.getAbsolutePath(),(i.origin||i.protocol+"//"+i.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${i.origin} on ${location.origin} . History behavior disabled.`))},s.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},s.bindHistoryAppendEvents=function(e){e=e?"addEventListener":"removeEventListener";this.scroller[e]("scroll",this.scrollHistoryHandler),r[e]("unload",this.unloadHandler)},s.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},e.destroy.history=s.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},s.onAppendHistory=function(e,t,s){s&&s.length&&(s=s[0],s=this.getElementScrollY(s),i.href=t,this.scrollPages.push({top:s,path:i.href,title:e.title}))},s.getElementScrollY=function(e){return this.options.elementScroll?e.offsetTop-this.top:e.getBoundingClientRect().top+r.scrollY},s.onScrollHistory=function(){var e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},t.debounceMethod(e,"onScrollHistory",150),s.getClosestScrollPage=function(){let e,t;e=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:r.scrollY+this.windowHeight/2;for(var s of this.scrollPages){if(s.top>=e)break;t=s}return t},s.setHistory=function(e,t){var s=this.options.history;s&&history[s+"State"]&&(history[s+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},s.onUnload=function(){var e;0!==this.scrollPage.top&&(e=r.scrollY-this.scrollPage.top+this.top,this.destroyHistory(),scrollTo(0,e))},s.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},e},e.exports?e.exports=s(t,core.exports,utils.exports):s(t,t.InfiniteScroll,t.fizzyUIUtils)}(history$1),{exports:{}}),status=(!function(e){var t,s;t=window,s=function(e,t,s){class r{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){var e=s.getQueryElement(this.options.button);e&&(this.button=new r(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=r,t},e.exports?e.exports=s(0,core.exports,utils.exports):s(0,t.InfiniteScroll,t.fizzyUIUtils)}(button),{exports:{}}),TheInfinitScroll=(!function(e){var t,s;t=window,s=function(e,t,s){let r=t.prototype;function i(e){a(e,"none")}function n(e){a(e,"block")}function a(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=s.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},r.bindHideStatus=function(e){var t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},r.showRequestStatus=function(){this.showStatus("request")},r.showErrorStatus=function(){this.showStatus("error")},r.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},r.showStatus=function(e){n(this.statusElement),this.hideStatusEventElements(),n(this.statusEventElements[e])},r.hideAllStatus=function(){i(this.statusElement),this.hideStatusEventElements()},r.hideStatusEventElements=function(){for(var e in this.statusEventElements)i(this.statusEventElements[e])},t},e.exports?e.exports=s(0,core.exports,utils.exports):s(0,t.InfiniteScroll,t.fizzyUIUtils)}(status),function(e){window,e.exports&&(e.exports=(e=core.exports,pageLoad.exports,scrollWatch.exports,history$1.exports,button.exports,status.exports,e))}(js),js.exports);class InfiniteScroll extends BaseAlias{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},this.instances=[]}initiate(e,t,s){s=this.getCustomOptions(t,s);t="string"!=typeof e?e:document.querySelector(e),e=s.path;if(t&&e&&("string"!=typeof e||document.querySelector(e))){let e=new TheInfinitScroll(t,s);return e.on("scrollThreshold",salla.infiniteScroll.event.scrollThreshold),e.on("request",salla.infiniteScroll.event.request),e.on("load",salla.infiniteScroll.event.load),e.on("append",salla.infiniteScroll.event.append),e.on("error",salla.infiniteScroll.event.error),e.on("last",salla.infiniteScroll.event.last),e.on("history",salla.infiniteScroll.event.history),this.instances.push(e),e}salla.log(t?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!")}getCustomOptions(e,t){return(t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}function injectValueToFromData(e,t,s){return e instanceof FormData?e.append(t,s):e[t]=s,e}function number(t,e=!1){t+="";var s,r=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],n=(e=e||!salla.config.get("store.settings.arabic_numbers_enabled"))?r:i,a=e?i:r;for(let e=0;e<n.length;e++)s=new RegExp(n[e],"g"),t=t.replace(s,a[e]);return t}function digitsOnly(e){return number(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")}function inputDigitsOnly(t,s=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach(e=>inputDigitsOnly(e,s));if(t){let e=salla.helpers.digitsOnly(t.value);return t.min&&e<t.min?t.value=t.min:t.max&&e>t.max?t.value=t.max:1<=t.maxLength&&e.toString().length>t.maxLength?t.value=e.toString().substring(0,t.maxLength):t.value=s||t.dataset.hasOwnProperty("digitsWithDecimal")?getOnlyDecimal(e):e.replace(/\D/g,"")}salla.log("Can't find Object With Id: "+t)}function getOnlyDecimal(e){var t=(e.match(/\./g)||[]).length;return t&&1!==t?getOnlyDecimal(e.replace(/\.(.+)\./g,".$1")):e}function money(e){return number(e?.amount|e)+" "+salla.config.currency(e?.currency).symbol}function debounce(s,t){t=t||100;let r,i=[];return function(...e){return clearTimeout(r),r=setTimeout(()=>{let t=s(...e);i.forEach(e=>e(t)),i=[]},t),new Promise(e=>i.push(e))}}function getInputDataWithName(t,s,r={}){if(t.includes("[")){let e=t.split("]").join("").split("[");return{name:e[0],value:getLeveledData(e.slice(1),s,r[e[0]])}}return{name:t,value:s}}function getLeveledData(e,t,s){var r=e[0];return s&&0==e.length?Array.isArray(s)?(s.push(t),s):[s,t]:Array.isArray(s)?(s.push(t),s):"string"==typeof s?[s,t]:s?(s[r]=getLeveledData(e.slice(1),t,s[r]),s):r?{[r]:getLeveledData(e.slice(1),t)}:""===r?[t]:t}function setNested(e,t,s){let r=e,i=t.split("."),n=i.length;for(let e=0;e<n-1;e++){var a=i[e];r[a]||(r[a]={}),r=r[a]}return r[i[n-1]]=s,e}function getNested(e,t,s){var r;for(r of t.split("."))if(!(e=e.hasOwnProperty(r)?e[r]:s||void 0))return e;return e}function url(e){return salla.config.get("store.url","/")+e}function addParamToUrl(e,t){if(!t||!e)return window.location.href;let s=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),r=window.location.href.replace(s,"$1").replace(/&$|\?$/,"");return(r+=(r.includes("?")?"&":"?")+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")})},String.prototype.toDatasetName=function(){return(this.startsWith("data-")?this.substr(5):this).toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var s,r=this,i=0;i<e.length;i++)s=new RegExp(e[i],"g"),r=r.replace(s,t[i]);return r},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement}}),Element.prototype.getElementSallaData=function(r,...i){if(this.getAttribute){if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(r){}var n=this.getAttribute("data-function");if(n&&window[n])return"function"==typeof window[n]?this.getFilteredData(window[n].call(this,...i)):this.getFilteredData(window[n]);let e=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if((e="FORM"!==this.tagName&&(e||this.closest("form")||this.closest("[salla-form-data]"))||this)&&"FORM"===e.tagName)return this.getFilteredData(new FormData(e),null,e);let t=e.querySelectorAll("[name]");if(!t.length)return this.getFilteredData();let s=Object.assign({},this.dataset);return t.forEach(t=>{if(!["checkbox","radio"].includes(t.type)||t.checked)try{var e=salla.helpers.inputData(t.name,t.value,s);s[e.name]=e.value}catch(e){salla.log(t.name+" can't be send")}}),this.getFilteredData(s)}},Element.prototype.canEventFireHook=function(e){return!!this.hasAttribute&&this.hasAttribute(salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(t,s){t=t.toLowerCase();for(var r=0;r<this.attributes.length;r++){let e=this.attributes[r].name.toLowerCase();if(0===e.indexOf(t))return!s||e}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]'),s=(t.forEach(e=>{e.files.length||e.setAttribute("disabled","")}),new FormData(this));return t.forEach(e=>{e.files.length||e.removeAttribute("disabled")}),{formData:this.getFilteredData(s,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(s=null,r=null,i=null){return s=s||i?.dataset||this.dataset,i&&this.name&&void 0!==this.value&&(s=injectValueToFromData(s,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach(e=>{e=i?.dataset[e]||this.dataset[e];if(e){var t=window[e];if("function"==typeof t){if(!t(s,i||this,r)&&s)throw`Data failed to be pass verify function window.${e}(formData, element, event)!`;return t(s,i||this,r)}salla.log("window."+e+"() not found!")}}),s},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return{formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},window.onbeforeunload=function(e){if(salla.document.event.leaving(e),!salla.config.get("canLeave"))return e.preventDefault(),!1};var Helpers={digitsOnly:digitsOnly,inputDigitsOnly:inputDigitsOnly,number:number,money:money,setNested:setNested,getNested:getNested,inputData:getInputDataWithName,url:url,addParamToUrl:addParamToUrl,debounce:debounce};class AppHelpers{toggleClassIf(e,t,s,r){return document.querySelectorAll(e).forEach(e=>this.toggleElementClassIf(e,t,s,r)),this}toggleElementClassIf(e,t,s,r){t=Array.isArray(t)?t:t.split(" "),s=Array.isArray(s)?s:s.split(" ");r=r(e);return e?.classList.remove(...r?s:t),e?.classList.add(...r?t:s),this}isValidEmail(e){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return"object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach(e=>this.watchElement(e[0],e[1])),this}on(t,e,s,r={}){return"object"==typeof e?this.element(e).addEventListener(t,s,r):document.querySelectorAll(e).forEach(e=>e.addEventListener(t,s,r)),this}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,e=>13===e.keyCode&&t(e)),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e){return this.debounce_||(this.debounce_=salla.helpers.debounce((e,...t)=>e(...t),500)),this.debounce_(e,...Array.from(arguments).slice(1))}}class Form{async submit(e,t=null){t=t||event;let s,r=!1;if("SubmitEvent"===t?.constructor?.name){if(salla.log("Event Object",event),t.preventDefault(),!t.target||"FORM"!==t.target.tagName)return console.error("Failed find the target element for submit action. make sure you submit a form element"),new Promise(()=>{throw"Failed find the target element for submit action. make sure you submit a form element"});(r=t?.submitter&&t.submitter?.parentElement&&"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName?!0:r)&&t?.submitter?.parentElement.load(),s=t.target.getElementSallaData(),salla.log("Data from element",s)}else s=t;if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.twilight.request(e,s,"post").finally(()=>{r&&t?.submitter?.parentElement.stop()});let i=e.split("."),n=i.splice(-1);return salla.call(i.join("."))[n](s).finally(()=>{r&&t?.submitter?.parentElement.stop()}).catch(e=>{throw salla.log(e),e})}}class SallaCookie{constructor(e){e.on("cookies::remove",e=>this.remove(e)),e.on("cookies::add",(e,t)=>this.set(e,t))}get(t){return document.cookie.split("; ").find(e=>e.startsWith(t+"="))?.split("=")[1]}set(e,t="",s=10){let r="";if(s){let e=new Date;e.setTime(e.getTime()+24*s*60*60*1e3),r="; expires="+e.toUTCString()}return document.cookie=`${e}=${t}${r}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=e+"=; Max-Age=0; path=/;",this}}class SallaConfig{constructor(e){this.triedToGetCurrencies_=!1,this.languages_=[],this.triedToGetLanguages_=!1,this.currencies_=[],this.properties_=e||{debug:"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}}}merge(e){return Object.assign(this.properties_,e),this}set(e,t){return e.includes(".")?salla.helpers.setNested(this.properties_,e,t):this.properties_[e]=t,this}get(e,t=null){return e.includes(".")?salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]:t||void 0}isUser(){return"user"===this.get("user.type")}isGuest(){return!this.isUser()}async languages(e=!0){if(this.languages_.length||this.triedToGetLanguages_)return this.languages_;if(this.languages_=Object.values(this.get("languages",{})),!e||this.languages_.length)return this.languages_;this.triedToGetLanguages_=!0;let t=await salla.document.api.request("languages",null,"get"),s=salla.url("");return this.languages_=t&&t.data?t.data.map(e=>(e.code=e.code||e.iso_code,e.url=s+e.code,e.is_rtl=e.is_rtl||e.rtl,e)):[]}async currencies(){if(this.triedToGetCurrencies_)return this.currencies_;this.triedToGetCurrencies_=!0;let e=await salla.currency.api.list();return this.currencies_=e&&e.data?e.data.map(e=>(e.country_code=e.code.substr(0,2).toLowerCase(),e)):[]}currency(e){return this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}}var lang={exports:{}},Lang=(lang.exports=function(){function l(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}function e(e){this.locale=(e=e||{}).locale||function(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}()||t,this.fallback=e.fallback,this.messages=e.messages}var c=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,u=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,t="en";return e.prototype.setMessages=function(e){this.messages=e},e.prototype.getLocale=function(){return this.locale||this.fallback},e.prototype.setLocale=function(e){this.locale=e},e.prototype.getFallback=function(){return this.fallback},e.prototype.setFallback=function(e){this.fallback=e},e.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},e.prototype.get=function(e,t,s){if(!this.has(e,s))return e;s=this._getMessage(e,s);return null===s?e:s=t?this._applyReplacements(s,t):s},e.prototype.trans=function(e,t){return this.get(e,t)},e.prototype.choice=function(e,t,s,r){(s=void 0!==s?s:{}).count=t;s=this.get(e,s,r);if(null==s)return s;for(var i,n=s.split("|"),a=[],o=0;o<n.length;o++)n[o]=n[o].trim(),u.test(n[o])&&(i=n[o].split(/\s/),a.push(i.shift()),n[o]=i.join(" "));if(1===n.length)return s;for(var l=0;l<a.length;l++)if(this._testInterval(t,a[l]))return n[l];return r=r||this._getLocale(e),n[this._getPluralForm(t,r)]},e.prototype.transChoice=function(e,t,s){return this.choice(e,t,s)},e.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var e=e.split("."),s=e[0].replace(/\//g,".");return{source:t+"."+s,sourceFallback:this.getFallback()+"."+s,entries:e.slice(1)}},e.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var s=this.messages[e.source],r=e.entries.slice(),i=r.join(".");if("string"!=typeof(s=void 0!==s?this._getValueInKey(s,i):void 0)&&this.messages[e.sourceFallback])for(s=this.messages[e.sourceFallback],r=e.entries.slice(),i="";r.length&&void 0!==s;)s[i=i?i.concat(".",r.shift()):r.shift()]&&(s=s[i],i="");return"string"!=typeof s?null:s},e.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var s=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),r=0,i=s.length;r<i;++r){var n=s.slice(0,r+1).join("."),a=s.slice(r+1,s.length).join(".");if(e[n])return this._getValueInKey(e[n],a)}return e},e.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},e.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var s=e.join(".");if(t[s]){t=t[s];break}t=t[e.shift()]}return t},e.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},e.prototype._applyReplacements=function(e,r){return Object.keys(r).sort(this._sortReplacementKeys).forEach(function(s){e=e.replace(new RegExp(":"+s,"gi"),function(e){var t=r[s];return e===e.toUpperCase()?t.toUpperCase():e===e.replace(/\w/i,function(e){return e.toUpperCase()})?t.charAt(0).toUpperCase()+t.slice(1):t})}),e},e.prototype._testInterval=function(e,t){if("string"!=typeof t)throw"Invalid interval: should be a string.";var s,r,i,n=(t=t.trim()).match(c);if(!n)throw"Invalid interval: "+t;if(!n[2])return t=(n=n.filter(function(e){return!!e}))[1],(s=l(n[2]))===1/0&&(s=-1/0),r=l(n[3]),i=n[4],("["===t?s<=e:s<e)&&("]"===i?e<=r:e<r);for(var a=n[2].split(","),o=0;o<a.length;o++)if(parseInt(a[o],10)===e)return!0;return!1},e.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:2<=e%10&&e%10<=4&&(e%100<10||20<=e%100)?1:2;case"cs":case"sk":return 1==e?0:2<=e&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:2<=e%10&&(e%100<10||20<=e%100)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||1<e%100&&e%100<11?1:10<e%100&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:2<=e%10&&e%10<=4&&(e%100<12||14<e%100)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||0<e%100&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:3<=e%100&&e%100<=10?3:11<=e%100&&e%100<=99?4:5}},e}(),lang.exports);class SallaLang extends Lang{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||window.locale||"en",e.fallback=e.fallback||"en",super(e),this.translationsLoaded=!1}onLoaded(e){this.translationsLoaded?e():salla.event.on("languages::translations.loaded",e)}loadStoreTranslations(){var e=salla.config.get("store.url")?.rtrim("/");if(!e)return salla.lang.messages&&salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0,void salla.log("There is no `store.url` to auto loading translations from it!");let t=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),s=document.createElement("script");s.src=e+`/languages/assets/${t}.js`,s.onload=()=>{if(window.translations)return this.setMessages(window.translations),salla.event.dispatch("languages::translations.loaded"),void(this.translationsLoaded=!0);console.warn('You should load Salla Translations Before!\nUse: <script src="{{ link("languages/assets/{theme.translations_hash}.js") }}"><\/script>\nor: salla.lang.setMessages({....}), see https://github.com/rmariuzzo/Lang.js for more informations.')},document.head.appendChild(s)}get(e,t,s){return window.translations&&(e="trans."+e),super.get(e,t,s)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}}var assign=make_assign(),create$1=make_create(),trim$1=make_trim(),Global$5="undefined"!=typeof window?window:commonjsGlobal,util$6={assign:assign,create:create$1,trim:trim$1,bind:bind$1,slice:slice$1,each:each$7,map:map,pluck:pluck$1,isList:isList$1,isFunction:isFunction$1,isObject:isObject$1,Global:Global$5};function make_assign(){return Object.assign||function(s,e,t,r){for(var i=1;i<arguments.length;i++)each$7(Object(arguments[i]),function(e,t){s[t]=e});return s}}function make_create(){return Object.create?function(e,t,s,r){var i=slice$1(arguments,1);return assign.apply(this,[Object.create(e)].concat(i))}:function(e,t,s,r){var i=slice$1(arguments,1);return n.prototype=e,assign.apply(this,[new n].concat(i))};function n(){}}function make_trim(){return String.prototype.trim?function(e){return String.prototype.trim.call(e)}:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}}function bind$1(e,t){return function(){return t.apply(e,Array.prototype.slice.call(arguments,0))}}function slice$1(e,t){return Array.prototype.slice.call(e,t||0)}function each$7(e,s){pluck$1(e,function(e,t){return s(e,t),!1})}function map(e,s){var r=isList$1(e)?[]:{};return pluck$1(e,function(e,t){return r[t]=s(e,t),!1}),r}function pluck$1(e,t){if(isList$1(e)){for(var s=0;s<e.length;s++)if(t(e[s],s))return e[s]}else for(var r in e)if(e.hasOwnProperty(r)&&t(e[r],r))return e[r]}function isList$1(e){return null!=e&&"function"!=typeof e&&"number"==typeof e.length}function isFunction$1(e){return e&&"[object Function]"==={}.toString.call(e)}function isObject$1(e){return e&&"[object Object]"==={}.toString.call(e)}var util$5=util$6,slice=util$5.slice,pluck=util$5.pluck,each$6=util$5.each,bind=util$5.bind,create=util$5.create,isList=util$5.isList,isFunction=util$5.isFunction,isObject=util$5.isObject,storeEngine={createStore:createStore},storeAPI={version:"2.0.12",enabled:!1,get:function(e,t){e=this.storage.read(this._namespacePrefix+e);return this._deserialize(e,t)},set:function(e,t){return void 0===t?this.remove(e):(this.storage.write(this._namespacePrefix+e,this._serialize(t)),t)},remove:function(e){this.storage.remove(this._namespacePrefix+e)},each:function(s){var r=this;this.storage.each(function(e,t){s.call(r,r._deserialize(e),(t||"").replace(r._namespaceRegexp,""))})},clearAll:function(){this.storage.clearAll()},hasNamespace:function(e){return this._namespacePrefix=="__storejs_"+e+"_"},createStore:function(){return createStore.apply(this,arguments)},addPlugin:function(e){this._addPlugin(e)},namespace:function(e){return createStore(this.storage,this.plugins,e)}};function _warn(){var e="undefined"==typeof console?null:console;e&&(e.warn||e.log).apply(e,arguments)}function createStore(e,t,s){s=s||"",e&&!isList(e)&&(e=[e]),t&&!isList(t)&&(t=[t]);var r=s?"__storejs_"+s+"_":"",i=s?new RegExp("^"+r):null;if(!/^[a-zA-Z0-9_\-]*$/.test(s))throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes");var n=create({_namespacePrefix:r,_namespaceRegexp:i,_testStorage:function(e){try{var t="__storejs__test__",s=(e.write(t,t),e.read(t)===t);return e.remove(t),s}catch(e){return!1}},_assignPluginFnProp:function(r,e){var i=this[e];this[e]=function(){var s=slice(arguments,0),e=this;var t=[function(){if(i)return each$6(arguments,function(e,t){s[t]=e}),i.apply(e,s)}].concat(s);return r.apply(e,t)}},_serialize:function(e){return JSON.stringify(e)},_deserialize:function(e,t){if(!e)return t;var s="";try{s=JSON.parse(e)}catch(t){s=e}return void 0!==s?s:t},_addStorage:function(e){this.enabled||this._testStorage(e)&&(this.storage=e,this.enabled=!0)},_addPlugin:function(s){var r=this;if(isList(s))each$6(s,function(e){r._addPlugin(e)});else if(!pluck(this.plugins,function(e){return s===e})){if(this.plugins.push(s),!isFunction(s))throw new Error("Plugins must be function values that return objects");var e=s.call(this);if(!isObject(e))throw new Error("Plugins must return an object of function properties");each$6(e,function(e,t){if(!isFunction(e))throw new Error("Bad plugin property: "+t+" from plugin "+s.name+". Plugins should only return functions.");r._assignPluginFnProp(e,t)})}},addStorage:function(e){_warn("store.addStorage(storage) is deprecated. Use createStore([storages])"),this._addStorage(e)}},storeAPI,{plugins:[]});return n.raw={},each$6(n,function(e,t){isFunction(e)&&(n.raw[t]=bind(n,e))}),each$6(e,function(e){n._addStorage(e)}),each$6(t,function(e){n._addPlugin(e)}),n}var util$4=util$6,Global$4=util$4.Global,localStorage_1={name:"localStorage",read:read$5,write:write$5,each:each$5,remove:remove$5,clearAll:clearAll$5};function localStorage(){return Global$4.localStorage}function read$5(e){return localStorage().getItem(e)}function write$5(e,t){return localStorage().setItem(e,t)}function each$5(e){for(var t=localStorage().length-1;0<=t;t--){var s=localStorage().key(t);e(read$5(s),s)}}function remove$5(e){return localStorage().removeItem(e)}function clearAll$5(){return localStorage().clear()}var util$3=util$6,Global$3=util$3.Global,oldFFGlobalStorage={name:"oldFF-globalStorage",read:read$4,write:write$4,each:each$4,remove:remove$4,clearAll:clearAll$4},globalStorage=Global$3.globalStorage;function read$4(e){return globalStorage[e]}function write$4(e,t){globalStorage[e]=t}function each$4(e){for(var t=globalStorage.length-1;0<=t;t--){var s=globalStorage.key(t);e(globalStorage[s],s)}}function remove$4(e){return globalStorage.removeItem(e)}function clearAll$4(){each$4(function(e,t){delete globalStorage[e]})}var util$2=util$6,Global$2=util$2.Global,oldIEUserDataStorage={name:"oldIE-userDataStorage",write:write$3,read:read$3,each:each$3,remove:remove$3,clearAll:clearAll$3},storageName="storejs",doc$1=Global$2.document,_withStorageEl=_makeIEStorageElFunction(),disable=(Global$2.navigator?Global$2.navigator.userAgent:"").match(/ (MSIE 8|MSIE 9|MSIE 10)\./);function write$3(e,t){var s;disable||(s=fixKey(e),_withStorageEl(function(e){e.setAttribute(s,t),e.save(storageName)}))}function read$3(e){var t,s;if(!disable)return t=fixKey(e),s=null,_withStorageEl(function(e){s=e.getAttribute(t)}),s}function each$3(i){_withStorageEl(function(e){for(var t=e.XMLDocument.documentElement.attributes,s=t.length-1;0<=s;s--){var r=t[s];i(e.getAttribute(r.name),r.name)}})}function remove$3(e){var t=fixKey(e);_withStorageEl(function(e){e.removeAttribute(t),e.save(storageName)})}function clearAll$3(){_withStorageEl(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(storageName);for(var s=t.length-1;0<=s;s--)e.removeAttribute(t[s].name);e.save(storageName)})}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function fixKey(e){return e.replace(/^\d/,"___$&").replace(forbiddenCharsRegex,"___")}function _makeIEStorageElFunction(){if(!doc$1||!doc$1.documentElement||!doc$1.documentElement.addBehavior)return null;var s,e,r;try{(e=new ActiveXObject("htmlfile")).open(),e.write('<script>document.w=window<\/script><iframe src="/favicon.ico"></iframe>'),e.close(),s=e.w.frames[0].document,r=s.createElement("div")}catch(e){r=doc$1.createElement("div"),s=doc$1.body}return function(e){var t=[].slice.call(arguments,0);t.unshift(r),s.appendChild(r),r.addBehavior("#default#userData"),r.load(storageName),e.apply(this,t),s.removeChild(r)}}var util$1=util$6,Global$1=util$1.Global,trim=util$1.trim,cookieStorage={name:"cookieStorage",read:read$2,write:write$2,each:each$2,remove:remove$2,clearAll:clearAll$2},doc=Global$1.document;function read$2(e){if(!e||!_has(e))return null;e="(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(doc.cookie.replace(new RegExp(e),"$1"))}function each$2(e){for(var t,s,r=doc.cookie.split(/; ?/g),i=r.length-1;0<=i;i--)trim(r[i])&&(t=r[i].split("="),s=unescape(t[0]),e(unescape(t[1]),s))}function write$2(e,t){e&&(doc.cookie=escape(e)+"="+escape(t)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/")}function remove$2(e){e&&_has(e)&&(doc.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function clearAll$2(){each$2(function(e,t){remove$2(t)})}function _has(e){return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(doc.cookie)}var util=util$6,Global=util.Global,sessionStorage_1={name:"sessionStorage",read:read$1,write:write$1,each:each$1,remove:remove$1,clearAll:clearAll$1};function sessionStorage(){return Global.sessionStorage}function read$1(e){return sessionStorage().getItem(e)}function write$1(e,t){return sessionStorage().setItem(e,t)}function each$1(e){for(var t=sessionStorage().length-1;0<=t;t--){var s=sessionStorage().key(t);e(read$1(s),s)}}function remove$1(e){return sessionStorage().removeItem(e)}function clearAll$1(){return sessionStorage().clear()}var memoryStorage_1={name:"memoryStorage",read:read,write:write,each:each,remove:remove,clearAll:clearAll},memoryStorage={};function read(e){return memoryStorage[e]}function write(e,t){memoryStorage[e]=t}function each(e){for(var t in memoryStorage)memoryStorage.hasOwnProperty(t)&&e(memoryStorage[t],t)}function remove(e){delete memoryStorage[e]}function clearAll(e){memoryStorage={}}var all=[localStorage_1,oldFFGlobalStorage,oldIEUserDataStorage,cookieStorage,sessionStorage_1,memoryStorage_1],json2=("object"!=typeof JSON&&(JSON={}),function(){var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/g,rx_escapable=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta,rep;function f(e){return e<10?"0"+e:e}function this_value(){return this.valueOf()}function quote(e){return rx_escapable.lastIndex=0,rx_escapable.test(e)?'"'+e.replace(rx_escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var s,r,i,n,a,o=gap,l=t[e];switch(l&&"object"==typeof l&&"function"==typeof l.toJSON&&(l=l.toJSON(e)),typeof(l="function"==typeof rep?rep.call(t,e,l):l)){case"string":return quote(l);case"number":return isFinite(l)?String(l):"null";case"boolean":case"null":return String(l);case"object":if(!l)return"null";if(gap+=indent,a=[],"[object Array]"===Object.prototype.toString.apply(l)){for(n=l.length,s=0;s<n;s+=1)a[s]=str(s,l)||"null";return i=0===a.length?"[]":gap?"[\n"+gap+a.join(",\n"+gap)+"\n"+o+"]":"["+a.join(",")+"]",gap=o,i}if(rep&&"object"==typeof rep)for(n=rep.length,s=0;s<n;s+=1)"string"==typeof rep[s]&&(i=str(r=rep[s],l))&&a.push(quote(r)+(gap?": ":":")+i);else for(r in l)Object.prototype.hasOwnProperty.call(l,r)&&(i=str(r,l))&&a.push(quote(r)+(gap?": ":":")+i);return i=0===a.length?"{}":gap?"{\n"+gap+a.join(",\n"+gap)+"\n"+o+"}":"{"+a.join(",")+"}",gap=o,i}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value),"function"!=typeof JSON.stringify&&(meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(e,t,s){var r;if(indent=gap="","number"==typeof s)for(r=0;r<s;r+=1)indent+=" ";else"string"==typeof s&&(indent=s);if(!(rep=t)||"function"==typeof t||"object"==typeof t&&"number"==typeof t.length)return str("",{"":e});throw new Error("JSON.stringify")}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){var j;function walk(e,t){var s,r,i=e[t];if(i&&"object"==typeof i)for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&(void 0!==(r=walk(i,s))?i[s]=r:delete i[s]);return reviver.call(e,t,i)}if(text=String(text),rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),rx_one.test(text.replace(rx_two,"@").replace(rx_three,"]").replace(rx_four,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),json2Plugin);function json2Plugin(){return{}}var engine=storeEngine,storages=all,plugins=[json2],store_legacy=engine.createStore(storages,plugins);class SallaStorage{constructor(e){e.on("storage::item.remove",e=>this.remove(e)),e.on("storage::item.set",(e,t)=>this.set(e,t)),this.store=store_legacy}set(e,t){var s,r;return e.includes(".")?(r={[s=e.split(".")[0]]:store_legacy.get(s)},r=salla.helpers.setNested(r,e,t),store_legacy.set(s,r[s])):store_legacy.set(e,t)}remove(e){return store_legacy.remove(e)}get(e,t){var s;return e.includes(".")?(s=e.split(".")[0],salla.helpers.getNested({[s]:store_legacy.get(s)},e)):store_legacy.get(e,t)}}let event$1=new sallaEmitter,api=new SallaApi(event$1);window.Salla=window.salla={notify:Notify,api:api,event:event$1,infiniteScroll:new InfiniteScroll(void 0,event$1.infiniteScroll),helpers:Helpers,config:new SallaConfig,storage:new SallaStorage(event$1),cookie:new SallaCookie(event$1),lang:new SallaLang,cart:new Cart(api.cart,event$1.cart),auth:new Auth(api.auth,event$1.auth),gift:new Gift(api.gift,event$1.gift),order:new Order(api.order,event$1.order),offer:new Offer(api.offer,event$1.offer),search:new Search(api.search,event$1.search),coupon:new Coupon(api.coupon,event$1.coupon),comment:new Comment(api.comment,event$1.comment),loyalty:new Loyalty(api.loyalty,event$1.loyalty),product:new Product(api.product,event$1.product),currency:new Currency(api.currency,event$1.currency),document:new Document(api.document,event$1.document),feedback:new Feedback(api.feedback,event$1.feedback),twilight:new Twilight(api.twilight,event$1.twilight),form:new Form,wishlist:new Wishlist(api.wishlist,event$1.wishlist),scope:new Scope(api.scope,event$1.scope),init:e=>api.twilight.init(e),log:Notify.log,success:Notify.success,error:Notify.error,onReady:e=>document.addEventListener("DOMContentLoaded",e),AppHelpers:AppHelpers,money:Helpers.money,url:Helpers.url,call:e=>{let t=salla,s=e.split(".");for(;s.length&&(t=t[s.shift()]););return t}};var salla$1=salla;exports.default=salla$1});
|
|
10
13
|
//# sourceMappingURL=twilight.min.js.map
|