/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@algolia/recommend@4.14.2/dist/recommend.umd.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/*! recommend.umd.js | 4.14.2 | © Algolia, inc. | https://github.com/algolia/algoliasearch-client-javascript */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define('recommend', t):(e=e||self)["@algolia/recommend"]=t()}(this,(function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?t(Object(o),!0).forEach((function(t){e(r,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(o,e))}))}return r}function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw a}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function o(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t<e.length;t++)r[t]=e[t];return r}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function a(e){var t,r="algoliasearch-client-js-".concat(e.key),o=function(){return void 0===t&&(t=e.localStorage||window.localStorage),t},a=function(){return JSON.parse(o().getItem(r)||"{}")};return{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then((function(){var r=JSON.stringify(e),n=a()[r];return Promise.all([n||t(),void 0!==n])})).then((function(e){var t=n(e,2),o=t[0],a=t[1];return Promise.all([o,a||r.miss(o)])})).then((function(e){return n(e,1)[0]}))},set:function(e,t){return Promise.resolve().then((function(){var n=a();return n[JSON.stringify(e)]=t,o().setItem(r,JSON.stringify(n)),t}))},delete:function(e){return Promise.resolve().then((function(){var t=a();delete t[JSON.stringify(e)],o().setItem(r,JSON.stringify(t))}))},clear:function(){return Promise.resolve().then((function(){o().removeItem(r)}))}}}function u(e){var t=o(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},o=t();return o.then((function(e){return Promise.all([e,r.miss(e)])})).then((function(e){return n(e,1)[0]}))},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,o).catch((function(){return u({caches:t}).get(e,n,o)}))},set:function(e,n){return r.set(e,n).catch((function(){return u({caches:t}).set(e,n)}))},delete:function(e){return r.delete(e).catch((function(){return u({caches:t}).delete(e)}))},clear:function(){return r.clear().catch((function(){return u({caches:t}).clear()}))}}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var u=n(),i=o&&o.miss||function(){return Promise.resolve()};return u.then((function(e){return i(e)})).then((function(){return u}))},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function s(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}var c={WithinQueryParameters:0,WithinHeaders:1},l=1,f=2,d=3;function h(e,t){var r=e||{},n=r.data||{};return Object.keys(r).forEach((function(e){-1===["timeout","headers","queryParameters","data","cacheable"].indexOf(e)&&(n[e]=r[e])})),{data:Object.entries(n).length>0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var m={Read:1,Write:2,Any:3},p=1,g=2,v=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function b(e){return"string"==typeof e?{protocol:"https",url:e,accept:m.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||m.Any}}var P="GET",O="POST";function q(e,t){return Promise.all(t.map((function(t){return e.get(t,(function(){return Promise.resolve(y(t))}))}))).then((function(e){var r=e.filter((function(e){return function(e){return e.status===p||Date.now()-e.lastUpdate>12e4}(e)})),n=e.filter((function(e){return function(e){return e.status===v&&Date.now()-e.lastUpdate<=12e4}(e)})),a=[].concat(o(r),o(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:a.length>0?a.map((function(e){return b(e)})):t}}))}function S(e,t,n,a){var u=[],i=function(e,t){if(e.method===P||void 0===e.data&&void 0===t.data)return;var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}(n,a),s=function(e,t){var n=r(r({},e.headers),t.headers),o={};return Object.keys(n).forEach((function(e){var t=n[e];o[e.toLowerCase()]=t})),o}(e,a),c=n.method,l=n.method!==P?{}:r(r({},n.data),a.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),l),a.queryParameters),d=0,h=function t(r,o){var l=r.pop();if(void 0===l)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:T(u)};var h={data:i,headers:s,method:c,url:w(l,n.path,f),connectTimeout:o(d,e.timeouts.connect),responseTimeout:o(d,a.timeout)},m=function(e){var t={request:h,response:e,host:l,triesLeft:r.length};return u.push(t),t},p={onSuccess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var a=m(n);return n.isTimedOut&&d++,Promise.all([e.logger.info("Retryable failure",A(a)),e.hostsCache.set(l,y(l,n.isTimedOut?v:g))]).then((function(){return t(r,o)}))},onFail:function(e){throw m(e),function(e,t){var r=e.content,n=e.status,o=r;try{o=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}(o,n,t)}(e,T(u))}};return e.requester.send(h).then((function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSuccess(e):t.onFail(e)}(e,p)}))};return q(e.hostsCache,t).then((function(e){return h(o(e.statelessHosts).reverse(),e.getTimeout)}))}function j(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function w(e,t,r){var n,o=(n=r,Object.keys(n).map((function(e){return function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var o=0;return e.replace(/%s/g,(function(){return encodeURIComponent(r[o++])}))}("%s=%s",e,(t=n[e],"[object Object]"===Object.prototype.toString.call(t)||"[object Array]"===Object.prototype.toString.call(t)?JSON.stringify(n[e]):n[e]));var t})).join("&")),a="".concat(e.protocol,"://").concat(e.url,"/").concat("/"===t.charAt(0)?t.substr(1):t);return o.length&&(a+="?".concat(o)),a}function T(e){return e.map((function(e){return A(e)}))}function A(e){var t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},e),{},{request:r(r({},e.request),{},{headers:r(r({},e.request.headers),t)})})}var C=function(e){var t=e.appId,o=function(e,t,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers:function(){return e===c.WithinHeaders?n:{}},queryParameters:function(){return e===c.WithinQueryParameters?n:{}}}}(void 0!==e.authMode?e.authMode:c.WithinHeaders,t,e.apiKey),a=function(e){var t=e.hostsCache,r=e.logger,o=e.requester,a=e.requestsCache,u=e.responsesCache,i=e.timeouts,s=e.userAgent,c=e.hosts,l=e.queryParameters,f={hostsCache:t,logger:r,requester:o,requestsCache:a,responsesCache:u,timeouts:i,userAgent:s,headers:e.headers,queryParameters:l,hosts:c.map((function(e){return b(e)})),read:function(e,t){var r=h(t,f.timeouts.read),o=function(){return S(f,f.hosts.filter((function(e){return 0!=(e.accept&m.Read)})),e,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:e.cacheable))return o();var a={request:e,mappedRequestOptions:r,transporter:{queryParameters:f.queryParameters,headers:f.headers}};return f.responsesCache.get(a,(function(){return f.requestsCache.get(a,(function(){return f.requestsCache.set(a,o()).then((function(e){return Promise.all([f.requestsCache.delete(a),e])}),(function(e){return Promise.all([f.requestsCache.delete(a),Promise.reject(e)])})).then((function(e){var t=n(e,2);t[0];return t[1]}))}))}),{miss:function(e){return f.responsesCache.set(a,e)}})},write:function(e,t){return S(f,f.hosts.filter((function(e){return 0!=(e.accept&m.Write)})),e,h(t,f.timeouts.write))}};return f}(r(r({hosts:[{url:"".concat(t,"-dsn.algolia.net"),accept:m.Read},{url:"".concat(t,".algolia.net"),accept:m.Write}].concat(s([{url:"".concat(t,"-1.algolianet.com")},{url:"".concat(t,"-2.algolianet.com")},{url:"".concat(t,"-3.algolianet.com")}]))},e),{},{headers:r(r(r({},o.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:r(r({},o.queryParameters()),e.queryParameters)}));return function(e,t){return t?(Object.keys(t).forEach((function(r){e[r]=t[r](e)})),e):e}({transporter:a,appId:t,addAlgoliaAgent:function(e,t){a.userAgent.add({segment:e,version:t})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then((function(){}))}},e.methods)},N=function(e){return function(t,n){var o=t.map((function(e){return r(r({},e),{},{threshold:e.threshold||0})}));return e.transporter.read({method:O,path:"1/indexes/*/recommendations",data:{requests:o},cacheable:!0},n)}},k=function(e){return function(t,n){return N(e)(t.map((function(e){return r(r({},e),{},{fallbackParameters:{},model:"bought-together"})})),n)}},x=function(e){return function(t,n){return N(e)(t.map((function(e){return r(r({},e),{},{model:"related-products"})})),n)}},J=function(e){return function(t,n){var o=t.map((function(e){return r(r({},e),{},{model:"trending-facets",threshold:e.threshold||0})}));return e.transporter.read({method:O,path:"1/indexes/*/recommendations",data:{requests:o},cacheable:!0},n)}},E=function(e){return function(t,n){var o=t.map((function(e){return r(r({},e),{},{model:"trending-items",threshold:e.threshold||0})}));return e.transporter.read({method:O,path:"1/indexes/*/recommendations",data:{requests:o},cacheable:!0},n)}};function R(e,t,n){var o,s={appId:e,apiKey:t,timeouts:{connect:1,read:2,write:30},requester:{send:function(e){return new Promise((function(t){var r=new XMLHttpRequest;r.open(e.method,e.url,!0),Object.keys(e.headers).forEach((function(t){return r.setRequestHeader(t,e.headers[t])}));var n,o=function(e,n){return setTimeout((function(){r.abort(),t({status:0,content:n,isTimedOut:!0})}),1e3*e)},a=o(e.connectTimeout,"Connection timeout");r.onreadystatechange=function(){r.readyState>r.OPENED&&void 0===n&&(clearTimeout(a),n=o(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)}))}},logger:(o=d,{debug:function(e,t){return l>=o&&console.debug(e,t),Promise.resolve()},info:function(e,t){return f>=o&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:i(),requestsCache:i({serializable:!1}),hostsCache:u({caches:[a({key:"".concat("4.14.2","-").concat(e)}),i()]}),userAgent:j("4.14.2").add({segment:"Recommend",version:"4.14.2"}).add({segment:"Browser"}),authMode:c.WithinQueryParameters};return C(r(r(r({},s),n),{},{methods:{getFrequentlyBoughtTogether:k,getRecommendations:N,getRelatedProducts:x,getTrendingFacets:J,getTrendingItems:E}}))}return R.version="4.14.2",R}));

define('Algolia_AlgoliaSearch/internals/template/recommend/products', [], function () {
    return {
        getItemHtml: function (item, html, addTocart) {
            let correctFKey = getCookie('form_key');
            let action = algoliaConfig.recommend.addToCartParams.action + 'product/' + item.objectID + '/';
            if(correctFKey != "" && algoliaConfig.recommend.addToCartParams.formKey != correctFKey) {
                algoliaConfig.recommend.addToCartParams.formKey = correctFKey;
            }
            this.defaultIndexName = algoliaConfig.indexName + '_products';
            return  html`<div class="product-details">
                <a class="recommend-item product-url" href="${item.url}" data-objectid=${item.objectID} data-position=${item.position}  data-index=${this.defaultIndexName}>
                    <img class="product-img" src="${item.image_url}" alt="${item.name}"/>
                    <p class="product-name">${item.name}</p>
                    ${addTocart && html`
                        <form class="addTocartForm" action="${action}" method="post" data-role="tocart-form">
                            <input type="hidden" name="form_key" value="${algoliaConfig.recommend.addToCartParams.formKey}" />
                            <input type="hidden" name="unec" value="${AlgoliaBase64.mageEncode(action)}"/>
                            <input type="hidden" name="product" value="${item.objectID}" />
                            <button type="submit" class="action tocart primary">
                                <span>${algoliaConfig.translations.addToCart}</span>
                            </button>
                        </form>`
                    }
                </a>
            </div>`;
        },
        getHeaderHtml: function (html,title) {
            return html`<h3 class="auc-Recommend-title">${title}</h3>`;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('mage/sticky', [
    'jquery',
    'jquery-ui-modules/widget'
], function ($) {
    'use strict';

    $.widget('mage.sticky', {
        options: {
            /**
             * Element selector, who's height will be used to restrict the
             * maximum offsetTop position of the stuck element.
             * Default uses document body.
             * @type {String}
             */
            container: '',

            /**
             * Spacing in pixels above the stuck element
             * @type {Number|Function} Number or Function that will return a Number
             */
            spacingTop: 0,

            /**
             * Allows postponing sticking, until element will go out of the
             * screen for the number of pixels.
             * @type {Number|Function} Number or Function that will return a Number
             */
            stickAfter: 0,

            /**
             * CSS class for active sticky state
             * @type {String}
             */
            stickyClass: '_sticky'
        },

        /**
         * Retrieve option value
         * @param  {String} option
         * @return {*}
         * @private
         */
        _getOptionValue: function (option) {
            var value = this.options[option] || 0;

            if (typeof value === 'function') {
                value = this.options[option]();
            }

            return value;
        },

        /**
         * Bind handlers to scroll event
         * @private
         */
        _create: function () {
            $(window).on({
                'scroll': $.proxy(this._stick, this),
                'resize': $.proxy(this.reset, this)
            });

            this.element.on('dimensionsChanged', $.proxy(this.reset, this));

            this.reset();

            // Application of the workaround for IE11 and Edge
            this.normalizeIE11AndEdgeScroll();
        },

        /**
         * float Block on windowScroll
         * @private
         */
        _stick: function () {
            var offset,
                isStatic,
                stuck,
                stickAfter;

            isStatic = this.element.css('position') === 'static';

            if (!isStatic && this.element.is(':visible')) {
                offset = $(document).scrollTop() -
                    this.parentOffset +
                    this._getOptionValue('spacingTop');

                offset = Math.max(0, Math.min(offset, this.maxOffset));

                stuck = this.element.hasClass(this.options.stickyClass);
                stickAfter = this._getOptionValue('stickAfter');

                if (offset && !stuck && offset < stickAfter) {
                    offset = 0;
                }

                this.element
                    .toggleClass(this.options.stickyClass, offset > 0)
                    .css('top', offset);
            }
        },

        /**
         * Defines maximum offset value of the element.
         * @private
         */
        _calculateDimens: function () {
            var $parent         = this.element.parent(),
                topMargin       = parseInt(this.element.css('margin-top'), 10),
                parentHeight    = $parent.height() - topMargin,
                height          = this.element.innerHeight(),
                maxScroll       = document.body.offsetHeight - window.innerHeight;

            if (this.options.container.length > 0) {
                maxScroll = $(this.options.container).height();
            }

            this.parentOffset   = $parent.offset().top + topMargin;
            this.maxOffset      = maxScroll - this.parentOffset;

            if (this.maxOffset + height >= parentHeight) {
                this.maxOffset = parentHeight - height;
            }

            return this;
        },

        /**
         * Facade method that places sticky element where it should be.
         */
        reset: function () {
            this._calculateDimens()
                ._stick();
        },

        /**
         * Workaround for IE11 and Edge that solves the IE known rendering issue
         * that prevents sticky element from jumpy movement on scrolling the page.
         *
         * Alternatively, undesired jumpy movement can be eliminated by changing the setting in IE:
         * Settings > Internet options > Advanced tab > inside 'Browsing' item > set 'Use smooth scrolling' to False
         */
        normalizeIE11AndEdgeScroll: function () {
            if (navigator.userAgent.match(/Trident.*rv[ :]*11\.|Edge\//)) {
                document.body.addEventListener('mousewheel', function () {
                    event.preventDefault();
                    window.scrollTo(0, window.pageYOffset - event.wheelDelta);
                });
            }
        }
    });

    return $.mage.sticky;
});

/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@algolia/recommend-js@1.8.0/dist/umd/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/*! @algolia/recommend-js 1.8.0 | MIT License | © Algolia, Inc. and contributors | https://github.com/algolia/recommend */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define('recommendJs', ["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@algolia/recommend-js"]={})}(this,(function(e){"use strict";function t(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function n(){return n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(this,arguments)}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function i(e,t){if(e){if("string"==typeof e)return o(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?o(e,t):void 0}}function a(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,i=[],a=!0,c=!1;try{for(n=n.call(e);!(a=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);a=!0);}catch(e){c=!0,o=e}finally{try{a||null==n.return||n.return()}finally{if(c)throw o}}return i}}(e,t)||i(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e){var t=e.hits,n=e.maxRecommendations,r=e.nrOfObjs,o={};t.forEach((function(e){e.forEach((function(e,t){o[e.objectID]?o[e.objectID]={indexSum:o[e.objectID].indexSum+t,nr:o[e.objectID].nr+1}:o[e.objectID]={indexSum:t,nr:1}}))}));var i=function(e,t){for(var n=[],r=0,o=Object.keys(e);r<o.length;r++){var i=o[r];e[i].nr<2&&(e[i].indexSum+=100),n.push({objectID:i,avgOfIndices:e[i].indexSum/t})}return n.sort((function(e,t){return e.avgOfIndices>t.avgOfIndices?1:-1}))}(o,r);return i.reduce((function(e,n){var r=t.flat().find((function(e){return e.objectID===n.objectID}));return r?e.concat(r):e}),[]).slice(0,n&&n>0?n:void 0)}function l(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||i(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e){var t,n,r,o=e.hits,i=e.maxRecommendations;return(t=function(e,t){return(e._score||0)>(t._score||0)?-1:1},n=o,r=l(n),r.sort(t),r).slice(0,i&&i>0?i:void 0)}var s="1.8.0";function m(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter(Boolean).join(" ")}function _(e){var t=e.createElement,n=e.Fragment;return function(e){return 0===e.recommendations.length&&"idle"===e.status?t(e.Fallback,null):t("section",{className:m("auc-Recommend",e.classNames.root)},t(e.Header,{classNames:e.classNames,recommendations:e.recommendations,translations:e.translations,createElement:t,Fragment:n}),t(e.View,null))}}function f(e){var t=e.createElement;return function(e){return!e.recommendations||e.recommendations.length<1?null:e.translations.title?t("h3",{className:m("auc-Recommend-title",e.classNames.title)},e.translations.title):null}}function p(e){var t=e.createElement,n=e.Fragment;return function(e){return t("div",{className:m("auc-Recommend-container",e.classNames.container)},t("ol",{className:m("auc-Recommend-list",e.classNames.list)},e.items.map((function(r){return t("li",{key:r.objectID,className:m("auc-Recommend-item",e.classNames.item)},t(e.itemComponent,{createElement:t,Fragment:n,item:r}))}))))}}function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function h(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function v(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function b(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}var y,g,O,j,w={},P=[],k=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function C(e,t){for(var n in t)e[n]=t[n];return e}function E(e){var t=e.parentNode;t&&t.removeChild(e)}function D(e,t,n){var r,o,i,a=arguments,c={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:c[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(a[i]);if(null!=n&&(c.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===c[i]&&(c[i]=e.defaultProps[i]);return S(e,c,r,o,null)}function S(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++y.__v:o};return null!=y.vnode&&y.vnode(i),i}function F(e){return e.children}function N(e,t){this.props=e,this.context=t}function x(e,t){if(null==t)return e.__?x(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?x(e):null}function A(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return A(e)}}function I(e){(!e.__d&&(e.__d=!0)&&g.push(e)&&!R.__r++||j!==y.debounceRendering)&&((j=y.debounceRendering)||O)(R)}function R(){for(var e;R.__r=g.length;)e=g.sort((function(e,t){return e.__v.__b-t.__v.__b})),g=[],e.some((function(e){var t,n,r,o,i,a;e.__d&&(i=(o=(t=e).__v).__e,(a=t.__P)&&(n=[],(r=C({},o)).__v=o.__v+1,W(a,o,r,t.__n,void 0!==a.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?x(o):i,o.__h),B(n,o),o.__e!=i&&A(o)))}))}function T(e,t,n,r,o,i,a,c,l,u){var s,m,_,f,p,d,h,v=r&&r.__k||P,b=v.length;for(n.__k=[],s=0;s<t.length;s++)if(null!=(f=n.__k[s]=null==(f=t[s])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?S(null,f,null,null,f):Array.isArray(f)?S(F,{children:f},null,null,null):f.__b>0?S(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(_=v[s])||_&&f.key==_.key&&f.type===_.type)v[s]=void 0;else for(m=0;m<b;m++){if((_=v[m])&&f.key==_.key&&f.type===_.type){v[m]=void 0;break}_=null}W(e,f,_=_||w,o,i,a,c,l,u),p=f.__e,(m=f.ref)&&_.ref!=m&&(h||(h=[]),_.ref&&h.push(_.ref,null,f),h.push(m,f.__c||p,f)),null!=p?(null==d&&(d=p),"function"==typeof f.type&&null!=f.__k&&f.__k===_.__k?f.__d=l=H(f,l,e):l=q(e,f,_,v,p,l),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=l):e.value=""):l&&_.__e==l&&l.parentNode!=e&&(l=x(_))}for(n.__e=d,s=b;s--;)null!=v[s]&&("function"==typeof n.type&&null!=v[s].__e&&v[s].__e==n.__d&&(n.__d=x(r,s+1)),z(v[s],v[s]));if(h)for(s=0;s<h.length;s++)G(h[s],h[++s],h[++s])}function H(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?H(o,t,n):q(n,o,o,e.__k,o.__e,t));return t}function q(e,t,n,r,o,i){var a,c,l;if(void 0!==t.__d)a=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),a=null;else{for(c=i,l=0;(c=c.nextSibling)&&l<r.length;l+=2)if(c==o)break e;e.insertBefore(o,i),a=i}return void 0!==a?a:o.nextSibling}function M(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||k.test(t)?n:n+"px"}function L(e,t,n,r,o){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||M(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||M(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?V:U,i):e.removeEventListener(t,i?V:U,i);else if("dangerouslySetInnerHTML"!==t){if(o)t=t.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function U(e){this.l[e.type+!1](y.event?y.event(e):e)}function V(e){this.l[e.type+!0](y.event?y.event(e):e)}function W(e,t,n,r,o,i,a,c,l){var u,s,m,_,f,p,d,h,v,b,g,O=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(l=n.__h,c=t.__e=n.__e,t.__h=null,i=[c]),(u=y.__b)&&u(t);try{e:if("function"==typeof O){if(h=t.props,v=(u=O.contextType)&&r[u.__c],b=u?v?v.props.value:u.__:r,n.__c?d=(s=t.__c=n.__c).__=s.__E:("prototype"in O&&O.prototype.render?t.__c=s=new O(h,b):(t.__c=s=new N(h,b),s.constructor=O,s.render=J),v&&v.sub(s),s.props=h,s.state||(s.state={}),s.context=b,s.__n=r,m=s.__d=!0,s.__h=[]),null==s.__s&&(s.__s=s.state),null!=O.getDerivedStateFromProps&&(s.__s==s.state&&(s.__s=C({},s.__s)),C(s.__s,O.getDerivedStateFromProps(h,s.__s))),_=s.props,f=s.state,m)null==O.getDerivedStateFromProps&&null!=s.componentWillMount&&s.componentWillMount(),null!=s.componentDidMount&&s.__h.push(s.componentDidMount);else{if(null==O.getDerivedStateFromProps&&h!==_&&null!=s.componentWillReceiveProps&&s.componentWillReceiveProps(h,b),!s.__e&&null!=s.shouldComponentUpdate&&!1===s.shouldComponentUpdate(h,s.__s,b)||t.__v===n.__v){s.props=h,s.state=s.__s,t.__v!==n.__v&&(s.__d=!1),s.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),s.__h.length&&a.push(s);break e}null!=s.componentWillUpdate&&s.componentWillUpdate(h,s.__s,b),null!=s.componentDidUpdate&&s.__h.push((function(){s.componentDidUpdate(_,f,p)}))}s.context=b,s.props=h,s.state=s.__s,(u=y.__r)&&u(t),s.__d=!1,s.__v=t,s.__P=e,u=s.render(s.props,s.state,s.context),s.state=s.__s,null!=s.getChildContext&&(r=C(C({},r),s.getChildContext())),m||null==s.getSnapshotBeforeUpdate||(p=s.getSnapshotBeforeUpdate(_,f)),g=null!=u&&u.type===F&&null==u.key?u.props.children:u,T(e,Array.isArray(g)?g:[g],t,n,r,o,i,a,c,l),s.base=t.__e,t.__h=null,s.__h.length&&a.push(s),d&&(s.__E=s.__=null),s.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=$(n.__e,t,n,r,o,i,a,l);(u=y.diffed)&&u(t)}catch(e){t.__v=null,(l||null!=i)&&(t.__e=c,t.__h=!!l,i[i.indexOf(c)]=null),y.__e(e,t,n)}}function B(e,t){y.__c&&y.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){y.__e(e,t.__v)}}))}function $(e,t,n,r,o,i,a,c){var l,u,s,m,_=n.props,f=t.props,p=t.type,d=0;if("svg"===p&&(o=!0),null!=i)for(;d<i.length;d++)if((l=i[d])&&(l===e||(p?l.localName==p:3==l.nodeType))){e=l,i[d]=null;break}if(null==e){if(null===p)return document.createTextNode(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,c=!1}if(null===p)_===f||c&&e.data===f||(e.data=f);else{if(i=i&&P.slice.call(e.childNodes),u=(_=n.props||w).dangerouslySetInnerHTML,s=f.dangerouslySetInnerHTML,!c){if(null!=i)for(_={},m=0;m<e.attributes.length;m++)_[e.attributes[m].name]=e.attributes[m].value;(s||u)&&(s&&(u&&s.__html==u.__html||s.__html===e.innerHTML)||(e.innerHTML=s&&s.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||L(e,i,null,n[i],r);for(i in t)o&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||L(e,i,t[i],n[i],r)}(e,f,_,o,c),s)t.__k=[];else if(d=t.props.children,T(e,Array.isArray(d)?d:[d],t,n,r,o&&"foreignObject"!==p,i,a,e.firstChild,c),null!=i)for(d=i.length;d--;)null!=i[d]&&E(i[d]);c||("value"in f&&void 0!==(d=f.value)&&(d!==e.value||"progress"===p&&!d)&&L(e,"value",d,_.value,!1),"checked"in f&&void 0!==(d=f.checked)&&d!==e.checked&&L(e,"checked",d,_.checked,!1))}return e}function G(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){y.__e(e,n)}}function z(e,t,n){var r,o,i;if(y.unmount&&y.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||G(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){y.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&z(r[i],t,n);null!=o&&E(o)}function J(e,t,n){return this.constructor(e,n)}function K(e,t,n){var r,o,i;y.__&&y.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],W(t,e=(!r&&n||t).__k=D(F,null,[e]),o||w,w,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?P.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),B(i,e)}y={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},N.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=C({},this.state),"function"==typeof e&&(e=e(C({},n),this.props)),e&&C(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),I(this))},N.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),I(this))},N.prototype.render=F,g=[],O="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,R.__r=0;var Q=function(e,t,n,r){var o;t[0]=0;for(var i=1;i<t.length;i++){var a=t[i++],c=t[i]?(t[0]|=a?1:2,n[t[i++]]):t[++i];3===a?r[0]=c:4===a?r[1]=Object.assign(r[1]||{},c):5===a?(r[1]=r[1]||{})[t[++i]]=c:6===a?r[1][t[++i]]+=c+"":a?(o=e.apply(c,Q(e,c,n,["",null])),r.push(o),c[0]?t[0]|=2:(t[i-2]=0,t[i]=o)):r.push(c)}return r},X=new Map;var Y,Z,ee,te=function(e){var t=X.get(this);return t||(t=new Map,X.set(this,t)),(t=Q(this,t.get(e)||(t.set(e,t=function(e){for(var t,n,r=1,o="",i="",a=[0],c=function(e){1===r&&(e||(o=o.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?a.push(0,e,o):3===r&&(e||o)?(a.push(3,e,o),r=2):2===r&&"..."===o&&e?a.push(4,e,0):2===r&&o&&!e?a.push(5,0,!0,o):r>=5&&((o||!e&&5===r)&&(a.push(r,0,o,n),r=6),e&&(a.push(r,e,0,n),r=6)),o=""},l=0;l<e.length;l++){l&&(1===r&&c(),c(l));for(var u=0;u<e[l].length;u++)t=e[l][u],1===r?"<"===t?(c(),a=[a],r=3):o+=t:4===r?"--"===o&&">"===t?(r=1,o=""):o=t+o[0]:i?t===i?i="":o+=t:'"'===t||"'"===t?i=t:">"===t?(c(),r=1):r&&("="===t?(r=5,n=o,o=""):"/"===t&&(r<5||">"===e[l][u+1])?(c(),3===r&&(a=a[0]),r=a,(a=a[0]).push(2,0,r),r=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(c(),r=2):o+=t),3===r&&"!--"===o&&(r=4,a=a[0])}return c(),a}(e)),t),arguments,[])).length>1?t:t[0]}.bind(D),ne=0,re=[],oe=y.__b,ie=y.__r,ae=y.diffed,ce=y.__c,le=y.unmount;function ue(e,t){y.__h&&y.__h(Z,e,ne||t),ne=0;var n=Z.__H||(Z.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function se(e){return ne=1,function(e,t,n){var r=ue(Y++,2);return r.t=e,r.__c||(r.__=[n?n(t):be(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Z),r.__}(be,e)}function me(e,t){var n=ue(Y++,3);!y.__s&&ve(n.__H,t)&&(n.__=e,n.__H=t,Z.__H.__h.push(n))}function _e(e){return ne=5,function(e,t){var n=ue(Y++,7);return ve(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function fe(){re.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(de),e.__H.__h.forEach(he),e.__H.__h=[]}catch(t){e.__H.__h=[],y.__e(t,e.__v)}})),re=[]}y.__b=function(e){Z=null,oe&&oe(e)},y.__r=function(e){ie&&ie(e),Y=0;var t=(Z=e.__c).__H;t&&(t.__h.forEach(de),t.__h.forEach(he),t.__h=[])},y.diffed=function(e){ae&&ae(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==re.push(t)&&ee===y.requestAnimationFrame||((ee=y.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),pe&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);pe&&(t=requestAnimationFrame(n))})(fe)),Z=void 0},y.__c=function(e,t){t.some((function(e){try{e.__h.forEach(de),e.__h=e.__h.filter((function(e){return!e.__||he(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],y.__e(n,e.__v)}})),ce&&ce(e,t)},y.unmount=function(e){le&&le(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(de)}catch(e){y.__e(e,t.__v)}};var pe="function"==typeof requestAnimationFrame;function de(e){var t=Z;"function"==typeof e.__c&&e.__c(),Z=t}function he(e){var t=Z;e.__c=e.__(),Z=t}function ve(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function be(e,t){return"function"==typeof t?t(e):t}function ye(e,t){return"string"==typeof e?t.document.querySelector(e):e}function ge(e){me((function(){e.recommendClient.addAlgoliaAgent("recommend-js","1.8.0")}),[e.recommendClient])}function Oe(e){var t=_e(void 0),n=a(se(e),2),r=n[0],o=n[1];return me((function(){"stalled"!==r&&t.current&&clearTimeout(t.current),"loading"===r&&(t.current=setTimeout((function(){o("stalled")}),300))}),[r]),{status:r,setStatus:o}}function je(e){return function(t){return D(e,n({},t,{html:te}))}}var we=["container","environment","itemComponent","fallbackComponent","headerComponent","view","children"];function Pe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ke(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Pe(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Pe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Ce,Ee,De,Se=(Ee=(Ce={createElement:D,Fragment:F}).createElement,De=Ce.Fragment,function(e){var t,o,i,a,c,l=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?d(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({title:"Frequently bought together",sliderLabel:"Frequently bought together products"},e.translations),u=null!==(t=e.classNames)&&void 0!==t?t:{},s=null!==(o=e.children)&&void 0!==o?o:_({createElement:Ee,Fragment:De}),m=null!==(i=e.fallbackComponent)&&void 0!==i?i:function(){return null},h=null!==(a=e.headerComponent)&&void 0!==a?a:f({createElement:Ee,Fragment:De}),v=null!==(c=e.view)&&void 0!==c?c:p({createElement:Ee,Fragment:De});return s({classNames:u,Fallback:function(){return Ee(m,{Fragment:De,createElement:Ee})},Header:h,recommendations:e.items,status:e.status,translations:l,View:function(t){return Ee(v,n({classNames:u,itemComponent:e.itemComponent,items:e.items,translations:l,Fragment:De,createElement:Ee},t))}})});function Fe(e){var t=a(se({recommendations:[]}),2),n=t[0],r=t[1],o=Oe("loading"),i=o.status,l=o.setStatus;return ge({recommendClient:e.recommendClient}),me((function(){l("loading"),function(e){var t=e.objectIDs,n=e.recommendClient,r=e.transformItems,o=void 0===r?function(e){return e}:r,i=e.indexName,a=e.maxRecommendations,l=e.queryParameters,u=e.threshold,m=t.map((function(e){return{indexName:i,maxRecommendations:a,objectID:e,queryParameters:l,threshold:u}}));return n.addAlgoliaAgent("recommend-core",s),n.getFrequentlyBoughtTogether(m).then((function(e){return c({maxRecommendations:a,hits:e.results.map((function(e){return e.hits})),nrOfObjs:t.length})})).then((function(e){return{recommendations:o(e)}}))}(e).then((function(e){r(e),l("idle")}))}),[e,l]),ke(ke({},n),{},{status:i})}function Ne(e){var t=Fe(e),r=t.recommendations,o=t.status;return D(Se,n({},e,{items:r,status:o}))}var xe=["container","environment","itemComponent","fallbackComponent","headerComponent","view","children"];function Ae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Ae(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Re=function(e){var t=e.createElement,o=e.Fragment;return function(e){var i,a,c,l,u,s=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?h(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):h(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({title:"Related products",sliderLabel:"Related products"},e.translations),m=null!==(i=e.classNames)&&void 0!==i?i:{},d=null!==(a=e.children)&&void 0!==a?a:_({createElement:t,Fragment:o}),v=null!==(c=e.fallbackComponent)&&void 0!==c?c:function(){return null},b=null!==(l=e.headerComponent)&&void 0!==l?l:f({createElement:t,Fragment:o}),y=null!==(u=e.view)&&void 0!==u?u:p({createElement:t,Fragment:o});return d({classNames:m,Fallback:function(){return t(v,{Fragment:o,createElement:t})},Header:b,recommendations:e.items,status:e.status,translations:s,View:function(r){return t(y,n({classNames:m,itemComponent:e.itemComponent,items:e.items,translations:s,Fragment:o,createElement:t},r))}})}}({createElement:D,Fragment:F});function Te(e){var t=a(se({recommendations:[]}),2),n=t[0],r=t[1],o=Oe("loading"),i=o.status,l=o.setStatus;return ge({recommendClient:e.recommendClient}),me((function(){l("loading"),function(e){var t=e.objectIDs,n=e.recommendClient,r=e.transformItems,o=void 0===r?function(e){return e}:r,i=e.fallbackParameters,a=e.indexName,l=e.maxRecommendations,u=e.queryParameters,m=e.threshold,_=t.map((function(e){return{fallbackParameters:i,indexName:a,maxRecommendations:l,objectID:e,queryParameters:u,threshold:m}}));return n.addAlgoliaAgent("recommend-core",s),n.getRelatedProducts(_).then((function(e){return c({maxRecommendations:l,hits:e.results.map((function(e){return e.hits})),nrOfObjs:t.length})})).then((function(e){return{recommendations:o(e)}}))}(e).then((function(e){r(e),l("idle")}))}),[e,l]),Ie(Ie({},n),{},{status:i})}function He(e){var t=Te(e),r=t.recommendations,o=t.status;return D(Re,n({},e,{items:r,status:o}))}var qe=["container","environment","itemComponent","fallbackComponent","headerComponent","view","children"];function Me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Le(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Me(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Ue=function(e){var t=e.createElement,o=e.Fragment;return function(e){var i,a,c,l,u,s=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?v(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):v(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({title:"Trending facets",sliderLabel:"Trending facets"},e.translations),p=null!==(i=e.classNames)&&void 0!==i?i:{},d=null!==(a=e.children)&&void 0!==a?a:_({createElement:t,Fragment:o}),h=null!==(c=e.fallbackComponent)&&void 0!==c?c:function(){return null},b=null!==(l=e.headerComponent)&&void 0!==l?l:f({createElement:t,Fragment:o}),y=null!==(u=e.view)&&void 0!==u?u:function(e){var t=e.createElement,n=e.Fragment;return function(e){return t("div",{className:m("auc-Recommend-container",e.classNames.container)},t("ol",{className:m("auc-Recommend-list",e.classNames.list)},e.items.map((function(r){return t("li",{key:r.facetValue,className:m("auc-Recommend-item",e.classNames.item)},t(e.itemComponent,{createElement:t,Fragment:n,item:r}))}))))}}({createElement:t,Fragment:o});return d({classNames:p,Fallback:function(){return t(h,{Fragment:o,createElement:t})},Header:b,recommendations:e.items,status:e.status,translations:s,View:function(r){return t(y,n({classNames:p,itemComponent:e.itemComponent,items:e.items,translations:s,Fragment:o,createElement:t},r))}})}}({createElement:D,Fragment:F});function Ve(e){var t=a(se({recommendations:[]}),2),n=t[0],r=t[1],o=Oe("loading"),i=o.status,c=o.setStatus;return ge({recommendClient:e.recommendClient}),me((function(){c("loading"),function(e){var t=e.recommendClient,n=e.transformItems,r=void 0===n?function(e){return e}:n,o=e.fallbackParameters,i=e.indexName,a=e.maxRecommendations,c=e.queryParameters,l=e.threshold,m=e.facetName,_={fallbackParameters:o,indexName:i,maxRecommendations:a,queryParameters:c,threshold:l,facetName:m};return t.addAlgoliaAgent("recommend-core",s),t.getTrendingFacets([_]).then((function(e){return u({maxRecommendations:a,hits:e.results.map((function(e){return e.hits})).flat()})})).then((function(e){return{recommendations:r(e)}}))}(e).then((function(e){r(e),c("idle")}))}),[e,c]),Le(Le({},n),{},{status:i})}function We(e){var t=Ve(e),r=t.recommendations,o=t.status;return D(Ue,n({},e,{items:r,status:o}))}var Be=["container","environment","itemComponent","fallbackComponent","headerComponent","view","children"];function $e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ge(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?$e(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$e(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ze=function(e){var t=e.createElement,o=e.Fragment;return function(e){var i,a,c,l,u,s=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?b(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({title:"Trending items",sliderLabel:"Trending items"},e.translations),m=null!==(i=e.classNames)&&void 0!==i?i:{},d=null!==(a=e.children)&&void 0!==a?a:_({createElement:t,Fragment:o}),h=null!==(c=e.fallbackComponent)&&void 0!==c?c:function(){return null},v=null!==(l=e.headerComponent)&&void 0!==l?l:f({createElement:t,Fragment:o}),y=null!==(u=e.view)&&void 0!==u?u:p({createElement:t,Fragment:o});return d({classNames:m,Fallback:function(){return t(h,{Fragment:o,createElement:t})},Header:v,recommendations:e.items,status:e.status,translations:s,View:function(r){return t(y,n({classNames:m,itemComponent:e.itemComponent,items:e.items,translations:s,Fragment:o,createElement:t},r))}})}}({createElement:D,Fragment:F});function Je(e){var t=a(se({recommendations:[]}),2),n=t[0],r=t[1],o=Oe("loading"),i=o.status,c=o.setStatus;return ge({recommendClient:e.recommendClient}),me((function(){c("loading"),function(e){var t=e.recommendClient,n=e.transformItems,r=void 0===n?function(e){return e}:n,o=e.fallbackParameters,i=e.indexName,a=e.maxRecommendations,c=e.queryParameters,m=e.threshold,_=e.facetName,f=e.facetValue,p={fallbackParameters:o,indexName:i,maxRecommendations:a,queryParameters:c,threshold:m,facetName:_,facetValue:f};return t.addAlgoliaAgent("recommend-core",s),t.getTrendingItems([p]).then((function(e){return u({maxRecommendations:a,hits:(t="objectID",n=e.results.map((function(e){return e.hits})).flat(),l(new Map(n.map((function(e){return[e[t],e]}))).values()))});var t,n})).then((function(e){return{recommendations:r(e)}}))}(e).then((function(e){r(e),c("idle")}))}),[e,c]),Ge(Ge({},n),{},{status:i})}function Ke(e){var t=Je(e),r=t.recommendations,o=t.status;return D(ze,n({},e,{items:r,status:o}))}e.frequentlyBoughtTogether=function(e){var r=e.container,o=e.environment,i=void 0===o?window:o,a=e.itemComponent,c=e.fallbackComponent,l=e.headerComponent,u=e.view,s=e.children,m=D(Ne,n({},t(e,we),{view:u&&je(u),itemComponent:a&&je(a),headerComponent:l&&je(l),fallbackComponent:c&&je(c)}),s?function(e){return s(ke(ke({},e),{},{html:te}))}:void 0);return r?(K(m,ye(r,i)),null):m},e.relatedProducts=function(e){var r=e.container,o=e.environment,i=void 0===o?window:o,a=e.itemComponent,c=e.fallbackComponent,l=e.headerComponent,u=e.view,s=e.children,m=D(He,n({},t(e,xe),{view:u&&je(u),itemComponent:a&&je(a),headerComponent:l&&je(l),fallbackComponent:c&&je(c)}),s?function(e){return s(Ie(Ie({},e),{},{html:te}))}:void 0);return r?(K(m,ye(r,i)),null):m},e.trendingFacets=function(e){var r=e.container,o=e.environment,i=void 0===o?window:o,a=e.itemComponent,c=e.fallbackComponent,l=e.headerComponent,u=e.view,s=e.children,m=D(We,n({},t(e,qe),{view:u&&je(u),itemComponent:a&&je(a),headerComponent:l&&je(l),fallbackComponent:c&&je(c)}),s?function(e){return s(Le(Le({},e),{},{html:te}))}:void 0);return r?(K(m,ye(r,i)),null):m},e.trendingItems=function(e){var r=e.container,o=e.environment,i=void 0===o?window:o,a=e.itemComponent,c=e.fallbackComponent,l=e.headerComponent,u=e.view,s=e.children,m=D(Ke,n({},t(e,Be),{view:u&&je(u),itemComponent:a&&je(a),headerComponent:l&&je(l),fallbackComponent:c&&je(c)}),s?function(e){return s(Ge(Ge({},e),{},{html:te}))}:void 0);return r?(K(m,ye(r,i)),null):m},Object.defineProperty(e,"__esModule",{value:!0})}));

define('Algolia_AlgoliaSearch/recommend', [
    'algoliaBundle',
    'recommend',
    'recommendJs',
    'recommendProductsHtml',
    'domReady!'
],function (algoliaBundle, recommend, recommendJs, recommendProductsHtml) {
    'use strict';

    if (typeof algoliaConfig === 'undefined') {
        return;
    }

    return function (config, element) {
        algoliaBundle.$(function ($) {
            this.defaultIndexName = algoliaConfig.indexName + '_products';
            const appId = algoliaConfig.applicationId;
            const apiKey = algoliaConfig.apiKey;
            const recommendClient = recommend(appId, apiKey);
            const indexName = this.defaultIndexName;
            if ($('body').hasClass('catalog-product-view') || $('body').hasClass('checkout-cart-index')) {
                // --- Add the current product objectID here ---
                if ((algoliaConfig.recommend.enabledFBT && $('body').hasClass('catalog-product-view')) || (algoliaConfig.recommend.enabledFBTInCart && $('body').hasClass('checkout-cart-index'))) {
                    recommendJs.frequentlyBoughtTogether({
                        container: '#frequentlyBoughtTogether',
                        recommendClient,
                        indexName,
                        objectIDs: config.algoliObjectId,
                        maxRecommendations: algoliaConfig.recommend.limitFBTProducts,
                        transformItems:function (items) {
                            return items.map((item, index) => ({
                                ...item,
                                position: index + 1,
                            }));
                        },
                        headerComponent({html}) {
                            return recommendProductsHtml.getHeaderHtml(html,algoliaConfig.recommend.FBTTitle);
                        },
                        itemComponent({item, html}) {
                            return recommendProductsHtml.getItemHtml(item, html, algoliaConfig.recommend.isAddToCartEnabledInFBT);
                        },
                    });
                }
                if ((algoliaConfig.recommend.enabledRelated && $('body').hasClass('catalog-product-view')) || (algoliaConfig.recommend.enabledRelatedInCart && $('body').hasClass('checkout-cart-index'))) {
                    recommendJs.relatedProducts({
                        container: '#relatedProducts',
                        recommendClient,
                        indexName,
                        objectIDs: config.algoliObjectId,
                        maxRecommendations: algoliaConfig.recommend.limitRelatedProducts,
                        transformItems:function (items) {
                            return items.map((item, index) => ({
                                ...item,
                                position: index + 1,
                            }));
                        },
                        headerComponent({html}) {
                            return recommendProductsHtml.getHeaderHtml(html,algoliaConfig.recommend.relatedProductsTitle);
                        },
                        itemComponent({item, html}) {
                            return recommendProductsHtml.getItemHtml(item, html, algoliaConfig.recommend.isAddToCartEnabledInRelatedProduct);
                        },
                    });
                }
            }

            if ((algoliaConfig.recommend.isTrendItemsEnabledInPDP && $('body').hasClass('catalog-product-view')) || (algoliaConfig.recommend.isTrendItemsEnabledInCartPage && $('body').hasClass('checkout-cart-index'))) {
                recommendJs.trendingItems({
                    container: '#trendItems',
                    facetName: algoliaConfig.recommend.trendItemFacetName ? algoliaConfig.recommend.trendItemFacetName : '',
                    facetValue: algoliaConfig.recommend.trendItemFacetValue ? algoliaConfig.recommend.trendItemFacetValue : '',
                    recommendClient,
                    indexName,
                    maxRecommendations: algoliaConfig.recommend.limitTrendingItems,
                    transformItems:function (items) {
                        return items.map((item, index) => ({
                            ...item,
                            position: index + 1,
                        }));
                    },
                    headerComponent({html}) {
                        return recommendProductsHtml.getHeaderHtml(html,algoliaConfig.recommend.trendingItemsTitle);
                    },
                    itemComponent({item, html}) {
                        return recommendProductsHtml.getItemHtml(item, html, algoliaConfig.recommend.isAddToCartEnabledInTrendsItem);
                    },
                });
            } else if (algoliaConfig.recommend.enabledTrendItems && typeof config.recommendTrendContainer !== "undefined") {
                let containerValue = "#" + config.recommendTrendContainer;
                recommendJs.trendingItems({
                    container: containerValue,
                    facetName: config.facetName ? config.facetName : '',
                    facetValue: config.facetValue ? config.facetValue : '',
                    recommendClient,
                    indexName,
                    maxRecommendations: config.numOfTrendsItem ? parseInt(config.numOfTrendsItem) : algoliaConfig.recommend.limitTrendingItems,
                    transformItems:function (items) {
                        return items.map((item, index) => ({
                            ...item,
                            position: index + 1,
                        }));
                    },
                    headerComponent({html}) {
                        return recommendProductsHtml.getHeaderHtml(html,algoliaConfig.recommend.trendingItemsTitle);
                    },
                    itemComponent({item, html}) {
                        return recommendProductsHtml.getItemHtml(item, html, algoliaConfig.recommend.isAddToCartEnabledInTrendsItem);
                    },
                });
            }
        });
    }
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('mage/validation/validation', [
    'jquery',
    'mage/validation',
    'mage/translate'
], function ($) {
    'use strict';

    $.each({
        'validate-grouped-qty': [
            function (value, element, params) {
                var result = false,
                    total = 0;

                $(params).find('input[data-validate*="validate-grouped-qty"]').each(function (i, e) {
                    var val = $(e).val(),
                        valInt;

                    if (val && val.length > 0) {
                        result = true;
                        valInt = parseFloat(val) || 0;

                        if (valInt >= 0) {
                            total += valInt;
                        } else {
                            result = false;

                            return result;
                        }
                    }
                });

                return result && total > 0;
            },
            $.mage.__('Please specify the quantity of product(s).')
        ],
        'validate-one-checkbox-required-by-name': [
            function (value, element, params) {
                var checkedCount = 0,
                    container;

                if (element.type === 'checkbox') {
                    $('[name="' + element.name + '"]').each(
                        function () {
                            if ($(this).is(':checked')) {
                                checkedCount += 1;

                                return false;
                            }
                        }
                    );
                }
                container = '#' + params;

                if (checkedCount > 0) {
                    $(container).removeClass('validation-failed');
                    $(container).addClass('validation-passed');

                    return true;
                }
                $(container).addClass('validation-failed');
                $(container).removeClass('validation-passed');

                return false;
            },
            $.mage.__('Please select one of the options.')
        ],
        'validate-date-between': [
            function (value, element, params) {
                var minDate = new Date(params[0]),
                    maxDate = new Date(params[1]),
                    inputDate = new Date(element.value),
                    message;

                minDate.setHours(0);
                maxDate.setHours(0);

                if (inputDate >= minDate && inputDate <= maxDate) {
                    return true;
                }
                message = $.mage.__('Please enter a date between %min and %max.');
                this.dateBetweenErrorMessage = message.replace('%min', minDate).replace('%max', maxDate);

                return false;
            },
            function () {
                return this.dateBetweenErrorMessage;
            }
        ],
        'validate-dob': [
            function (val, element, params) {
                var dob = $(element).parents('.customer-dob'),
                    dayVal, monthVal, yearVal, dobLength, day, month, year, curYear,
                    validYearMessage, validateDayInMonth, validDateMessage, today, dateEntered;

                $(dob).find('.' + this.settings.errorClass).removeClass(this.settings.errorClass);
                dayVal = $(dob).find(params[0]).find('input:text').val();
                monthVal = $(dob).find(params[1]).find('input:text').val();
                yearVal = $(dob).find(params[2]).find('input:text').val();
                dobLength = dayVal.length + monthVal.length + yearVal.length;

                if (params[3] && dobLength === 0) {
                    this.dobErrorMessage = $.mage.__('This is a required field.');

                    return false;
                }

                if (!params[3] && dobLength === 0) {
                    return true;
                }
                day = parseInt(dayVal, 10) || 0;
                month = parseInt(monthVal, 10) || 0;
                year = parseInt(yearVal, 10) || 0;
                curYear = new Date().getFullYear();

                if (!day || !month || !year) {
                    this.dobErrorMessage = $.mage.__('Please enter a valid full date.');

                    return false;
                }

                if (month < 1 || month > 12) {
                    this.dobErrorMessage = $.mage.__('Please enter a valid month (1-12).');

                    return false;
                }

                if (year < 1900 || year > curYear) {
                    validYearMessage = $.mage.__('Please enter a valid year (1900-%1).');
                    this.dobErrorMessage = validYearMessage.replace('%1', curYear.toString());

                    return false;
                }
                validateDayInMonth = new Date(year, month, 0).getDate();

                if (day < 1 || day > validateDayInMonth) {
                    validDateMessage = $.mage.__('Please enter a valid day (1-%1).');
                    this.dobErrorMessage = validDateMessage.replace('%1', validateDayInMonth.toString());

                    return false;
                }
                today = new Date();
                dateEntered = new Date();
                dateEntered.setFullYear(year, month - 1, day);

                if (dateEntered > today) {
                    this.dobErrorMessage = $.mage.__('Please enter a date from the past.');

                    return false;
                }

                day = day % 10 === day ? '0' + day : day;
                month = month % 10 === month ? '0' + month : month;
                $(element).val(month + '/' + day + '/' + year);

                return true;
            },
            function () {
                return this.dobErrorMessage;
            }
        ]
    }, function (i, rule) {
        rule.unshift(i);
        $.validator.addMethod.apply($.validator, rule);
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/shopping-cart', [
    'jquery',
    'Magento_Ui/js/modal/confirm',
    'jquery-ui-modules/widget',
    'mage/translate'
], function ($, confirm) {
    'use strict';

    $.widget('mage.shoppingCart', {
        /** @inheritdoc */
        _create: function () {
            var items, i, reload;

            $(this.options.emptyCartButton).on('click', $.proxy(function () {
                this._confirmClearCart();
            }, this));
            items = $.find('[data-role="cart-item-qty"]');

            for (i = 0; i < items.length; i++) {
                $(items[i]).on('keypress', $.proxy(function (event) { //eslint-disable-line no-loop-func
                    var keyCode = event.keyCode ? event.keyCode : event.which;

                    if (keyCode == 13) { //eslint-disable-line eqeqeq
                        $(this.options.emptyCartButton).attr('name', 'update_cart_action_temp');
                        $(this.options.updateCartActionContainer)
                            .attr('name', 'update_cart_action').attr('value', 'update_qty');

                    }
                }, this));
            }
            $(this.options.continueShoppingButton).on('click', $.proxy(function () {
                location.href = this.options.continueShoppingUrl;
            }, this));

            $(document).on('ajax:removeFromCart', $.proxy(function () {
                reload = true;
                $('div.block.block-minicart').on('dropdowndialogclose', $.proxy(function () {
                    if (reload === true) {
                        location.reload();
                        reload = false;
                    }
                    $('div.block.block-minicart').off('dropdowndialogclose');
                }));
            }, this));
            $(document).on('ajax:updateItemQty', $.proxy(function () {
                reload = true;
                $('div.block.block-minicart').on('dropdowndialogclose', $.proxy(function () {
                    if (reload === true) {
                        location.reload();
                        reload = false;
                    }
                    $('div.block.block-minicart').off('dropdowndialogclose');
                }));
            }, this));
        },

        /**
         * Display confirmation modal for clearing the cart
         * @private
         */
        _confirmClearCart: function () {
            var self = this;

            confirm({
                content: $.mage.__('Are you sure you want to remove all items from your shopping cart?'),
                actions: {
                    /**
                     * Confirmation modal handler to execute clear cart action
                     */
                    confirm: function () {
                        self.clearCart();
                    }
                }
            });
        },

        /**
         * Prepares the form and submit to clear the cart
         * @public
         */
        clearCart: function () {
            $(this.options.emptyCartButton).attr('name', 'update_cart_action_temp');
            $(this.options.updateCartActionContainer)
                .attr('name', 'update_cart_action').attr('value', 'empty_cart');

            if ($(this.options.emptyCartButton).parents('form').length > 0) {
                $(this.options.emptyCartButton).parents('form').trigger('submit');
            }
        }
    });

    return $.mage.shoppingCart;
});

"use strict";

define('Magento_Checkout/js/cart-methods.babel', ['jquery', 'Magento_Customer/js/customer-data'], ($, customerData) => {
  const cart = customerData.get('cart');
  return (config, element) => {
    let elPayPal = element.querySelector('.paypal-express-in-context-mini-cart-container');
    $(window).on('addtocartclick', () => {
      if (elPayPal) {
        elPayPal.style.display = 'none';
      }
    });
    cart.subscribe(c => {
      if (!c.extra_actions) {
        if (elPayPal) {
          elPayPal.parentElement.removeChild(elPayPal);
          elPayPal = null;
        }
      } else {
        if (elPayPal) {
          elPayPal.style.display = '';
        }
      }
    });
  };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/discount-codes', [
    'jquery',
    'jquery-ui-modules/widget'
], function ($) {
    'use strict';

    $.widget('mage.discountCode', {
        options: {
        },

        /** @inheritdoc */
        _create: function () {
            this.couponCode = $(this.options.couponCodeSelector);
            this.removeCoupon = $(this.options.removeCouponSelector);

            $(this.options.applyButton).on('click', $.proxy(function () {
                this.couponCode.attr('data-validate', '{required:true}');
                this.removeCoupon.attr('value', '0');
                $(this.element).validation().trigger('submit');
            }, this));

            $(this.options.cancelButton).on('click', $.proxy(function () {
                this.couponCode.removeAttr('data-validate');
                this.removeCoupon.attr('value', '1');
                this.element.trigger('submit');
            }, this));
        }
    });

    return $.mage.discountCode;
});

define('MediaLounge_TagManager/js/checkout/error.babel', [
    'jquery',
    'dataLayers'
], ($, e) => {
    'use strict';

    return function (config, element) {

        let elMessagesItems,
            elMessages = document.querySelector('.page.messages');

        const pushMessage = function(el) {
            try {
                let errorMsg = el.textContent;
                e.addError(errorMsg)
            } catch (error) {
                // error
            }
        }

        const checkMessages = function(el) {
            if (el) {
                elMessagesItems = el.querySelectorAll(".message-warning, .message-error");
                elMessagesItems.forEach(message => pushMessage(message));
            }
        }

        if (!elMessages) {
            setTimeout(() => {
                elMessages = document.querySelector('.checkout-messages');
                checkMessages(elMessages);
            }, 5000);
        } else {
            checkMessages(elMessages);
        }

    };

});


define('Aheadworks_Giftcard/js/widget/giftcardManagement', [
    'jquery'
], function($){
    'use strict';

    $.widget('mage.awGiftCardManagement', {
        options: {
            checkCodeSelector: '[data-role=aw-giftcard-check-code-action]',
            applyCodeSelector: '[data-role=aw-giftcard-apply-action]',
            resultSelector: '#aw_giftcard__code_info'
        },

        /**
         * Initialize widget
         */
        _create: function() {
            this._bind();
        },

        /**
         * Event binding
         */
        _bind: function () {
            var handlers = {};

            handlers['click ' + this.options.checkCodeSelector] = this._onClickCheckCode;
            handlers['click ' + this.options.applyCodeSelector] = this._onSubmitForm;
            this._on(handlers);
        },

        /**
         * Click on check code action
         *
         * @param {Object} event
         * @private
         */
        _onClickCheckCode: function(event) {
            event.preventDefault();
            $(this.options.resultSelector).html('');
            if (!this.validate()) {
                return;
            }
            var self = this,
                data = $(this.element).serializeArray(),
                url = $(this.options.checkCodeSelector).data('url');

            $('body').trigger('processStart');
            $.ajax({
                url: url,
                data: data,
                method: 'post',
                context: this
            }).success(function(response) {
                if (response) {
                    $(self.options.resultSelector).html(response);
                }
            }).always(function() {
                $('body').trigger('processStop');
            });
        },

        /**
         * Click on apply code action
         *
         * @param {Object} event
         * @private
         */
        _onSubmitForm: function(event) {
            event.preventDefault();
            var url = $(this.options.applyCodeSelector).data('url');

            if (!this.validate()) {
                return;
            }

            $('body').trigger('processStart');
            $(this.element).attr('action', url).submit();
        },

        /**
         * Coupon form validation
         *
         * @returns {Boolean}
         */
        validate: function () {
            return $(this.element) && $(this.element).validation() && $(this.element).validation('isValid');
        }
    });

    return $.mage.awGiftCardManagement;
});

/**
 * Copyright © 2019 Media Lounge. All rights reserved.
 */
define('MediaLounge_TagManager/js/checkout/cart.babel', [
    'jquery',
    'Magento_Customer/js/section-config',
    'dataLayers',
    'mage/url'
], ($, sectionConfig, e, url) => {

    return function (config, element) {

        config.step = 1;
        e.onePageCheckout(config);

        let $el = $('#shopping-cart-table');

        $el.on('click', '.qty-decr', (ev) => {

            let $elem = $(ev.target),
                $entity = $elem.closest('.control').find('[data-role="cart-item-qty"]'),
                entityId = $entity.data('entity-id');

            $.ajax({
                url: url.build(`tagmanager/index/product/id/${entityId}`),
                contentType: "application/json",
                dataType: 'json',
                success: function (result) {
                    let product = result;
                    product.currency = `${config.currency}`;
                    e.removeProduct(product);
                }
            });
        });

        $el.on('click', '.qty-incr', (ev) => {

            let $elem = $(ev.target),
                $entity = $elem.closest('.control').find('[data-role="cart-item-qty"]'),
                entityId = $entity.data('entity-id'),
                qty = $entity.val(),
                count = $entity.data('item-qty-old');

            $.ajax({
                url: url.build(`tagmanager/index/product/id/${entityId}`),
                contentType: "application/json",
                dataType: 'json',
                success: function (result) {
                    let product = result;
                    product.qty = `${qty}`;
                    product.currency = `${config.currency}`;
                    e.updateProduct(product, `${count}`);
                }
            });
        });

        $(document).on('ajax:couponFailure', (event, data) => {
            const coupon = {};
            let msg = JSON.parse(data.message);

            coupon.code = $('#discount-code').val();
            coupon.message = msg.message;
            e.discountFailure(coupon);
        });

        $(document).on('ajax:couponSuccess', (event, data) => {
            const coupon = {};
            coupon.code = $('#discount-code').val();

            e.discountApply(coupon);
        });
    }
});

define('MediaLounge_UpSell/js/upsell.babel', [
    'Magento_Customer/js/customer-data'
], (
    customerData
 ) => {

    return (config, element) => {
        const cartData = customerData.get('cart');
        const elTableRows = document.querySelectorAll('.cart-items-item[data-sku]');

        function updateUpsell()
        {
            let showUpsell = true;

            // Check the cart data object
            if (cartData && cartData().items)
            {
                cartData().items.forEach(item => {
                    if (item.product_sku === config.sku)
                    {
                        showUpsell = false;
                    }
                });
            }

            // Check the basket markup
            [...elTableRows].forEach(item => {
                if (item.dataset.sku === config.sku)
                {
                    showUpsell = false;
                }
            });

            if (showUpsell)
            {
                element.classList.remove('__hidden');
            } else
            {
                element.classList.add('__hidden');
            }
        }

        cartData.subscribe(updateUpsell);

        updateUpsell()
    };
});
define('Magento_Checkout/js/action/update-shopping-cart-mixin', ['jquery'], $ => {
    const mixin = {
        /** @inheritdoc */
        _create: function () {
            this._super();

            this.element
                .on('change.qty', 'select.qty', () => {
                    this.onChange();
                });
        },
        onChange: function () {
            if (this.isValid()) {
                this.validateItems(this.options.validationURL, this.element.serialize());
            }
        }
    };
    return target => {
        $.widget('mage.updateShoppingCart', target, mixin);
        return $.mage.updateShoppingCart;
    }
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/proceed-to-checkout', [
    'jquery',
    'Magento_Customer/js/model/authentication-popup',
    'Magento_Customer/js/customer-data'
], function ($, authenticationPopup, customerData) {
    'use strict';

    return function (config, element) {
        $(element).on('click', function (event) {
            var cart = customerData.get('cart'),
                customer = customerData.get('customer');

            event.preventDefault();

            if (!customer().firstname && cart().isGuestCheckoutAllowed === false) {
                authenticationPopup.showModal();

                return false;
            }
            $(element).attr('disabled', true);
            location.href = config.checkoutUrl;
        });

    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/action/update-shopping-cart', [
    'Magento_Ui/js/modal/alert',
    'jquery',
    'jquery-ui-modules/widget',
    'mage/validation'
], function (alert, $) {
    'use strict';

    $.widget('mage.updateShoppingCart', {
        options: {
            validationURL: '',
            eventName: 'updateCartItemQty',
            updateCartActionContainer: ''
        },

        /** @inheritdoc */
        _create: function () {
            this._on(this.element, {
                'submit': this.onSubmit
            });
        },

        /**
         * Prevents default submit action and calls form validator.
         *
         * @param {Event} event
         * @return {Boolean}
         */
        onSubmit: function (event) {
            var action = this.element.find(this.options.updateCartActionContainer).val();

            if (!this.options.validationURL || action === 'empty_cart') {
                return true;
            }

            if (this.isValid()) {
                event.preventDefault();
                this.validateItems(this.options.validationURL, this.element.serialize());
            }

            return false;
        },

        /**
         * Validates requested form.
         *
         * @return {Boolean}
         */
        isValid: function () {
            return this.element.validation() && this.element.validation('isValid');
        },

        /**
         * Validates updated shopping cart data.
         *
         * @param {String} url - request url
         * @param {Object} data - post data for ajax call
         */
        validateItems: function (url, data) {
            $.extend(data, {
                'form_key': $.mage.cookies.get('form_key')
            });

            $.ajax({
                url: url,
                data: data,
                type: 'post',
                dataType: 'json',
                context: this,

                /** @inheritdoc */
                beforeSend: function () {
                    $(document.body).trigger('processStart');
                },

                /** @inheritdoc */
                complete: function () {
                    $(document.body).trigger('processStop');
                }
            })
            .done(function (response) {
                if (response.success) {
                    this.onSuccess();
                } else {
                    this.onError(response);
                }
            })
            .fail(function () {
                this.submitForm();
            });
        },

        /**
         * Form validation succeed.
         */
        onSuccess: function () {
            $(document).trigger('ajax:' + this.options.eventName);
            this.submitForm();
        },

        /**
         * Form validation failed.
         */
        onError: function (response) {
            var that = this,
                elm,
                responseData = JSON.parse(response['error_message']);

            if (response['error_message']) {
                try {
                    $.each(responseData, function (index, data) {

                        if (data.itemId !== undefined) {
                            elm = $('#cart-' + data.itemId + '-qty');
                            elm.val(elm.attr('data-item-qty'));
                        }
                        response['error_message'] = data.error;
                    });
                } catch (e) {}
                alert({
                    content: response['error_message'],
                    actions: {
                        /** @inheritdoc */
                        always: function () {
                            that.submitForm();
                        }
                    }
                });
            } else {
                this.submitForm();
            }
        },

        /**
         * Real submit of validated form.
         */
        submitForm: function () {
            this.element
                .off('submit', this.onSubmit)
                .on('submit', function () {
                    $(document.body).trigger('processStart');
                })
                .trigger('submit');
        }
    });

    return $.mage.updateShoppingCart;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Wishlist/js/wishlist', [
    'jquery',
    'mage/template',
    'Magento_Ui/js/modal/alert',
    'jquery-ui-modules/widget',
    'mage/validation/validation',
    'mage/dataPost'
], function ($, mageTemplate, alert) {
    'use strict';

    $.widget('mage.wishlist', {
        options: {
            dataAttribute: 'item-id',
            nameFormat: 'qty[{0}]',
            btnRemoveSelector: '[data-role=remove]',
            qtySelector: '[data-role=qty]',
            addToCartSelector: '[data-role=tocart]',
            addAllToCartSelector: '[data-role=all-tocart]',
            commentInputType: 'textarea',
            infoList: false
        },

        /**
         * Bind handlers to events.
         */
        _create: function () {
            var _this = this;

            if (!this.options.infoList) {
                this.element
                    .on('addToCart', function (event, context) {
                        var urlParams;

                        event.stopPropagation(event);
                        $(context).data('stop-processing', true);
                        urlParams = _this._getItemsToCartParams(
                            $(context).parents('[data-row=product-item]').find(_this.options.addToCartSelector)
                        );
                        $.mage.dataPost().postData(urlParams);

                        return false;
                    })
                    .on('click', this.options.btnRemoveSelector, $.proxy(function (event) {
                        event.preventDefault();
                        $.mage.dataPost().postData($(event.currentTarget).data('post-remove'));
                    }, this))
                    .on('click', this.options.addToCartSelector, $.proxy(this._beforeAddToCart, this))
                    .on('click', this.options.addAllToCartSelector, $.proxy(this._addAllWItemsToCart, this))
                    .on('focusin focusout', this.options.commentInputType, $.proxy(this._focusComment, this));
            }

            // Setup validation for the form
            this.element.mage('validation', {
                /** @inheritdoc */
                errorPlacement: function (error, element) {
                    error.insertAfter(element.next());
                }
            });
        },

        /**
         * Process data before add to cart
         *
         * - update item's qty value.
         *
         * @param {Event} event
         * @private
         */
        _beforeAddToCart: function (event) {
            var elem = $(event.currentTarget),
                itemId = elem.data(this.options.dataAttribute),
                qtyName = $.validator.format(this.options.nameFormat, itemId),
                qtyValue = elem.parents().find('[name="' + qtyName + '"]').val(),
                params = elem.data('post');

            if (params) {
                params.data = $.extend({}, params.data, {
                    'qty': qtyValue
                });
                elem.data('post', params);
            }
        },

        /**
         * Add wish list items to cart.
         * @private
         * @param {jQuery} elem - clicked 'add to cart' button
         */
        _getItemsToCartParams: function (elem) {
            var itemId, url, qtyName, qtyValue;

            if (elem.data(this.options.dataAttribute)) {
                itemId = elem.data(this.options.dataAttribute);
                url = this.options.addToCartUrl;
                qtyName = $.validator.format(this.options.nameFormat, itemId);
                qtyValue = elem.parents().find('[name="' + qtyName + '"]').val();
                url.data.item = itemId;
                url.data.qty = qtyValue;

                return url;
            }
        },

        /**
         * Add all wish list items to cart
         * @private
         */
        _addAllWItemsToCart: function () {
            var urlParams = this.options.addAllToCartUrl,
                separator = urlParams.action.indexOf('?') >= 0 ? '&' : '?';

            this.element.find(this.options.qtySelector).each(function (index, element) {
                urlParams.action += separator + $(element).prop('name') + '=' + encodeURIComponent($(element).val());
                separator = '&';
            });
            $.mage.dataPost().postData(urlParams);
        },

        /**
         * Toggle comment string.
         * @private
         * @param {Event} e
         */
        _focusComment: function (e) {
            var commentInput = e.currentTarget;

            if (commentInput.value === '' || commentInput.value === this.options.commentString) {
                commentInput.value = commentInput.value === this.options.commentString ?
                    '' : this.options.commentString;
            }
        }
    });

    // Extension for mage.wishlist - Select All checkbox
    $.widget('mage.wishlist', $.mage.wishlist, {
        options: {
            selectAllCheckbox: '#select-all',
            parentContainer: '#wishlist-table'
        },

        /** @inheritdoc */
        _create: function () {
            var selectAllCheckboxParent, checkboxCount;

            this._super();
            selectAllCheckboxParent = $(this.options.selectAllCheckbox).parents(this.options.parentContainer);
            checkboxCount = selectAllCheckboxParent
                .find('input:checkbox:not(' + this.options.selectAllCheckbox + ')').length;
            // If Select all checkbox is checked, check all item checkboxes, if unchecked, uncheck all item checkboxes
            $(this.options.selectAllCheckbox).on('click', function () {
                selectAllCheckboxParent.find('input:checkbox').attr('checked', $(this).is(':checked'));
            });
            // If all item checkboxes are checked, check select all checkbox,
            // if not all item checkboxes are checked, uncheck select all checkbox
            selectAllCheckboxParent.on(
                'click',
                'input:checkbox:not(' + this.options.selectAllCheckbox + ')',
                $.proxy(function () {
                    var checkedCount = selectAllCheckboxParent
                        .find('input:checkbox:checked:not(' + this.options.selectAllCheckbox + ')').length;

                    $(this.options.selectAllCheckbox).attr('checked', checkboxCount === checkedCount);
                }, this)
            );
        }
    });
    // Extension for mage.wishlist info add to cart
    $.widget('mage.wishlist', $.mage.wishlist, {
        /** @inheritdoc */
        _create: function () {
            this._super();

            if (this.options.infoList) {
                this.element.on('addToCart', $.proxy(function (event, context) {
                    this.element.find('input:checkbox').attr('checked', false);
                    $(context).closest('tr').find('input:checkbox').attr('checked', true);
                    this.element.trigger('submit');
                }, this));
                this._checkBoxValidate();
            }
        },

        /**
         * validate checkbox selection.
         * @private
         */
        _checkBoxValidate: function () {
            this.element.validation({
                submitHandler: $.proxy(function (form) {
                    if ($(form).find('input:checkbox:checked').length) {
                        form.submit();
                    } else {
                        alert({
                            content: this.options.checkBoxValidationMessage
                        });
                    }
                }, this)
            });
        }
    });

    // Extension for mage.wishlist - Add Wishlist item to Gift Registry
    $.widget('mage.wishlist', $.mage.wishlist, {
        options: {
            formTmplSelector: '#form-tmpl',
            formTmplId: '#wishlist-hidden-form'
        },

        /** @inheritdoc */
        _create: function () {
            var _this = this;

            this._super();
            this.element.on('click', '[data-wishlist-to-giftregistry]', function () {
                var json = $(this).data('wishlist-to-giftregistry'),
                    tmplJson = {
                        item: json.itemId,
                        entity: json.entity,
                        url: json.url
                    },
                    html = mageTemplate(_this.options.formTmplSelector, {
                        data: tmplJson
                    });

                $(html).appendTo('body');
                $(_this.options.formTmplId).trigger('submit');
            });
        }
    });

    return $.mage.wishlist;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Paypal/js/in-context/paypal-sdk', [
    'jquery'
], function ($) {
    'use strict';

    var dfd = $.Deferred();

    /**
     * Loads the PayPal SDK object
     * @param {String} paypalUrl - the url of the PayPal SDK
     * @param {Array} dataAttributes - Array of the Attributes for PayPal SDK Script tag
     */
    return function loadPaypalScript(paypalUrl, dataAttributes) {
        //configuration for loaded PayPal script
        require.config({
            paths: {
                paypalSdk: paypalUrl
            },
            shim: {
                paypalSdk: {
                    exports: 'paypal'
                }
            },
            attributes: {
                'paypalSdk': dataAttributes
            },

            /**
             * Add attributes under Paypal SDK Script tag
             */
            onNodeCreated: function (node, config, name) {
                if (config.attributes && config.attributes[name]) {
                    $.each(dataAttributes, function (index, elem) {
                        node.setAttribute(index, elem);
                    });
                }
            }
        });

        if (dfd.state() !== 'resolved') {
            require(['paypalSdk'], function (paypalObject) {
                delete window.paypal;
                dfd.resolve(paypalObject);
            });
        }

        return dfd.promise();
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/* eslint-disable max-nested-callbacks */
define('Magento_Paypal/js/in-context/express-checkout-smart-buttons', [
    'underscore',
    'jquery',
    'Magento_Paypal/js/in-context/paypal-sdk',
    'domReady!'
], function (_, $, paypalSdk) {
    'use strict';

    var lang = LOCALE.slice(0, LOCALE.indexOf('-'));

    var paypalMethodsInitialised = [];

    /**
     * Triggers beforePayment action on PayPal buttons
     *
     * @param {Object} clientConfig
     * @returns {Object} jQuery promise
     */
    function performCreateOrder(clientConfig) {
        var params = {
            'quote_id': clientConfig.quoteId,
            'customer_id': clientConfig.customerId || '',
            'form_key': clientConfig.formKey,
            button: clientConfig.button
        };

        return $.Deferred(function (deferred) {
            clientConfig.rendererComponent.beforePayment(deferred.resolve, deferred.reject).then(function () {
                $.post(clientConfig.getTokenUrl, params).done(function (res) {
                    clientConfig.rendererComponent.afterPayment(res, deferred.resolve, deferred.reject);
                }).fail(function (jqXHR, textStatus, err) {
                    clientConfig.rendererComponent.catchPayment(err, deferred.resolve, deferred.reject);
                });
            });
        }).promise();
    }

    /**
     * Triggers beforeOnAuthorize action on PayPal buttons
     * @param {Object} clientConfig
     * @param {Object} data
     * @param {Object} actions
     * @returns {Object} jQuery promise
     */
    function performOnApprove(clientConfig, data, actions) {
        var params = {
            paymentToken: data.orderID,
            payerId: data.payerID,
            'form_key': clientConfig.formKey,
            paypalFundingSource: data.paymentSource
        };

        return $.Deferred(function (deferred) {
            clientConfig.rendererComponent.beforeOnAuthorize(deferred.resolve, deferred.reject, actions)
                .then(function () {
                    $.post(clientConfig.onAuthorizeUrl, params).done(function (res) {
                        clientConfig.rendererComponent
                            .afterOnAuthorize(res, deferred.resolve, deferred.reject, actions);
                    }).fail(function (jqXHR, textStatus, err) {
                        clientConfig.rendererComponent.catchOnAuthorize(err, deferred.resolve, deferred.reject);
                    });
                });
        }).promise();
    }

    function initPaypalSdk(clientConfig, element) {
        paypalSdk(clientConfig.sdkUrl).done(function (paypal) {
            const config = {
                style: clientConfig.styles,

                /**
                 * onInit is called when the button first renders
                 * @param {Object} data
                 * @param {Object} actions
                 */
                onInit: function (data, actions) {
                    clientConfig.rendererComponent.validate(actions);
                },

                /**
                 * Triggers beforePayment action on PayPal buttons
                 * @returns {Object} jQuery promise
                 */
                createOrder: function () {
                    return performCreateOrder(clientConfig);
                },

                /**
                 * Triggers beforeOnAuthorize action on PayPal buttons
                 * @param {Object} data
                 * @param {Object} actions
                 */
                onApprove: function (data, actions) {
                    performOnApprove(clientConfig, data, actions);
                },

                /**
                 * Execute logic on Paypal button click
                 */
                onClick: function () {
                    clientConfig.rendererComponent.validate();
                    clientConfig.rendererComponent.onClick();
                },

                /**
                 * Process cancel action
                 * @param {Object} data
                 * @param {Object} actions
                 */
                onCancel: function (data, actions) {
                    clientConfig.rendererComponent.onCancel(data, actions);
                },

                /**
                 * Process errors
                 *
                 * @param {Error} err
                 */
                onError: function (err) {
                    clientConfig.rendererComponent.onError(err);
                }
            };

            for (const fundingSourceKey in paypal.FUNDING) {
                const fundingSource = paypal.FUNDING[fundingSourceKey];
                const instanceConfig = { ...config, fundingSource: fundingSource };

                if (fundingSource === paypal.FUNDING.SEPA)
                {
                    continue;
                }

                if (fundingSource !== paypal.FUNDING.CARD
                    && element.classList.contains('--card'))
                {
                    continue;
                }

                if (fundingSource === paypal.FUNDING.CARD
                    && !element.classList.contains('--card'))
                {
                    continue;
                }

                if (fundingSource === paypal.FUNDING.CARD)
                {
                    instanceConfig.style.color = 'black';
                }

                const btn = paypal.Buttons(instanceConfig);

                if (btn.isEligible())
                {
                    btn.render(element);
                }
            }
        });
    }

    function updatePaypalLocale(sdkUrl, countryCode) {
        if ( PAYPAL_ALLOWED_LOCALES.includes(lang + '_' + countryCode)) {
            return sdkUrl.replace(/(locale=[^&]*)/, 'locale=' + lang + '_' + countryCode);
        } else {
            return sdkUrl;
        }
    }

    return function (clientConfig, element) {

        if (typeof PAYPAL_ALLOWED_LOCALES !== 'undefined') {
            require([
                'Magento_Checkout/js/model/quote',
                'Magento_Customer/js/model/customer',
                'Magento_Customer/js/model/address-list',
            ], function(quote, customer, addressList){
                // get the default billing address if the logged in customer has it
                if (customer.isLoggedIn() && addressList().length) {
                    addressList().find(function(address) {
                        if (address.isDefaultBilling()) {
                            clientConfig.sdkUrl = updatePaypalLocale(clientConfig.sdkUrl, address.countryId);
                            initPaypalSdk(clientConfig, element);
                        }
                    });
                } else {
                    // attempt to get country ID from the quote - guest customer filled in address but refreshed the page
                    var billingAddress = quote.billingAddress();
                    if (billingAddress && billingAddress.countryId) {
                        clientConfig.sdkUrl = updatePaypalLocale(clientConfig.sdkUrl, billingAddress.countryId);
                        initPaypalSdk(clientConfig, element);
                    } else {
                        // wait for the guest customer to fill in billing address for the first time
                        quote.billingAddress.subscribe(function(newAddress) {
                            var billingCountry = newAddress ? newAddress.countryId : null;
                            if (!paypalMethodsInitialised.includes(clientConfig.rendererComponent.index)) {
                                clientConfig.sdkUrl = updatePaypalLocale(clientConfig.sdkUrl, billingCountry);
                                paypalMethodsInitialised.push(clientConfig.rendererComponent.index);
                                initPaypalSdk(clientConfig, element);
                            }
                        });
                    }
                }
            })
        } else {
            initPaypalSdk(clientConfig, element);
        }

    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Paypal/js/in-context/express-checkout-wrapper', [
    'jquery',
    'mage/translate',
    'Magento_Customer/js/customer-data',
    'Magento_Paypal/js/in-context/express-checkout-smart-buttons',
    'Magento_Ui/js/modal/alert',
    'mage/cookies'
], function ($, $t, customerData, checkoutSmartButtons, alert) {
    'use strict';

    return {
        defaults: {
            paymentActionError: $t('Something went wrong with your request. Please try again later.'),
            signInMessage: $t('To check out, please sign in with your email address.')
        },

        /**
         * Render PayPal buttons using checkout.js
         */
        renderPayPalButtons: function (element) {
            checkoutSmartButtons(this.prepareClientConfig(), element);
        },

        /**
         * Validate payment method
         *
         * @param {Object} actions
         */
        validate: function (actions) {
            this.actions = actions || this.actions;
        },

        /**
         * Execute logic on Paypal button click
         */
        onClick: function () {},

        /**
         * Before payment execute
         *
         * @param {Function} resolve
         * @param {Function} reject
         * @return {*}
         */
        beforePayment: function (resolve, reject) { //eslint-disable-line no-unused-vars
            return $.Deferred().resolve();
        },

        /**
         * After payment execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         *
         * @return {*}
         */
        afterPayment: function (res, resolve, reject) {

            if (res.success) {
                return resolve(res.token);
            }

            return reject(new Error(res['error_message']));
        },

        /**
         * Catch payment
         *
         * @param {Error} err
         * @param {Function} resolve
         * @param {Function} reject
         */
        catchPayment: function (err, resolve, reject) {
            this.addAlert(this.paymentActionError);
            reject(err);
        },

        /**
         * Before onAuthorize execute
         *
         * @param {Function} resolve
         * @param {Function} reject
         * @param {Object} actions
         *
         * @return {jQuery.Deferred}
         */
        beforeOnAuthorize: function (resolve, reject, actions) { //eslint-disable-line no-unused-vars
            //display loading widget.
            $('body').trigger('processStart');

            return $.Deferred().resolve();
        },

        /**
         * After onAuthorize execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         * @param {Object} actions
         *
         * @return {*}
         */
        afterOnAuthorize: function (res, resolve, reject, actions) {
            $('body').trigger('processStop');

            if (res.success) {
                resolve();

                return actions.redirect(res.redirectUrl);
            }

            return reject(new Error(res['error_message']));
        },

        /**
         * Catch payment
         *
         * @param {Error} err
         * @param {Function} resolve
         * @param {Function} reject
         */
        catchOnAuthorize: function (err, resolve, reject) {
            $('body').trigger('processStop');
            this.addAlert(this.paymentActionError);
            reject(err);
        },

        /**
         * Process cancel action
         *
         * @param {Object} data
         * @param {Object} actions
         */
        onCancel: function (data, actions) {
            $('body').trigger('processStop');
            actions.redirect(this.clientConfig.onCancelUrl);
        },

        /**
         * Process errors
         *
         * @param {Error} err
         */
        onError: function (err) { //eslint-disable-line no-unused-vars
            // Uncaught error isn't displayed in the console
        },

        /**
         * Adds error message
         *
         * @param {String} message
         * @param {String} [type]
         */
        addError: function (message, type) {
            type = type || 'error';
            customerData.set('messages', {
                messages: [{
                    type: type,
                    text: message
                }],
                'data_id': Math.floor(Date.now() / 1000)
            });
        },

        /**
         * Add alert message
         *
         * @param {String} message
         */
        addAlert: function (message) {
            alert({
                content: message
            });
        },

        /**
         * @returns {String}
         */
        getButtonId: function () {
            return this.inContextId;
        },

        /**
         * Populate client config with all required data
         *
         * @return {Object}
         */
        prepareClientConfig: function () {
            this.clientConfig.rendererComponent = this;
            this.clientConfig.formKey = $.mage.cookies.get('form_key');

            return this.clientConfig;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Paypal/js/in-context/button', [
    'uiComponent',
    'jquery',
    'Magento_Paypal/js/in-context/express-checkout-wrapper',
    'Magento_Customer/js/customer-data'
], function (Component, $, Wrapper, customerData) {
    'use strict';

    return Component.extend(Wrapper).extend({
        defaults: {
            declinePayment: false
        },

        /** @inheritdoc */
        initialize: function (config, element) {
            var cart = customerData.get('cart'),
                customer = customerData.get('customer');

            this._super();
            this.renderPayPalButtons(element);

            if (cart().isGuestCheckoutAllowed === undefined) {
                cart.subscribe(function (updatedCart) {
                    this.declinePayment = !customer().firstname && !cart().isGuestCheckoutAllowed;

                    return updatedCart;
                }.bind(this));
            }

            return this;
        },

        /** @inheritdoc */
        beforePayment: function (resolve, reject) {
            var promise = $.Deferred();

            if (this.declinePayment) {
                this.addError(this.signInMessage, 'warning');

                reject();
            } else {
                promise.resolve();
            }

            return promise;
        },

        /** @inheritdoc */
        prepareClientConfig: function () {
            this._super();

            return this.clientConfig;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/payment/additional-validators', [], function () {
    'use strict';

    var validators = [];

    return {
        /**
         * Register unique validator
         *
         * @param {*} validator
         */
        registerValidator: function (validator) {
            validators.push(validator);
        },

        /**
         * Returns array of registered validators
         *
         * @returns {Array}
         */
        getValidators: function () {
            return validators;
        },

        /**
         * Process validators
         *
         * @returns {Boolean}
         */
        validate: function (hideError) {
            var validationResult = true;

            hideError = hideError || false;

            if (validators.length <= 0) {
                return validationResult;
            }

            validators.forEach(function (item) {
                if (item.validate(hideError) == false) { //eslint-disable-line eqeqeq
                    validationResult = false;

                    return false;
                }
            });

            return validationResult;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * @api
 */
define('Magento_Checkout/js/model/quote', [
    'ko',
    'underscore',
    'domReady!'
], function (ko, _) {
    'use strict';

    /**
     * Get totals data from the extension attributes.
     * @param {*} data
     * @returns {*}
     */
    var proceedTotalsData = function (data) {
            if (_.isObject(data) && _.isObject(data['extension_attributes'])) {
                _.each(data['extension_attributes'], function (element, index) {
                    data[index] = element;
                });
            }

            return data;
        },
        billingAddress = ko.observable(null),
        shippingAddress = ko.observable(null),
        shippingMethod = ko.observable(null),
        paymentMethod = ko.observable(null),
        quoteData = window.checkoutConfig.quoteData,
        basePriceFormat = window.checkoutConfig.basePriceFormat,
        priceFormat = window.checkoutConfig.priceFormat,
        storeCode = window.checkoutConfig.storeCode,
        totalsData = proceedTotalsData(window.checkoutConfig.totalsData),
        totals = ko.observable(totalsData),
        collectedTotals = ko.observable({});

    return {
        totals: totals,
        shippingAddress: shippingAddress,
        shippingMethod: shippingMethod,
        billingAddress: billingAddress,
        paymentMethod: paymentMethod,
        guestEmail: null,

        /**
         * @return {*}
         */
        getQuoteId: function () {
            return quoteData['entity_id'];
        },

        /**
         * @return {Boolean}
         */
        isVirtual: function () {
            return !!Number(quoteData['is_virtual']);
        },

        /**
         * @return {*}
         */
        getPriceFormat: function () {
            return priceFormat;
        },

        /**
         * @return {*}
         */
        getBasePriceFormat: function () {
            return basePriceFormat;
        },

        /**
         * @return {*}
         */
        getItems: function () {
            return window.checkoutConfig.quoteItemData;
        },

        /**
         *
         * @return {*}
         */
        getTotals: function () {
            return totals;
        },

        /**
         * @param {Object} data
         */
        setTotals: function (data) {
            data = proceedTotalsData(data);
            totals(data);
            this.setCollectedTotals('subtotal_with_discount', parseFloat(data['subtotal_with_discount']));
        },

        /**
         * @param {*} paymentMethodCode
         */
        setPaymentMethod: function (paymentMethodCode) {
            paymentMethod(paymentMethodCode);
        },

        /**
         * @return {*}
         */
        getPaymentMethod: function () {
            return paymentMethod;
        },

        /**
         * @return {*}
         */
        getStoreCode: function () {
            return storeCode;
        },

        /**
         * @param {String} code
         * @param {*} value
         */
        setCollectedTotals: function (code, value) {
            var colTotals = collectedTotals();

            colTotals[code] = value;
            collectedTotals(colTotals);
        },

        /**
         * @return {Number}
         */
        getCalculatedTotal: function () {
            var total = 0.; //eslint-disable-line no-floating-decimal

            _.each(collectedTotals(), function (value) {
                total += value;
            });

            return total;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/full-screen-loader', [
    'jquery',
    'rjsResolver'
], function ($, resolver) {
    'use strict';

    var containerId = '#checkout';

    return {

        /**
         * Start full page loader action
         */
        startLoader: function () {
            $(containerId).trigger('processStart');
        },

        /**
         * Stop full page loader action
         *
         * @param {Boolean} [forceStop]
         */
        stopLoader: function (forceStop) {
            var $elem = $(containerId),
                stop = $elem.trigger.bind($elem, 'processStop'); //eslint-disable-line jquery-no-bind-unbind

            forceStop ? stop() : resolver(stop);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/redirect-on-success', 
    [
        'mage/url',
        'Magento_Checkout/js/model/full-screen-loader'
    ],
    function (url, fullScreenLoader) {
        'use strict';

        return {
            redirectUrl: window.checkoutConfig.defaultSuccessPageUrl,

            /**
             * Provide redirect to page
             */
            execute: function () {
                fullScreenLoader.startLoader();
                this.redirectToSuccessPage();
            },

            /**
             * Redirect to success page.
             */
            redirectToSuccessPage: function () {
                window.location.replace(url.build(this.redirectUrl));
            }
        };
    }
);

define('text!ui/template/collection.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<each args="data: elems, as: \'element\'">\n    <render if="hasTemplate()"></render>\n</each>\n';
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/shipping_method/price', [
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils'
], function (Component, quote, priceUtils) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Tax/checkout/shipping_method/price'
        },
        isDisplayShippingPriceExclTax: window.checkoutConfig.isDisplayShippingPriceExclTax,
        isDisplayShippingBothPrices: window.checkoutConfig.isDisplayShippingBothPrices,

        /**
         * @param {Object} item
         * @return {Boolean}
         */
        isPriceEqual: function (item) {
            return item['price_excl_tax'] != item['price_incl_tax']; //eslint-disable-line eqeqeq
        },

        /**
         * @param {*} price
         * @return {*|String}
         */
        getFormattedPrice: function (price) {
            //todo add format data
            return priceUtils.formatPriceLocale(price, quote.getPriceFormat());
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/totals', [
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Customer/js/customer-data'
], function (ko, quote, customerData) {
    'use strict';

    var quoteItems = ko.observable(quote.totals().items),
        cartData = customerData.get('cart'),
        quoteSubtotal = parseFloat(quote.totals().subtotal),
        subtotalAmount = parseFloat(cartData().subtotalAmount);

    quote.totals.subscribe(function (newValue) {
        quoteItems(newValue.items);
    });

    if (!isNaN(subtotalAmount) && quoteSubtotal !== subtotalAmount && quoteSubtotal !== 0) {
        customerData.reload(['cart'], false);
    }

    return {
        totals: quote.totals,
        isLoading: ko.observable(false),

        /**
         * @return {Function}
         */
        getItems: function () {
            return quoteItems;
        },

        /**
         * @param {*} code
         * @return {*}
         */
        getSegment: function (code) {
            var i, total;

            if (!this.totals()) {
                return null;
            }

            for (i in this.totals()['total_segments']) { //eslint-disable-line guard-for-in
                total = this.totals()['total_segments'][i];

                if (total.code == code) { //eslint-disable-line eqeqeq
                    return total;
                }
            }

            return null;
        }
    };
});

"use strict";

define('MediaLounge_PayPalPayLater/js/paylaterCart.babel', ['jquery', 'Magento_Checkout/js/model/totals', 'mage/cookies'], ($, totals) => {
  'use strict';

  let locale = $.cookie('geoipcountrycode') ? $.cookie('geoipcountrycode') : null;
  let scriptIsLoaded = false;
  return (config, element) => {
    let elMessage = element.querySelector('[data-pp-message]');

    if (locale && locale === 'US') {
      element.classList.add('__show');

      if (!scriptIsLoaded) {
        let script = document.createElement('script');
        script.setAttribute('src', `https://www.paypal.com/sdk/js?client-id=${config.client_id}&components=messages`);
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('data-namespace', 'paypal_sdk');
        document.getElementsByTagName('head')[0].appendChild(script);
        scriptIsLoaded = true;
      }

      setTimeout(() => {
        elMessage.setAttribute('data-pp-amount', totals.totals().base_grand_total);
        totals.totals.subscribe(() => {
          elMessage.setAttribute('data-pp-amount', totals.totals().base_grand_total);
        });
      }, 1000);
      setInterval(() => {
        elMessage.setAttribute('data-pp-timestamp', Date.now());
      }, 1000);
    }
  };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Checkout adapter for customer data storage
 *
 * @api
 */
define('Magento_Checkout/js/checkout-data', [
    'jquery',
    'Magento_Customer/js/customer-data',
    'mageUtils',
    'jquery/jquery-storageapi'
], function ($, storage, utils) {
    'use strict';

    var cacheKey = 'checkout-data',

        /**
         * @param {Object} data
         */
        saveData = function (data) {
            storage.set(cacheKey, data);
        },

        /**
         * @return {*}
         */
        initData = function () {
            return {
                'selectedShippingAddress': null, //Selected shipping address pulled from persistence storage
                'shippingAddressFromData': null, //Shipping address pulled from persistence storage
                'newCustomerShippingAddress': null, //Shipping address pulled from persistence storage for customer
                'selectedShippingRate': null, //Shipping rate pulled from persistence storage
                'selectedPaymentMethod': null, //Payment method pulled from persistence storage
                'selectedBillingAddress': null, //Selected billing address pulled from persistence storage
                'billingAddressFromData': null, //Billing address pulled from persistence storage
                'newCustomerBillingAddress': null //Billing address pulled from persistence storage for new customer
            };
        },

        /**
         * @return {*}
         */
        getData = function () {
            var data = storage.get(cacheKey)();

            if ($.isEmptyObject(data)) {
                data = $.initNamespaceStorage('mage-cache-storage').localStorage.get(cacheKey);

                if ($.isEmptyObject(data)) {
                    data = initData();
                    saveData(data);
                }
            }

            return data;
        };

    return {
        /**
         * Setting the selected shipping address pulled from persistence storage
         *
         * @param {Object} data
         */
        setSelectedShippingAddress: function (data) {
            var obj = getData();

            obj.selectedShippingAddress = data;
            saveData(obj);
        },

        /**
         * Pulling the selected shipping address from persistence storage
         *
         * @return {*}
         */
        getSelectedShippingAddress: function () {
            return getData().selectedShippingAddress;
        },

        /**
         * Setting the shipping address pulled from persistence storage
         *
         * @param {Object} data
         */
        setShippingAddressFromData: function (data) {
            var obj = getData();

            obj.shippingAddressFromData = utils.filterFormData(data);
            saveData(obj);
        },

        /**
         * Pulling the shipping address from persistence storage
         *
         * @return {*}
         */
        getShippingAddressFromData: function () {
            return getData().shippingAddressFromData;
        },

        /**
         * Setting the shipping address pulled from persistence storage for new customer
         *
         * @param {Object} data
         */
        setNewCustomerShippingAddress: function (data) {
            var obj = getData();

            obj.newCustomerShippingAddress = data;
            saveData(obj);
        },

        /**
         * Pulling the shipping address from persistence storage for new customer
         *
         * @return {*}
         */
        getNewCustomerShippingAddress: function () {
            return getData().newCustomerShippingAddress;
        },

        /**
         * Setting the selected shipping rate pulled from persistence storage
         *
         * @param {Object} data
         */
        setSelectedShippingRate: function (data) {
            var obj = getData();

            obj.selectedShippingRate = data;
            saveData(obj);
        },

        /**
         * Pulling the selected shipping rate from local storage
         *
         * @return {*}
         */
        getSelectedShippingRate: function () {
            return getData().selectedShippingRate;
        },

        /**
         * Setting the selected payment method pulled from persistence storage
         *
         * @param {Object} data
         */
        setSelectedPaymentMethod: function (data) {
            var obj = getData();

            obj.selectedPaymentMethod = data;
            saveData(obj);
        },

        /**
         * Pulling the payment method from persistence storage
         *
         * @return {*}
         */
        getSelectedPaymentMethod: function () {
            return getData().selectedPaymentMethod;
        },

        /**
         * Setting the selected billing address pulled from persistence storage
         *
         * @param {Object} data
         */
        setSelectedBillingAddress: function (data) {
            var obj = getData();

            obj.selectedBillingAddress = data;
            saveData(obj);
        },

        /**
         * Pulling the selected billing address from persistence storage
         *
         * @return {*}
         */
        getSelectedBillingAddress: function () {
            return getData().selectedBillingAddress;
        },

        /**
         * Setting the billing address pulled from persistence storage
         *
         * @param {Object} data
         */
        setBillingAddressFromData: function (data) {
            var obj = getData();

            obj.billingAddressFromData = utils.filterFormData(data);
            saveData(obj);
        },

        /**
         * Pulling the billing address from persistence storage
         *
         * @return {*}
         */
        getBillingAddressFromData: function () {
            return getData().billingAddressFromData;
        },

        /**
         * Setting the billing address pulled from persistence storage for new customer
         *
         * @param {Object} data
         */
        setNewCustomerBillingAddress: function (data) {
            var obj = getData();

            obj.newCustomerBillingAddress = data;
            saveData(obj);
        },

        /**
         * Pulling the billing address from persistence storage for new customer
         *
         * @return {*}
         */
        getNewCustomerBillingAddress: function () {
            return getData().newCustomerBillingAddress;
        },

        /**
         * Pulling the email address from persistence storage
         *
         * @return {*}
         */
        getValidatedEmailValue: function () {
            var obj = getData();

            return obj.validatedEmailValue ? obj.validatedEmailValue : '';
        },

        /**
         * Setting the email address pulled from persistence storage
         *
         * @param {String} email
         */
        setValidatedEmailValue: function (email) {
            var obj = getData();

            obj.validatedEmailValue = email;
            saveData(obj);
        },

        /**
         * Pulling the email input field value from persistence storage
         *
         * @return {*}
         */
        getInputFieldEmailValue: function () {
            var obj = getData();

            return obj.inputFieldEmailValue ? obj.inputFieldEmailValue : '';
        },

        /**
         * Setting the email input field value pulled from persistence storage
         *
         * @param {String} email
         */
        setInputFieldEmailValue: function (email) {
            var obj = getData();

            obj.inputFieldEmailValue = email;
            saveData(obj);
        },

        /**
         * Pulling the checked email value from persistence storage
         *
         * @return {*}
         */
        getCheckedEmailValue: function () {
            var obj = getData();

            return obj.checkedEmailValue ? obj.checkedEmailValue : '';
        },

        /**
         * Setting the checked email value pulled from persistence storage
         *
         * @param {String} email
         */
        setCheckedEmailValue: function (email) {
            var obj = getData();

            obj.checkedEmailValue = email;
            saveData(obj);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/model/messages', [
    'ko',
    'uiClass'
], function (ko, Class) {
    'use strict';

    return Class.extend({
        /** @inheritdoc */
        initialize: function () {
            this._super()
                .initObservable();

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this.errorMessages = ko.observableArray([]);
            this.successMessages = ko.observableArray([]);

            return this;
        },

        /**
         * Add  message to list.
         * @param {Object} messageObj
         * @param {Object} type
         * @returns {Boolean}
         */
        add: function (messageObj, type) {
            var expr = /([%])\w+/g,
                message;

            if (!messageObj.hasOwnProperty('parameters')) {
                this.clear();
                type.push(messageObj.message);

                return true;
            }
            message = messageObj.message.replace(expr, function (varName) {
                varName = varName.substr(1);

                if (!isNaN(varName)) {
                    varName--;
                }

                if (messageObj.parameters.hasOwnProperty(varName)) {
                    return messageObj.parameters[varName];
                }

                return messageObj.parameters.shift();
            });
            this.clear();
            type.push(message);

            return true;
        },

        /**
         * Add success message.
         *
         * @param {Object} message
         * @return {*|Boolean}
         */
        addSuccessMessage: function (message) {
            return this.add(message, this.successMessages);
        },

        /**
         * Add error message.
         *
         * @param {Object} message
         * @return {*|Boolean}
         */
        addErrorMessage: function (message) {
            return this.add(message, this.errorMessages);
        },

        /**
         * Get error messages.
         *
         * @return {Array}
         */
        getErrorMessages: function () {
            return this.errorMessages;
        },

        /**
         * Get success messages.
         *
         * @return {Array}
         */
        getSuccessMessages: function () {
            return this.successMessages;
        },

        /**
         * Checks if an instance has stored messages.
         *
         * @return {Boolean}
         */
        hasMessages: function () {
            return this.errorMessages().length > 0 || this.successMessages().length > 0;
        },

        /**
         * Removes stored messages.
         */
        clear: function () {
            this.errorMessages.removeAll();
            this.successMessages.removeAll();
        }
    });
});

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/view/payment/config-loader', 
    [
        'jquery'
    ],
    function ($) {
        'use strict';
        const MODULE_ID = 'checkoutcom_magento2';
        return window.checkoutConfig.payment[MODULE_ID];
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/shipping-rates-validation-rules', ['jquery'], function ($) {
    'use strict';

    var ratesRules = {},
        checkoutConfig = window.checkoutConfig;

    return {
        /**
         * @param {String} carrier
         * @param {Object} rules
         */
        registerRules: function (carrier, rules) {
            if (checkoutConfig.activeCarriers.indexOf(carrier) !== -1) {
                ratesRules[carrier] = rules.getRules();
            }
        },

        /**
         * @return {Object}
         */
        getRules: function () {
            return ratesRules;
        },

        /**
         * @return {Array}
         */
        getObservableFields: function () {
            var self = this,
                observableFields = [];

            $.each(self.getRules(), function (carrier, fields) {
                $.each(fields, function (field) {
                    if (observableFields.indexOf(field) === -1) {
                        observableFields.push(field);
                    }
                });
            });

            return observableFields;
        }
    };
});

/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license sliderConfig is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_RewardPoints
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
define('Mageplaza_RewardPoints/js/model/points', ['jquery', 'ko', 'Magento_Checkout/js/model/quote'], function ($, ko, quote) {
    "use strict";

    var pattern, isEarnWithSpent,
        balance            = ko.observable(),
        rewardPointsConfig = ko.computed(function () {
            var rewardConfig = {},
                extensionAttributes = quote.getTotals()().extension_attributes;
            
            if (extensionAttributes && extensionAttributes.reward_points) {
                rewardConfig = JSON.parse(extensionAttributes.reward_points);
            }

            pattern = rewardConfig.pattern || {single: "{point} point", plural: "{point} points"};
            balance(rewardConfig.balance || 0);
            isEarnWithSpent= rewardConfig.isEarnWithSpent;
            return rewardConfig.spending || {};
        });

    return {
        spendingConfig: rewardPointsConfig,
        balance: balance,
        isEarnWithSpent : isEarnWithSpent,
        isCheckoutCart: $('body').hasClass('checkout-cart-index'),

        /**
         * Format point label
         * @param point
         * @return {string}
         */
        format: function (point) {
            if (parseInt(point) > 1) {
                return pattern.plural.replace('{point}', point);
            }

            return pattern.single.replace('{point}', point);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/model/default-post-code-resolver', [], function () {
    'use strict';

    /**
     * Define necessity of using default post code value
     */
    var useDefaultPostCode;

    return {
        /**
         * Resolve default post code
         *
         * @returns {String|null}
         */
        resolve: function () {
            return useDefaultPostCode ?  window.checkoutConfig.defaultPostcode : null;
        },

        /**
         * Set state to useDefaultPostCode variable
         *
         * @param {Boolean} shouldUseDefaultPostCode
         * @returns {underscore}
         */
        setUseDefaultPostCode: function (shouldUseDefaultPostCode) {
            useDefaultPostCode = shouldUseDefaultPostCode;

            return this;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_GiftMessage/js/model/gift-message', [
    'uiElement',
    'underscore',
    'mage/url'
], function (uiElement, _, url) {
    'use strict';

    var provider = uiElement();

    return function (itemId) {
        var model = {
            id: 'message-' + itemId,
            itemId: itemId,
            observables: {},
            additionalOptions: [],
            submitParams: [
                'recipient',
                'sender',
                'message'
            ],

            /**
             * Initialize.
             */
            initialize: function () {
                var message = false;

                this.getObservable('alreadyAdded')(false);

                if (this.itemId == 'orderLevel') { //eslint-disable-line eqeqeq
                    message = window.giftOptionsConfig.giftMessage.hasOwnProperty(this.itemId) ?
                        window.giftOptionsConfig.giftMessage[this.itemId] :
                        null;
                } else {
                    message =
                        window.giftOptionsConfig.giftMessage.hasOwnProperty('itemLevel') &&
                        window.giftOptionsConfig.giftMessage.itemLevel.hasOwnProperty(this.itemId) ?
                            window.giftOptionsConfig.giftMessage.itemLevel[this.itemId].message :
                            null;
                }

                if (_.isObject(message)) {
                    this.getObservable('recipient')(message.recipient);
                    this.getObservable('sender')(message.sender);
                    this.getObservable('message')(message.message);
                    this.getObservable('alreadyAdded')(true);
                }
            },

            /**
             * @param {String} key
             * @return {*}
             */
            getObservable: function (key) {
                this.initObservable(this.id, key);

                return provider[this.getUniqueKey(this.id, key)];
            },

            /**
             * @param {String} node
             * @param {String} key
             */
            initObservable: function (node, key) {
                if (node && !this.observables.hasOwnProperty(node)) {
                    this.observables[node] = [];
                }

                if (key && this.observables[node].indexOf(key) === -1) {
                    this.observables[node].push(key);
                    provider.observe(this.getUniqueKey(node, key));
                }
            },

            /**
             * @param {String} node
             * @param {String} key
             * @return {String}
             */
            getUniqueKey: function (node, key) {
                return node + '-' + key;
            },

            /**
             * @param {String} key
             * @return {null}
             */
            getConfigValue: function (key) {
                return window.giftOptionsConfig.hasOwnProperty(key) ?
                    window.giftOptionsConfig[key]
                    : null;
            },

            /**
             * Reset.
             */
            reset: function () {
                this.getObservable('isClear')(true);
            },

            /**
             * @return {Array}
             */
            getAfterSubmitCallbacks: function () {
                var callbacks = [];

                callbacks.push(this.afterSubmit);
                _.each(this.additionalOptions, function (option) {
                    if (_.isFunction(option.afterSubmit)) {
                        callbacks.push(option.afterSubmit);
                    }
                });

                return callbacks;
            },

            /**
             * After submit.
             */
            afterSubmit: function () {
                window.location.href = url.build('checkout/cart/updatePost') +
                    '?form_key=' + window.checkoutConfig.formKey +
                    '&cart[]';
            },

            /**
             * @param {Boolean} remove
             * @return {Object}
             */
            getSubmitParams: function (remove) {
                var params = {},
                    self = this;

                _.each(this.submitParams, function (key) {
                    var observable = provider[self.getUniqueKey(self.id, key)];

                    if (_.isFunction(observable)) {
                        params[key] = remove ? null : observable();
                    }
                });

                if (this.additionalOptions.length) {
                    params['extension_attributes'] = {};
                }
                _.each(this.additionalOptions, function (option) {
                    if (_.isFunction(option.getSubmitParams)) {
                        params['extension_attributes'] = _.extend(
                            params['extension_attributes'],
                            option.getSubmitParams(remove)
                        );
                    }
                });

                return params;
            },

            /**
             * Check if gift message can be displayed
             *
             * @returns {Boolean}
             */
            isGiftMessageAvailable: function () {
                var isGloballyAvailable,
                    giftMessageConfig,
                    itemConfig;

                // itemId represent gift message level: 'orderLevel' constant or cart item ID
                if (this.itemId === 'orderLevel') {
                    return this.getConfigValue('isOrderLevelGiftOptionsEnabled');
                }

                // gift message product configuration must override system configuration
                isGloballyAvailable = this.getConfigValue('isItemLevelGiftOptionsEnabled');
                giftMessageConfig = window.giftOptionsConfig.giftMessage;
                itemConfig = giftMessageConfig.hasOwnProperty('itemLevel') &&
                    giftMessageConfig.itemLevel.hasOwnProperty(this.itemId) ?
                    giftMessageConfig.itemLevel[this.itemId] :
                    {};

                return itemConfig.hasOwnProperty('is_available') ? itemConfig['is_available'] : isGloballyAvailable;
            }
        };

        model.initialize();

        return model;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validation-rules/flatrate', [], function () {
    'use strict';

    return {
        /**
         * @return {Object}
         */
        getRules: function () {
            return {
                'country_id': {
                    'required': true
                }
            };
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validation-rules/freeshipping', [], function () {
    'use strict';

    return {
        /**
         * @return {Object}
         */
        getRules: function () {
            return {
                'country_id': {
                    'required': true
                }
            };
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validator/freeshipping', [
    'jquery',
    'mageUtils',
    '../shipping-rates-validation-rules/freeshipping',
    'mage/translate'
], function ($, utils, validationRules, $t) {
    'use strict';

    return {
        validationErrors: [],

        /**
         * @param {Object} address
         * @return {Boolean}
         */
        validate: function (address) {
            var self = this;

            this.validationErrors = [];
            $.each(validationRules.getRules(), function (field, rule) {
                var message;

                if (rule.required && utils.isEmpty(address[field])) {
                    message = $t('Field ') + field + $t(' is required.');
                    self.validationErrors.push(message);
                }
            });

            return !this.validationErrors.length;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validator/flatrate', [
    'jquery',
    'mageUtils',
    '../shipping-rates-validation-rules/flatrate',
    'mage/translate'
], function ($, utils, validationRules, $t) {
    'use strict';

    return {
        validationErrors: [],

        /**
         * @param {Object} address
         * @return {Boolean}
         */
        validate: function (address) {
            var self = this;

            this.validationErrors = [];
            $.each(validationRules.getRules(), function (field, rule) {
                var message;

                if (rule.required && utils.isEmpty(address[field])) {
                    message = $t('Field ') + field + $t(' is required.');
                    self.validationErrors.push(message);
                }
            });

            return !this.validationErrors.length;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/select-shipping-address', [
    'Magento_Checkout/js/model/quote'
], function (quote) {
    'use strict';

    return function (shippingAddress) {
        quote.shippingAddress(shippingAddress);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_GiftMessage/js/model/gift-options', [
    'underscore',
    'ko'
], function (_, ko) {
    'use strict';

    return {
        options: ko.observableArray([]),

        /**
         * @param {Object} option
         */
        addOption: function (option) {
            if (!this.options().hasOwnProperty(option.itemId)) {
                this.options.push({
                        id: option.itemId, value: option
                    }
                );
            }
        },

        /**
         * @param {*} itemId
         * @return {*}
         */
        getOptionByItemId: function (itemId) {
            var option = null;

            _.each(this.options(), function (data) {
                if (data.id === itemId) {
                    option = data.value;

                    return false;
                }
            });

            return option;
        }
    };
});

define('CheckoutCom_Magento2/js/model/grand-total-hide', function () {
    'use strict';

    var mixin = {
        isBaseGrandTotalDisplayNeeded: function () {
            let checkoutConfig = window.checkoutConfig.payment["checkoutcom_magento2"];
            return !parseInt(checkoutConfig["checkoutcom_configuration"]['active']);
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment/method-list', [
    'ko'
], function (ko) {
    'use strict';

    return ko.observableArray([]);
});

/**
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Smile ElasticSuite to newer
 * versions in the future.
 *
 * @category  Smile
 * @package   Smile\ElasticsuiteCore
 * @author    Botis <botis@smile.fr>
 * @copyright 2021 Smile
 * @license   Open Software License ("OSL") v. 3.0
 */

define('Smile_ElasticsuiteCore/js/validation/validator-mixin', ['jquery'], function ($) {
    'use strict';

    return function (validator) {
        validator.addRule(
            'not-zero',
            function (value, element) {
                return parseInt(value) !== 0;
            },
            $.mage.__('The value should be different to zero.')
        );

        return validator;
    }
});


/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validation-rules/tablerate', [], function () {
    'use strict';

    return {
        /**
         * @return {Object}
         */
        getRules: function () {
            return {
                'postcode': {
                    'required': true
                },
                'country_id': {
                    'required': true
                },
                'region_id': {
                    'required': true
                },
                'region_id_input': {
                    'required': true
                }
            };
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/model/shipping-rates-validator/tablerate', [
    'jquery',
    'mageUtils',
    '../shipping-rates-validation-rules/tablerate',
    'mage/translate'
], function ($, utils, validationRules, $t) {
    'use strict';

    return {
        validationErrors: [],

        /**
         * @param {Object} address
         * @return {Boolean}
         */
        validate: function (address) {
            var self = this;

            this.validationErrors = [];
            $.each(validationRules.getRules(), function (field, rule) {
                var message, regionFields;

                if (rule.required && utils.isEmpty(address[field])) {
                    message = $t('Field ') + field + $t(' is required.');
                    regionFields = ['region', 'region_id', 'region_id_input'];

                    if (
                        $.inArray(field, regionFields) === -1 ||
                        utils.isEmpty(address.region) && utils.isEmpty(address['region_id'])
                    ) {
                        self.validationErrors.push(message);
                    }
                }
            });

            return !this.validationErrors.length;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/url-builder', ['jquery'], function ($) {
    'use strict';

    return {
        method: 'rest',
        storeCode: window.checkoutConfig.storeCode,
        version: 'V1',
        serviceUrl: ':method/:storeCode/:version',

        /**
         * @param {String} url
         * @param {Object} params
         * @return {*}
         */
        createUrl: function (url, params) {
            var completeUrl = this.serviceUrl + url;

            return this.bindParams(completeUrl, params);
        },

        /**
         * @param {String} url
         * @param {Object} params
         * @return {*}
         */
        bindParams: function (url, params) {
            var urlParts;

            params.method = this.method;
            params.storeCode = this.storeCode;
            params.version = this.version;

            urlParts = url.split('/');
            urlParts = urlParts.filter(Boolean);

            $.each(urlParts, function (key, part) {
                part = part.replace(':', '');

                if (params[part] != undefined) { //eslint-disable-line eqeqeq
                    urlParts[key] = params[part];
                }
            });

            return urlParts.join('/');
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * Coupon model.
 */
define('Magento_SalesRule/js/model/coupon', [
    'ko',
    'domReady!'
], function (ko) {
    'use strict';

    var couponCode = ko.observable(null),
        isApplied = ko.observable(null);

    return {
        couponCode: couponCode,
        isApplied: isApplied,

        /**
         * @return {*}
         */
        getCouponCode: function () {
            return couponCode;
        },

        /**
         * @return {Boolean}
         */
        getIsApplied: function () {
            return isApplied;
        },

        /**
         * @param {*} couponCodeValue
         */
        setCouponCode: function (couponCodeValue) {
            couponCode(couponCodeValue);
        },

        /**
         * @param {Boolean} isAppliedValue
         */
        setIsApplied: function (isAppliedValue) {
            isApplied(isAppliedValue);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/select-shipping-method', [
    '../model/quote'
], function (quote) {
    'use strict';

    return function (shippingMethod) {
        quote.shippingMethod(shippingMethod);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/select-billing-address', [
    'jquery',
    '../model/quote'
], function ($, quote) {
    'use strict';

    return function (billingAddress) {
        var address = null;

        if (quote.shippingAddress() && billingAddress.getCacheKey() == //eslint-disable-line eqeqeq
            quote.shippingAddress().getCacheKey()
        ) {
            address = $.extend(true, {}, billingAddress);
            address.saveInAddressBook = null;
        } else {
            address = billingAddress;
        }
        quote.billingAddress(address);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/model/agreements-assigner', [
    'jquery'
], function ($) {
    'use strict';

    var agreementsConfig = window.checkoutConfig.checkoutAgreements;

    /** Override default place order action and add agreement_ids to request */
    return function (paymentData) {
        var agreementForm,
            agreementData,
            agreementIds;

        if (!agreementsConfig.isEnabled) {
            return;
        }

        agreementForm = $('.payment-method._active div[data-role=checkout-agreements] input');
        agreementData = agreementForm.serializeArray();
        agreementIds = [];

        agreementData.forEach(function (item) {
            agreementIds.push(item.value);
        });

        if (paymentData['extension_attributes'] === undefined) {
            paymentData['extension_attributes'] = {};
        }

        paymentData['extension_attributes']['agreement_ids'] = agreementIds;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/model/place-order-mixin', [
    'jquery',
    'mage/utils/wrapper',
    'Magento_CheckoutAgreements/js/model/agreements-assigner'
], function ($, wrapper, agreementsAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override default place order action and add agreement_ids to request */
        return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
            agreementsAssigner(paymentData);

            return originalAction(paymentData, messageContainer);
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/shipping-address/form-popup-state', [
    'ko'
], function (ko) {
    'use strict';

    return {
        isVisible: ko.observable(false)
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/postcode-validator', [
    'mageUtils'
], function (utils) {
    'use strict';

    return {
        validatedPostCodeExample: [],

        /**
         * @param {*} postCode
         * @param {*} countryId
         * @param {Array} postCodesPatterns
         * @return {Boolean}
         */
        validate: function (postCode, countryId, postCodesPatterns) {
            var pattern, regex,
                patterns = postCodesPatterns ? postCodesPatterns[countryId] :
                    window.checkoutConfig.postCodes[countryId];

            this.validatedPostCodeExample = [];

            if (!utils.isEmpty(postCode) && !utils.isEmpty(patterns)) {
                for (pattern in patterns) {
                    if (patterns.hasOwnProperty(pattern)) { //eslint-disable-line max-depth
                        this.validatedPostCodeExample.push(patterns[pattern].example);
                        regex = new RegExp(patterns[pattern].pattern);

                        if (regex.test(postCode)) { //eslint-disable-line max-depth
                            return true;
                        }
                    }
                }

                return false;
            }

            return true;
        }
    };
});

define('Aheadworks_Giftcard/js/model/payment/total-messages', ['Magento_Ui/js/model/messages'], function(Messages) {
    'use strict';
    return new Messages();
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_GiftMessage/js/model/url-builder', [
    'jquery',
    'Magento_Checkout/js/model/url-builder'
], function ($, urlBuilder) {
    'use strict';

    return $.extend(urlBuilder, {
        storeCode: window.giftOptionsConfig.storeCode
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment/place-order-hooks', [], function () {
    'use strict';

    return {
        requestModifiers: [],
        afterRequestListeners: []
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_ReCaptchaWebapiUi/js/webapiReCaptchaRegistry', [], function () {
    'use strict';

    return {
        /**
         * recaptchaId: token map.
         *
         * Tokens for already verified recaptcha.
         */
        tokens: {},

        /**
         * recaptchaId: triggerFn map.
         *
         * Call a trigger to initiate a recaptcha verification.
         */
        triggers: {},

        /**
         * recaptchaId: callback map
         */
        _listeners: {},

        /**
         * Add a listener to when the ReCaptcha finishes verification
         * @param {String} id - ReCaptchaId
         * @param {Function} func - Will be called back with the token
         */
        addListener: function (id, func) {
            if (this.tokens.hasOwnProperty(id)) {
                func(this.tokens[id]);
            } else {
                this._listeners[id] = func;
            }
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* eslint-disable max-nested-callbacks */

define('Magento_ReCaptchaCheckout/js/model/place-order-mixin', [
    'jquery',
    'mage/utils/wrapper',
    'Magento_ReCaptchaWebapiUi/js/webapiReCaptchaRegistry'
], function ($, wrapper, recaptchaRegistry) {
    'use strict';

    return function (placeOrder) {
        return wrapper.wrap(placeOrder, function (originalAction, serviceUrl, payload, messageContainer) {
            var recaptchaDeferred;

            if (recaptchaRegistry.triggers.hasOwnProperty('recaptcha-checkout-place-order')) {
                //ReCaptcha is present for checkout
                recaptchaDeferred = $.Deferred();
                recaptchaRegistry.addListener('recaptcha-checkout-place-order', function (token) {
                    //Add reCaptcha value to place-order request and resolve deferred with the API call results
                    payload.xReCaptchaValue = token;
                    originalAction(serviceUrl, payload, messageContainer).done(function () {
                        recaptchaDeferred.resolve.apply(recaptchaDeferred, arguments);
                    }).fail(function () {
                        recaptchaDeferred.reject.apply(recaptchaDeferred, arguments);
                    });
                });
                //Trigger ReCaptcha validation
                recaptchaRegistry.triggers['recaptcha-checkout-place-order']();

                return recaptchaDeferred;
            }

            //No ReCaptcha, just sending the request
            return originalAction(serviceUrl, payload, messageContainer);
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/step-navigator', [
    'jquery',
    'ko'
], function ($, ko) {
    'use strict';

    var steps = ko.observableArray();

    return {
        steps: steps,
        stepCodes: [],
        validCodes: [],

        /**
         * @return {Boolean}
         */
        handleHash: function () {
            var hashString = window.location.hash.replace('#', ''),
                isRequestedStepVisible;

            if (hashString === '') {
                return false;
            }

            if ($.inArray(hashString, this.validCodes) === -1) {
                window.location.href = window.checkoutConfig.pageNotFoundUrl;

                return false;
            }

            isRequestedStepVisible = steps.sort(this.sortItems).some(function (element) {
                return (element.code == hashString || element.alias == hashString) && element.isVisible(); //eslint-disable-line
            });

            //if requested step is visible, then we don't need to load step data from server
            if (isRequestedStepVisible) {
                return false;
            }

            steps().sort(this.sortItems).forEach(function (element) {
                if (element.code == hashString || element.alias == hashString) { //eslint-disable-line eqeqeq
                    element.navigate(element);
                } else {
                    element.isVisible(false);
                }

            });

            return false;
        },

        /**
         * @param {String} code
         * @param {*} alias
         * @param {*} title
         * @param {Function} isVisible
         * @param {*} navigate
         * @param {*} sortOrder
         */
        registerStep: function (code, alias, title, isVisible, navigate, sortOrder) {
            var hash, active;

            if ($.inArray(code, this.validCodes) !== -1) {
                throw new DOMException('Step code [' + code + '] already registered in step navigator');
            }

            if (alias != null) {
                if ($.inArray(alias, this.validCodes) !== -1) {
                    throw new DOMException('Step code [' + alias + '] already registered in step navigator');
                }
                this.validCodes.push(alias);
            }
            this.validCodes.push(code);
            steps.push({
                code: code,
                alias: alias != null ? alias : code,
                title: title,
                isVisible: isVisible,
                navigate: navigate,
                sortOrder: sortOrder
            });
            active = this.getActiveItemIndex();
            steps.each(function (elem, index) {
                if (active !== index) {
                    elem.isVisible(false);
                }
            });
            this.stepCodes.push(code);
            hash = window.location.hash.replace('#', '');

            if (hash != '' && hash != code) { //eslint-disable-line eqeqeq
                //Force hiding of not active step
                isVisible(false);
            }
        },

        /**
         * @param {Object} itemOne
         * @param {Object} itemTwo
         * @return {Number}
         */
        sortItems: function (itemOne, itemTwo) {
            return itemOne.sortOrder > itemTwo.sortOrder ? 1 : -1;
        },

        /**
         * @return {Number}
         */
        getActiveItemIndex: function () {
            var activeIndex = 0;

            steps().sort(this.sortItems).some(function (element, index) {
                if (element.isVisible()) {
                    activeIndex = index;

                    return true;
                }

                return false;
            });

            return activeIndex;
        },

        /**
         * @param {*} code
         * @return {Boolean}
         */
        isProcessed: function (code) {
            var activeItemIndex = this.getActiveItemIndex(),
                sortedItems = steps().sort(this.sortItems),
                requestedItemIndex = -1;

            sortedItems.forEach(function (element, index) {
                if (element.code == code) { //eslint-disable-line eqeqeq
                    requestedItemIndex = index;
                }
            });

            return activeItemIndex > requestedItemIndex;
        },

        /**
         * @param {*} code
         * @param {*} scrollToElementId
         */
        navigateTo: function (code, scrollToElementId) {
            var sortedItems = steps().sort(this.sortItems),
                bodyElem = $('body');

            scrollToElementId = scrollToElementId || null;

            if (!this.isProcessed(code)) {
                return;
            }
            sortedItems.forEach(function (element) {
                if (element.code == code) { //eslint-disable-line eqeqeq
                    element.isVisible(true);
                    bodyElem.animate({
                        scrollTop: $('#' + code).offset().top
                    }, 0, function () {
                        window.location = window.checkoutConfig.checkoutUrl + '#' + code;
                    });

                    if (scrollToElementId && $('#' + scrollToElementId).length) {
                        bodyElem.animate({
                            scrollTop: $('#' + scrollToElementId).offset().top
                        }, 0);
                    }
                } else {
                    element.isVisible(false);
                }

            });
        },

        /**
         * Sets window location hash.
         *
         * @param {String} hash
         */
        setHash: function (hash) {
            window.location.hash = hash;
        },

        /**
         * Next step.
         */
        next: function () {
            var activeIndex = 0,
                code;

            steps().sort(this.sortItems).forEach(function (element, index) {
                if (element.isVisible()) {
                    element.isVisible(false);
                    activeIndex = index;
                }
            });

            if (steps().length > activeIndex + 1) {
                code = steps()[activeIndex + 1].code;
                steps()[activeIndex + 1].isVisible(true);
                this.setHash(code);
                document.body.scrollTop = document.documentElement.scrollTop = 0;
            }
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/abstract-total', [
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/totals',
    'Magento_Checkout/js/model/step-navigator'
], function (Component, quote, priceUtils, totals, stepNavigator) {
    'use strict';

    return Component.extend({
        /**
         * @param {*} price
         * @return {*|String}
         */
        getFormattedPrice: function (price) {
            return priceUtils.formatPriceLocale(price, quote.getPriceFormat());
        },

        /**
         * @return {*}
         */
        getTotals: function () {
            return totals.totals();
        },

        /**
         * @return {*}
         */
        isFullMode: function () {
            if (!this.getTotals()) {
                return false;
            }

            return stepNavigator.isProcessed('shipping');
        }
    });
});

/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_RewardPoints
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
define('Mageplaza_RewardPoints/js/view/totals/label', 
    [
        'Magento_Checkout/js/view/summary/abstract-total',
        'Magento_Checkout/js/model/totals',
        'Mageplaza_RewardPoints/js/model/points'
    ], function (Component, totals, points) {
        "use strict";

        return Component.extend({
            defaults: {
                template: 'Mageplaza_RewardPoints/totals/label'
            },

            /**
             * Get earning segment
             * @returns {*}
             */
            getEarning: function () {
                return totals.getSegment('mp_reward_earn');
            },

            /**
             * Get earning point formatted
             * @returns {*}
             */
            getEarningValue: function () {
                var point = this.getEarning().value;

                return points.format(point);
            },

            /**
             * Get earning point formatted
             * @returns {*}
             */
            checkIsLogin: function () {

                return totals.totals()['extension_attributes']['have_highlight'];
            },

            /**
             * Get spending segment
             * @returns {*}
             */
            getSpending: function () {
                return totals.getSegment('mp_reward_spent');
            },

            /**
             * Get spending point formatted
             * @returns {*}
             */
            getSpendingValue: function () {
                var point = this.getSpending().value;

                return points.format(point);
            },

            /**
             * Get spending segment
             * @returns {*}
             */
            isEarnWithSpent: function () {
                return points.isEarnWithSpent;
            }
        });
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/summary/subtotal', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote'
], function (Component, quote) {
    'use strict';

    var displaySubtotalMode = window.checkoutConfig.reviewTotalsDisplayMode;

    return Component.extend({
        defaults: {
            displaySubtotalMode: displaySubtotalMode,
            template: 'Magento_Tax/checkout/summary/subtotal'
        },
        totals: quote.getTotals(),

        /**
         * @return {*|String}
         */
        getValue: function () {
            var price = 0;

            if (this.totals()) {
                price = this.totals().subtotal;
            }

            return this.getFormattedPrice(price);
        },

        /**
         * @return {Boolean}
         */
        isBothPricesDisplayed: function () {
            return this.displaySubtotalMode == 'both'; //eslint-disable-line eqeqeq
        },

        /**
         * @return {Boolean}
         */
        isIncludingTaxDisplayed: function () {
            return this.displaySubtotalMode == 'including'; //eslint-disable-line eqeqeq
        },

        /**
         * @return {*|String}
         */
        getValueInclTax: function () {
            var price = 0;

            if (this.totals()) {
                price = this.totals()['subtotal_incl_tax'];
            }

            return this.getFormattedPrice(price);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('MediaLounge_AmountSaved/js/view/checkout/summary/saved', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'ko'
], function (Component, quote, ko) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'MediaLounge_AmountSaved/checkout/summary/saved'
        },
        itemData: ko.observable(window.checkoutConfig.quoteItemData),
        getValue: function(){
            let rrp = 0,
                dis = 0;

            this.itemData().forEach((item) => {
                if (item['oldprice'] && item['oldprice'] !== '0')
                {
                    rrp += (parseFloat(item['oldprice']) * item['qty']);
                    dis += parseFloat(item['row_total']);
                }
            });

            return rrp && dis ? this.getFormattedPrice(rrp - dis) : false;
        }
    });
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/view/summary/discount', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote'
], function (Component, quote) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_SalesRule/summary/discount'
        },
        totals: quote.getTotals(),

        /**
         * @return {*|Boolean}
         */
        isDisplayed: function () {
            return this.isFullMode() && this.getPureValue() != 0; //eslint-disable-line eqeqeq
        },

        /**
         * @return {*}
         */
        getCouponCode: function () {
            if (!this.totals()) {
                return null;
            }

            return this.totals()['coupon_code'];
        },

        /**
         * @return {*}
         */
        getCouponLabel: function () {
            if (!this.totals()) {
                return null;
            }

            return this.totals()['coupon_label'];
        },

        /**
         * Get discount title
         *
         * @returns {null|String}
         */
        getTitle: function () {
            var discountSegments;

            if (!this.totals()) {
                return null;
            }

            discountSegments = this.totals()['total_segments'].filter(function (segment) {
                return segment.code.indexOf('discount') !== -1;
            });

            return discountSegments.length ? discountSegments[0].title : null;
        },

        /**
         * @return {Number}
         */
        getPureValue: function () {
            var price = 0;

            if (this.totals() && this.totals()['discount_amount']) {
                price = parseFloat(this.totals()['discount_amount']);
            }

            return price;
        },

        /**
         * @return {*|String}
         */
        getValue: function () {
            return this.getFormattedPrice(this.getPureValue());
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/view/cart/totals/discount', [
    'Magento_SalesRule/js/view/summary/discount'
], function (Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_SalesRule/cart/totals/discount'
        },

        /**
         * @override
         *
         * @returns {Boolean}
         */
        isDisplayed: function () {
            return this.getPureValue() != 0; //eslint-disable-line eqeqeq
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/summary/grand-total', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/totals'
], function (Component, quote, priceUtils, totals) {
    'use strict';

    return Component.extend({
        defaults: {
            isFullTaxSummaryDisplayed: window.checkoutConfig.isFullTaxSummaryDisplayed || false,
            template: 'Magento_Tax/checkout/summary/grand-total'
        },
        totals: quote.getTotals(),
        isTaxDisplayedInGrandTotal: window.checkoutConfig.includeTaxInGrandTotal || false,

        /**
         * @return {*}
         */
        isDisplayed: function () {
            return this.isFullMode();
        },

        /**
         * @return {*|String}
         */
        getValue: function () {
            var price = 0;

            if (this.totals()) {
                price = totals.getSegment('grand_total').value;
            }

            return this.getFormattedPrice(price);
        },

        /**
         * @return {*|String}
         */
        getBaseValue: function () {
            var price = 0;

            if (this.totals()) {
                price = this.totals()['base_grand_total'];
            }

            return priceUtils.formatPriceLocale(price, quote.getBasePriceFormat());
        },

        /**
         * @return {*}
         */
        getGrandTotalExclTax: function () {
            var total = this.totals();

            if (!total) {
                return 0;
            }

            return this.getFormattedPrice(total['grand_total']);
        },

        /**
         * @return {Boolean}
         */
        isBaseGrandTotalDisplayNeeded: function () {
            var total = this.totals();

            if (!total) {
                return false;
            }

            return total['base_currency_code'] != total['quote_currency_code']; //eslint-disable-line eqeqeq
        }
    });
});

define('Bss_CheckoutWithDisplayCurrency/js/view/checkout/summary/grand-total-mixin', [
    'jquery',
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/totals'
], function ($, Component, quote, priceUtils, totals) {
    return function (target) {
        return target.extend({
            /**
             * @return {*}
             */
            isBaseGrandTotalDisplayNeeded: function () {
                var total = this.totals();
                var bssShowMessage = window.checkoutConfig.bssShowMessage;
                if (!total) {
                    return false;
                }

                if (bssShowMessage) {
                    $('tr.totals.charge').show();
                    return true;
                }

                return total['base_currency_code'] != total['quote_currency_code'];
            }
        });
    }
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/cart/totals/grand-total', [
    'Magento_Tax/js/view/checkout/summary/grand-total'
], function (Component) {
    'use strict';

    return Component.extend({
        /**
         * @override
         */
        isDisplayed: function () {
            return true;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/shipping', [
    'jquery',
    'underscore',
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'Magento_SalesRule/js/view/summary/discount'
], function ($, _, Component, quote, discountView) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/shipping'
        },
        quoteIsVirtual: quote.isVirtual(),
        totals: quote.getTotals(),

        /**
         * @return {*}
         */
        getShippingMethodTitle: function () {
            var shippingMethod,
                shippingMethodTitle = '';

            if (!this.isCalculated()) {
                return '';
            }
            shippingMethod = quote.shippingMethod();

            if (!_.isArray(shippingMethod) && !_.isObject(shippingMethod)) {
                return '';
            }

            if (typeof shippingMethod['method_title'] !== 'undefined') {
                shippingMethodTitle = ' - ' + shippingMethod['method_title'];
            }

            return shippingMethodTitle ?
                shippingMethod['carrier_title'] + shippingMethodTitle :
                shippingMethod['carrier_title'];
        },

        /**
         * @return {*|Boolean}
         */
        isCalculated: function () {
            return this.totals() && this.isFullMode() && quote.shippingMethod() != null; //eslint-disable-line eqeqeq
        },

        /**
         * @return {*}
         */
        getValue: function () {
            var price;

            if (!this.isCalculated()) {
                return this.notCalculatedMessage;
            }
            price =  this.totals()['shipping_amount'];

            return this.getFormattedPrice(price);
        },

        /**
         * If is set coupon code, but there wasn't displayed discount view.
         *
         * @return {Boolean}
         */
        haveToShowCoupon: function () {
            var couponCode = this.totals()['coupon_code'];

            if (typeof couponCode === 'undefined') {
                couponCode = false;
            }

            return couponCode && !discountView().isDisplayed();
        },

        /**
         * Returns coupon code description.
         *
         * @return {String}
         */
        getCouponDescription: function () {
            if (!this.haveToShowCoupon()) {
                return '';
            }

            return '(' + this.totals()['coupon_code'] + ')';
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/summary/shipping', [
    'jquery',
    'Magento_Checkout/js/view/summary/shipping',
    'Magento_Checkout/js/model/quote'
], function ($, Component, quote) {
    'use strict';

    var displayMode = window.checkoutConfig.reviewShippingDisplayMode;

    return Component.extend({
        defaults: {
            displayMode: displayMode,
            template: 'Magento_Tax/checkout/summary/shipping'
        },

        /**
         * @return {Boolean}
         */
        isBothPricesDisplayed: function () {
            return this.displayMode == 'both'; //eslint-disable-line eqeqeq
        },

        /**
         * @return {Boolean}
         */
        isIncludingDisplayed: function () {
            return this.displayMode == 'including'; //eslint-disable-line eqeqeq
        },

        /**
         * @return {Boolean}
         */
        isExcludingDisplayed: function () {
            return this.displayMode == 'excluding'; //eslint-disable-line eqeqeq
        },

        /**
         * @return {*|Boolean}
         */
        isCalculated: function () {
            return this.totals() && this.isFullMode() && quote.shippingMethod() != null;
        },

        /**
         * @return {*}
         */
        getIncludingValue: function () {
            var price;

            if (!this.isCalculated()) {
                return this.notCalculatedMessage;
            }
            price = this.totals()['shipping_incl_tax'];

            return this.getFormattedPrice(price);
        },

        /**
         * @return {*}
         */
        getExcludingValue: function () {
            var price;

            if (!this.isCalculated()) {
                return this.notCalculatedMessage;
            }
            price = this.totals()['shipping_amount'];

            return this.getFormattedPrice(price);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/cart/totals/shipping', [
    'Magento_Tax/js/view/checkout/summary/shipping',
    'Magento_Checkout/js/model/quote'
], function (Component, quote) {
    'use strict';

    return Component.extend({
        /**
         * @override
         */
        isCalculated: function () {
            return !!quote.shippingMethod();
        },

        /**
         * @override
         */
        getShippingMethodTitle: function () {
            return '(' + this._super() + ')';
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * @api
 */
define('Magento_Checkout/js/model/new-customer-address', [
    'underscore',
    'Magento_Checkout/js/model/default-post-code-resolver'
], function (_, DefaultPostCodeResolver) {
    'use strict';

    /**
     * @param {Object} addressData
     * Returns new address object
     */
    return function (addressData) {
        var identifier = Date.now(),
            countryId = addressData['country_id'] || addressData.countryId || window.checkoutConfig.defaultCountryId,
            regionId;

        if (addressData.region && addressData.region['region_id']) {
            regionId = addressData.region['region_id'];
        } else if (!addressData['region_id']) {
            regionId = undefined;
        } else if (
            /* eslint-disable */
            addressData['country_id'] && addressData['country_id'] == window.checkoutConfig.defaultCountryId ||
            !addressData['country_id'] && countryId == window.checkoutConfig.defaultCountryId
            /* eslint-enable */
        ) {
            regionId = window.checkoutConfig.defaultRegionId || undefined;
        }

        return {
            email: addressData.email,
            countryId: countryId,
            regionId: regionId || addressData.regionId,
            regionCode: addressData.region ? addressData.region['region_code'] : null,
            region: addressData.region ? addressData.region.region : null,
            customerId: addressData['customer_id'] || addressData.customerId,
            street: addressData.street ? _.compact(addressData.street) : addressData.street,
            company: addressData.company,
            telephone: addressData.telephone,
            fax: addressData.fax,
            postcode: addressData.postcode ? addressData.postcode : DefaultPostCodeResolver.resolve(),
            city: addressData.city,
            firstname: addressData.firstname,
            lastname: addressData.lastname,
            middlename: addressData.middlename,
            prefix: addressData.prefix,
            suffix: addressData.suffix,
            vatId: addressData['vat_id'],
            saveInAddressBook: addressData['save_in_address_book'],
            customAttributes: addressData['custom_attributes'],
            extensionAttributes: addressData['extension_attributes'],

            /**
             * @return {*}
             */
            isDefaultShipping: function () {
                return addressData['default_shipping'];
            },

            /**
             * @return {*}
             */
            isDefaultBilling: function () {
                return addressData['default_billing'];
            },

            /**
             * @return {String}
             */
            getType: function () {
                return 'new-customer-address';
            },

            /**
             * @return {String}
             */
            getKey: function () {
                return this.getType();
            },

            /**
             * @return {String}
             */
            getCacheKey: function () {
                return this.getType() + identifier;
            },

            /**
             * @return {Boolean}
             */
            isEditable: function () {
                return true;
            },

            /**
             * @return {Boolean}
             */
            canUseForBilling: function () {
                return true;
            }
        };
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * @api
 */
define('Magento_Checkout/js/model/address-converter', [
    'jquery',
    'Magento_Checkout/js/model/new-customer-address',
    'Magento_Customer/js/customer-data',
    'mage/utils/objects',
    'underscore'
], function ($, address, customerData, mageUtils, _) {
    'use strict';

    var countryData = customerData.get('directory-data');

    return {
        /**
         * Convert address form data to Address object
         *
         * @param {Object} formData
         * @returns {Object}
         */
        formAddressDataToQuoteAddress: function (formData) {
            // clone address form data to new object
            var addressData = $.extend(true, {}, formData),
                region,
                regionName = addressData.region,
                customAttributes;

            if (mageUtils.isObject(addressData.street)) {
                addressData.street = this.objectToArray(addressData.street);
            }

            addressData.region = {
                'region_id': addressData['region_id'],
                'region_code': addressData['region_code'],
                region: regionName
            };

            if (addressData['region_id'] &&
                countryData()[addressData['country_id']] &&
                countryData()[addressData['country_id']].regions
            ) {
                region = countryData()[addressData['country_id']].regions[addressData['region_id']];

                if (region) {
                    addressData.region['region_id'] = addressData['region_id'];
                    addressData.region['region_code'] = region.code;
                    addressData.region.region = region.name;
                }
            } else if (
                !addressData['region_id'] &&
                countryData()[addressData['country_id']] &&
                countryData()[addressData['country_id']].regions
            ) {
                addressData.region['region_code'] = '';
                addressData.region.region = '';
            }
            delete addressData['region_id'];

            if (addressData['custom_attributes']) {
                addressData['custom_attributes'] = _.map(
                    addressData['custom_attributes'],
                    function (value, key) {
                        customAttributes = {
                            'attribute_code': key,
                            'value': value
                        };

                        if (typeof value === 'boolean') {
                            customAttributes = {
                                'attribute_code': key,
                                'value': value,
                                'label': value === true ? 'Yes' : 'No'
                            };
                        }

                        return customAttributes;
                    }
                );
            }

            return address(addressData);
        },

        /**
         * Convert Address object to address form data.
         *
         * @param {Object} addrs
         * @returns {Object}
         */
        quoteAddressToFormAddressData: function (addrs) {
            var self = this,
                output = {},
                streetObject,
                customAttributesObject;

            $.each(addrs, function (key) {
                if (addrs.hasOwnProperty(key) && typeof addrs[key] !== 'function') {
                    output[self.toUnderscore(key)] = addrs[key];
                }
            });

            if (Array.isArray(addrs.street)) {
                streetObject = {};
                addrs.street.forEach(function (value, index) {
                    streetObject[index] = value;
                });
                output.street = streetObject;
            }

            //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
            if (Array.isArray(addrs.customAttributes)) {
                customAttributesObject = {};
                addrs.customAttributes.forEach(function (value) {
                    customAttributesObject[value.attribute_code] = value.value;
                });
                output.custom_attributes = customAttributesObject;
            }
            //jscs:enable requireCamelCaseOrUpperCaseIdentifiers

            return output;
        },

        /**
         * @param {String} string
         */
        toUnderscore: function (string) {
            return string.replace(/([A-Z])/g, function ($1) {
                return '_' + $1.toLowerCase();
            });
        },

        /**
         * @param {Object} formProviderData
         * @param {String} formIndex
         * @return {Object}
         */
        formDataProviderToFlatData: function (formProviderData, formIndex) {
            var addressData = {};

            $.each(formProviderData, function (path, value) {
                var pathComponents = path.split('.'),
                    dataObject = {};

                pathComponents.splice(pathComponents.indexOf(formIndex), 1);
                pathComponents.reverse();
                $.each(pathComponents, function (index, pathPart) {
                    var parent = {};

                    if (index == 0) { //eslint-disable-line eqeqeq
                        dataObject[pathPart] = value;
                    } else {
                        parent[pathPart] = dataObject;
                        dataObject = parent;
                    }
                });
                $.extend(true, addressData, dataObject);
            });

            return addressData;
        },

        /**
         * Convert object to array
         * @param {Object} object
         * @returns {Array}
         */
        objectToArray: function (object) {
            var convertedArray = [];

            $.each(object, function (key) {
                return typeof object[key] === 'string' ? convertedArray.push(object[key]) : false;
            });

            return convertedArray.slice(0);
        },

        /**
         * @param {Object} addrs
         * @return {*|Object}
         */
        addressToEstimationAddress: function (addrs) {
            var self = this,
                estimatedAddressData = {};

            $.each(addrs, function (key) {
                estimatedAddressData[self.toUnderscore(key)] = addrs[key];
            });

            return this.formAddressDataToQuoteAddress(estimatedAddressData);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/create-billing-address', [
    'Magento_Checkout/js/model/address-converter'
], function (addressConverter) {
    'use strict';

    return function (addressData) {
        var address = addressConverter.formAddressDataToQuoteAddress(addressData);

        /**
         * Returns new customer billing address type.
         *
         * @returns {String}
         */
        address.getType = function () {
            return 'new-customer-billing-address';
        };

        return address;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Cart adapter for customer data storage.
 * It stores cart data in customer data(localStorage) without saving on server.
 * Adapter is created for shipping rates and totals data caching. It eliminates unneeded calculations requests.
 */
define('Magento_Checkout/js/model/cart/cache', [
    'underscore',
    'Magento_Customer/js/customer-data',
    'mageUtils'
], function (_, storage, utils) {
    'use strict';

    var cacheKey = 'cart-data',
        cartData = {
            totals: null,
            address: null,
            cartVersion: null,
            shippingMethodCode: null,
            shippingCarrierCode: null,
            rates: null
        },

        /**
         * Set data to local storage.
         *
         * @param {Object} checkoutData
         */
        setData = function (checkoutData) {
            storage.set(cacheKey, checkoutData);
        },

        /**
         * Get data from local storage.
         *
         * @param {String} [key]
         * @returns {*}
         */
        getData = function (key) {
            var data = key ? storage.get(cacheKey)()[key] : storage.get(cacheKey)();

            if (_.isEmpty(storage.get(cacheKey)())) {
                setData(utils.copy(cartData));
            }

            return data;
        },

        /**
         * Build method name base on name, prefix and suffix.
         *
         * @param {String} name
         * @param {String} prefix
         * @param {String} suffix
         * @return {String}
         */
        getMethodName = function (name, prefix, suffix) {
            prefix = prefix || '';
            suffix = suffix || '';

            return prefix + name.charAt(0).toUpperCase() + name.slice(1) + suffix;
        };

    /**
     * Provides get/set/isChanged/clear methods for work with cart data.
     * Can be customized via mixin functionality.
     */
    return {
        cartData: cartData,

        /**
         * Array of required address fields
         */
        requiredFields: ['countryId', 'region', 'regionId', 'postcode'],

        /**
         * Get data from customer data.
         * Concatenate provided key with method name and call method if it exist or makes get by key.
         *
         * @param {String} key
         * @return {*}
         */
        get: function (key) {
            var methodName = getMethodName(key, '_get');

            if (key === cacheKey) {
                return getData();
            }

            if (this[methodName]) {
                return this[methodName]();
            }

            return getData(key);
        },

        /**
         * Set data to customer data.
         * Concatenate provided key with method name and call method if it exist or makes set by key.
         * @example _setCustomAddress method will be called, if it exists.
         *  set('address', customAddressValue)
         * @example Will set value by provided key.
         *  set('rates', ratesToCompare)
         *
         * @param {String} key
         * @param {*} value
         */
        set: function (key, value) {
            var methodName = getMethodName(key, '_set'),
                obj;

            if (key === cacheKey) {
                _.each(value, function (val, k) {
                    this.set(k, val);
                }, this);

                return;
            }

            if (this[methodName]) {
                this[methodName](value);
            } else {
                obj = getData();
                obj[key] = value;
                setData(obj);
            }
        },

        /**
         * Clear data in cache.
         * Concatenate provided key with method name and call method if it exist or clear by key.
         * @example _clearCustomAddress method will be called, if it exist.
         *  clear('customAddress')
         * @example Will clear data by provided key.
         *  clear('rates')
         *
         * @param {String} key
         */
        clear: function (key) {
            var methodName = getMethodName(key, '_clear');

            if (key === cacheKey) {
                setData(this.cartData);

                return;
            }

            if (this[methodName]) {
                this[methodName]();
            } else {
                this.set(key, null);
            }
        },

        /**
         * Check if provided data has difference with cached data.
         * Concatenate provided key with method name and call method if it exist or makes strict equality.
         * @example Will call existing _isAddressChanged.
         *  isChanged('address', addressToCompare)
         * @example Will get data by provided key and make strict equality with provided value.
         *  isChanged('rates', ratesToCompare)
         *
         * @param {String} key
         * @param {*} value
         * @return {Boolean}
         */
        isChanged: function (key, value) {
            var methodName = getMethodName(key, '_is', 'Changed');

            if (this[methodName]) {
                return this[methodName](value);
            }

            return this.get(key) !== value;
        },

        /**
         * Compare cached address with provided.
         * Custom method for check object equality.
         *
         * @param {Object} address
         * @returns {Boolean}
         */
        _isAddressChanged: function (address) {
            return JSON.stringify(_.pick(this.get('address'), this.requiredFields)) !==
                JSON.stringify(_.pick(address, this.requiredFields));
        },

        /**
         * Compare cached subtotal with provided.
         * Custom method for check object equality.
         *
         * @param {float} subtotal
         * @returns {Boolean}
         */
        _isSubtotalChanged: function (subtotal) {
            var cached = parseFloat(this.get('totals').subtotal);

            return subtotal !== cached;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Ui/js/lib/spinner', [
    'jquery'
], function ($) {
    'use strict';

    var selector = '[data-role="spinner"]',
        spinner = $(selector);

    return {
        /**
         * Show spinner.
         */
        show: function () {
            spinner.show();
        },

        /**
         * Hide spinner.
         */
        hide: function () {
            spinner.hide();
        },

        /**
         * Get spinner by selector.
         *
         * @param {String} id
         * @return {jQuery}
         */
        get: function (id) {
            return $(selector + '[data-component="' + id + '"]');
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Ui/js/model/messageList', [
    './messages'
], function (Messages) {
    'use strict';

    return new Messages();
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/error-processor', ['mage/url', 'Magento_Ui/js/model/messageList', 'mage/translate'], function(
    url,
    globalMessageList,
    $t
) {
    'use strict';

    return {
        /**
         * @param {Object} response
         * @param {Object} messageContainer
         */
        process: function(response, messageContainer) {
            var error;

            messageContainer = messageContainer || globalMessageList;

            function isFieldName(fieldName)
            {
                if (error.hasOwnProperty('parameters') &&
                    error.parameters.hasOwnProperty('fieldName') &&
                    error.parameters.fieldName === fieldName) {
                        return true;
                }

                return false;
            }

            if (response.status == 401) {
                //eslint-disable-line eqeqeq
                window.location.replace(url.build('customer/account/login/'));
            } else {
                try {
                    error = JSON.parse(response.responseText);

                    // Force translation to happen here as server translation is broken in this instance
                    if (error.message === '"%fieldName" is required. Enter and try again.') {
                        error.message = $t('"%fieldName" is required. Enter and try again.');

                        if (isFieldName('address')) {
                            error.message = $t(
                                'Please complete your address.'
                            );
                        }
                    }

                    if (
                        error.message ===
                        'The coupon code isn\'t valid. Verify the code and try again.'
                    ) {
                        error.message = $t(
                            'The coupon code isn\'t valid. Verify the code and try again.'
                        );
                    }
                } catch (exception) {
                    error = {
                        message: $t(
                            'Something went wrong with your request. Please try again later.'
                        )
                    };
                }

                messageContainer.addErrorMessage(error);
            }
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_GiftMessage/js/action/gift-options', [
    'Magento_GiftMessage/js/model/url-builder',
    'mage/storage',
    'Magento_Ui/js/model/messageList',
    'Magento_Checkout/js/model/error-processor',
    'mage/url',
    'Magento_Checkout/js/model/quote',
    'underscore'
], function (urlBuilder, storage, messageList, errorProcessor, url, quote, _) {
    'use strict';

    return function (giftMessage, remove) {
        var serviceUrl;

        url.setBaseUrl(giftMessage.getConfigValue('baseUrl'));

        if (giftMessage.getConfigValue('isCustomerLoggedIn')) {
            serviceUrl = urlBuilder.createUrl('/carts/mine/gift-message', {});

            if (giftMessage.itemId != 'orderLevel') { //eslint-disable-line eqeqeq
                serviceUrl = urlBuilder.createUrl('/carts/mine/gift-message/:itemId', {
                    itemId: giftMessage.itemId
                });
            }
        } else {
            serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/gift-message', {
                cartId: quote.getQuoteId()
            });

            if (giftMessage.itemId != 'orderLevel') { //eslint-disable-line eqeqeq
                serviceUrl = urlBuilder.createUrl(
                    '/guest-carts/:cartId/gift-message/:itemId',
                    {
                        cartId: quote.getQuoteId(), itemId: giftMessage.itemId
                    }
                );
            }
        }
        messageList.clear();

        storage.post(
            serviceUrl,
            JSON.stringify({
                'gift_message': giftMessage.getSubmitParams(remove)
            })
        ).done(function () {
            giftMessage.reset();
            _.each(giftMessage.getAfterSubmitCallbacks(), function (callback) {
                if (_.isFunction(callback)) {
                    callback();
                }
            });
        }).fail(function (response) {
            errorProcessor.process(response);
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_GiftMessage/js/view/gift-message', [
    'uiComponent',
    'Magento_GiftMessage/js/model/gift-message',
    'Magento_GiftMessage/js/model/gift-options',
    'Magento_GiftMessage/js/action/gift-options'
], function (Component, GiftMessage, giftOptions, giftOptionsService) {
    'use strict';

    return Component.extend({
        formBlockVisibility: null,
        resultBlockVisibility: null,
        model: {},

        /**
         * Component init
         */
        initialize: function () {
            var self = this,
                model;

            this._super()
                .observe('formBlockVisibility')
                .observe({
                    'resultBlockVisibility': false
                });

            this.itemId = this.itemId || 'orderLevel';
            model = new GiftMessage(this.itemId);
            this.model = model;
            this.isResultBlockVisible();
            giftOptions.addOption(model);

            this.model.getObservable('isClear').subscribe(function (value) {
                if (value == true) { //eslint-disable-line eqeqeq
                    self.formBlockVisibility(false);
                    self.model.getObservable('alreadyAdded')(true);
                }
            });
        },

        /**
         * Is reslt block visible
         */
        isResultBlockVisible: function () {
            var self = this;

            if (this.model.getObservable('alreadyAdded')()) {
                this.resultBlockVisibility(true);
            }
            this.model.getObservable('additionalOptionsApplied').subscribe(function (value) {
                if (value == true) { //eslint-disable-line eqeqeq
                    self.resultBlockVisibility(true);
                }
            });
        },

        /**
         * @param {String} key
         * @return {*}
         */
        getObservable: function (key) {
            return this.model.getObservable(key);
        },

        /**
         * Hide\Show form block
         */
        toggleFormBlockVisibility: function () {
            if (!this.model.getObservable('alreadyAdded')()) {
                this.formBlockVisibility(!this.formBlockVisibility());
            } else {
                this.resultBlockVisibility(!this.resultBlockVisibility());
            }
        },

        /**
         * Edit options
         */
        editOptions: function () {
            this.resultBlockVisibility(false);
            this.formBlockVisibility(true);
        },

        /**
         * Delete options
         */
        deleteOptions: function () {
            giftOptionsService(this.model, true);
        },

        /**
         * Hide form block
         */
        hideFormBlock: function () {
            this.formBlockVisibility(false);

            if (this.model.getObservable('alreadyAdded')()) {
                this.resultBlockVisibility(true);
            }
        },

        /**
         * @return {Boolean}
         */
        hasActiveOptions: function () {
            var regionData = this.getRegion('additionalOptions'),
                options = regionData(),
                i;

            for (i = 0; i < options.length; i++) {
                if (options[i].isActive()) {
                    return true;
                }
            }

            return false;
        },

        /**
         * @return {Boolean}
         */
        isActive: function () {
            return this.model.isGiftMessageAvailable();
        },

        /**
         * Submit options
         */
        submitOptions: function () {
            giftOptionsService(this.model);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * @api
 */
define('Magento_Checkout/js/model/place-order', 
    [
        'mage/storage',
        'Magento_Checkout/js/model/error-processor',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Customer/js/customer-data',
        'Magento_Checkout/js/model/payment/place-order-hooks',
        'underscore'
    ],
    function (storage, errorProcessor, fullScreenLoader, customerData, hooks, _) {
        'use strict';

        return function (serviceUrl, payload, messageContainer) {
            var headers = {};

            fullScreenLoader.startLoader();
            _.each(hooks.requestModifiers, function (modifier) {
                modifier(headers, payload);
            });

            return storage.post(
                serviceUrl, JSON.stringify(payload), true, 'application/json', headers
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageContainer);
                }
            ).done(
                function (response) {
                    var clearData = {
                        'selectedShippingAddress': null,
                        'shippingAddressFromData': null,
                        'newCustomerShippingAddress': null,
                        'selectedShippingRate': null,
                        'selectedPaymentMethod': null,
                        'selectedBillingAddress': null,
                        'billingAddressFromData': null,
                        'newCustomerBillingAddress': null
                    };

                    if (response.responseType !== 'error') {
                        customerData.set('checkout-data', clearData);
                    }
                }
            ).always(
                function () {
                    fullScreenLoader.stopLoader();
                    _.each(hooks.afterRequestListeners, function (listener) {
                        listener();
                    });
                }
            );
        };
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/default-validation-rules', [], function () {
    'use strict';

    return {
        /**
         * @return {Object}
         */
        getRules: function () {
            return {
                'country_id': {
                    'required': true
                }
            };
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/default-validator', [
    'jquery',
    'mageUtils',
    './default-validation-rules',
    'mage/translate'
], function ($, utils, validationRules, $t) {
    'use strict';

    return {
        validationErrors: [],

        /**
         * @param {Object} address
         * @return {Boolean}
         */
        validate: function (address) {
            var self = this;

            this.validationErrors = [];
            $.each(validationRules.getRules(), function (field, rule) {
                var message;

                if (rule.required && utils.isEmpty(address[field])) {
                    message = $t('Field ') + field + $t(' is required.');

                    self.validationErrors.push(message);
                }
            });

            return !this.validationErrors.length;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/shipping-rates-validator', [
    'jquery',
    'ko',
    './shipping-rates-validation-rules',
    '../model/address-converter',
    '../action/select-shipping-address',
    './postcode-validator',
    './default-validator',
    'mage/translate',
    'uiRegistry',
    'Magento_Checkout/js/model/shipping-address/form-popup-state',
    'Magento_Checkout/js/model/quote'
], function (
    $,
    ko,
    shippingRatesValidationRules,
    addressConverter,
    selectShippingAddress,
    postcodeValidator,
    defaultValidator,
    $t,
    uiRegistry,
    formPopUpState
) {
    'use strict';

    var checkoutConfig = window.checkoutConfig,
        validators = [],
        observedElements = [],
        postcodeElements = [],
        postcodeElementName = 'postcode';

    validators.push(defaultValidator);

    return {
        validateAddressTimeout: 0,
        validateZipCodeTimeout: 0,
        validateDelay: 2000,

        /**
         * @param {String} carrier
         * @param {Object} validator
         */
        registerValidator: function (carrier, validator) {
            if (checkoutConfig.activeCarriers.indexOf(carrier) !== -1) {
                validators.push(validator);
            }
        },

        /**
         * @param {Object} address
         * @return {Boolean}
         */
        validateAddressData: function (address) {
            return validators.some(function (validator) {
                return validator.validate(address);
            });
        },

        /**
         * Perform postponed binding for fieldset elements
         *
         * @param {String} formPath
         */
        initFields: function (formPath) {
            var self = this,
                elements = shippingRatesValidationRules.getObservableFields();

            if ($.inArray(postcodeElementName, elements) === -1) {
                // Add postcode field to observables if not exist for zip code validation support
                elements.push(postcodeElementName);
            }

            $.each(elements, function (index, field) {
                uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self));
            });
        },

        /**
         * Bind shipping rates request to form element
         *
         * @param {Object} element
         * @param {Boolean} force
         * @param {Number} delay
         */
        doElementBinding: function (element, force, delay) {
            var observableFields = shippingRatesValidationRules.getObservableFields();

            if (element && (observableFields.indexOf(element.index) !== -1 || force)) {
                if (element.index !== postcodeElementName) {
                    this.bindHandler(element, delay);
                }
            }

            if (element.index === postcodeElementName) {
                this.bindHandler(element, delay);
                postcodeElements.push(element);
            }
        },

        /**
         * @param {*} elements
         * @param {Boolean} force
         * @param {Number} delay
         */
        bindChangeHandlers: function (elements, force, delay) {
            var self = this;

            $.each(elements, function (index, elem) {
                self.doElementBinding(elem, force, delay);
            });
        },

        /**
         * @param {Object} element
         * @param {Number} delay
         */
        bindHandler: function (element, delay) {
            var self = this;

            delay = typeof delay === 'undefined' ? self.validateDelay : delay;

            if (element.component.indexOf('/group') !== -1) {
                $.each(element.elems(), function (index, elem) {
                    self.bindHandler(elem);
                });
            } else {
                element.on('value', function () {
                    clearTimeout(self.validateZipCodeTimeout);
                    self.validateZipCodeTimeout = setTimeout(function () {
                        if (element.index === postcodeElementName) {
                            self.postcodeValidation(element);
                        } else {
                            $.each(postcodeElements, function (index, elem) {
                                self.postcodeValidation(elem);
                            });
                        }
                    }, delay);

                    if (!formPopUpState.isVisible()) {
                        clearTimeout(self.validateAddressTimeout);
                        self.validateAddressTimeout = setTimeout(function () {
                            self.validateFields();
                        }, delay);
                    }
                });
                observedElements.push(element);
            }
        },

        /**
         * @return {*}
         */
        postcodeValidation: function (postcodeElement) {
            var countryId = $('select[name="country_id"]:visible').val(),
                validationResult,
                warnMessage;

            if (postcodeElement == null || postcodeElement.value() == null) {
                return true;
            }

            postcodeElement.warn(null);
            validationResult = postcodeValidator.validate(postcodeElement.value(), countryId);

            if (!validationResult) {
                warnMessage = $t('Provided Zip/Postal Code seems to be invalid.');

                if (postcodeValidator.validatedPostCodeExample.length) {
                    warnMessage += $t(' Example: ') + postcodeValidator.validatedPostCodeExample.join('; ') + '. ';
                }
                warnMessage += $t('If you believe it is the right one you can ignore this notice.');
                postcodeElement.warn(warnMessage);
            }

            return validationResult;
        },

        /**
         * Convert form data to quote address and validate fields for shipping rates
         */
        validateFields: function () {
            var addressFlat = addressConverter.formDataProviderToFlatData(
                this.collectObservedData(),
                'shippingAddress'
                ),
                address;

            if (this.validateAddressData(addressFlat)) {
                addressFlat = uiRegistry.get('checkoutProvider').shippingAddress;
                address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
                selectShippingAddress(address);
            }
        },

        /**
         * Collect observed fields data to object
         *
         * @returns {*}
         */
        collectObservedData: function () {
            var observedValues = {};

            $.each(observedElements, function (index, field) {
                observedValues[field.dataScope] = field.value();
            });

            return observedValues;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/view/shipping-rates-validation/flatrate', [
    'uiComponent',
    'Magento_Checkout/js/model/shipping-rates-validator',
    'Magento_Checkout/js/model/shipping-rates-validation-rules',
    '../../model/shipping-rates-validator/flatrate',
    '../../model/shipping-rates-validation-rules/flatrate'
], function (
    Component,
    defaultShippingRatesValidator,
    defaultShippingRatesValidationRules,
    flatrateShippingRatesValidator,
    flatrateShippingRatesValidationRules
) {
    'use strict';

    defaultShippingRatesValidator.registerValidator('flatrate', flatrateShippingRatesValidator);
    defaultShippingRatesValidationRules.registerRules('flatrate', flatrateShippingRatesValidationRules);

    return Component;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/view/shipping-rates-validation/freeshipping', [
    'uiComponent',
    'Magento_Checkout/js/model/shipping-rates-validator',
    'Magento_Checkout/js/model/shipping-rates-validation-rules',
    '../../model/shipping-rates-validator/freeshipping',
    '../../model/shipping-rates-validation-rules/freeshipping'
], function (
    Component,
    defaultShippingRatesValidator,
    defaultShippingRatesValidationRules,
    freeshippingShippingRatesValidator,
    freeshippingShippingRatesValidationRules
) {
    'use strict';

    defaultShippingRatesValidator.registerValidator('freeshipping', freeshippingShippingRatesValidator);
    defaultShippingRatesValidationRules.registerRules('freeshipping', freeshippingShippingRatesValidationRules);

    return Component;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_OfflineShipping/js/view/shipping-rates-validation/tablerate', [
    'uiComponent',
    'Magento_Checkout/js/model/shipping-rates-validator',
    'Magento_Checkout/js/model/shipping-rates-validation-rules',
    '../../model/shipping-rates-validator/tablerate',
    '../../model/shipping-rates-validation-rules/tablerate'
], function (
    Component,
    defaultShippingRatesValidator,
    defaultShippingRatesValidationRules,
    tablerateShippingRatesValidator,
    tablerateShippingRatesValidationRules
) {
    'use strict';

    defaultShippingRatesValidator.registerValidator('tablerate', tablerateShippingRatesValidator);
    defaultShippingRatesValidationRules.registerRules('tablerate', tablerateShippingRatesValidationRules);

    return Component;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Customer/js/model/customer/address', ['underscore'], function (_) {
    'use strict';

    /**
     * Returns new address object.
     *
     * @param {Object} addressData
     * @return {Object}
     */
    return function (addressData) {
        var regionId;

        if (addressData.region['region_id'] && addressData.region['region_id'] !== '0') {
            regionId = addressData.region['region_id'] + '';
        }

        return {
            customerAddressId: addressData.id,
            email: addressData.email,
            countryId: addressData['country_id'],
            regionId: regionId,
            regionCode: addressData.region['region_code'],
            region: addressData.region.region,
            customerId: addressData['customer_id'],
            street: addressData.street,
            company: addressData.company,
            telephone: addressData.telephone,
            fax: addressData.fax,
            postcode: addressData.postcode,
            city: addressData.city,
            firstname: addressData.firstname,
            lastname: addressData.lastname,
            middlename: addressData.middlename,
            prefix: addressData.prefix,
            suffix: addressData.suffix,
            vatId: addressData['vat_id'],
            sameAsBilling: addressData['same_as_billing'],
            saveInAddressBook: addressData['save_in_address_book'],
            customAttributes: _.toArray(addressData['custom_attributes']).reverse(),

            /**
             * @return {*}
             */
            isDefaultShipping: function () {
                return addressData['default_shipping'];
            },

            /**
             * @return {*}
             */
            isDefaultBilling: function () {
                return addressData['default_billing'];
            },

            /**
             * @return {*}
             */
            getAddressInline: function () {
                return addressData.inline;
            },

            /**
             * @return {String}
             */
            getType: function () {
                return 'customer-address';
            },

            /**
             * @return {String}
             */
            getKey: function () {
                return this.getType() + this.customerAddressId;
            },

            /**
             * @return {String}
             */
            getCacheKey: function () {
                return this.getKey();
            },

            /**
             * @return {Boolean}
             */
            isEditable: function () {
                return false;
            },

            /**
             * @return {Boolean}
             */
            canUseForBilling: function () {
                return true;
            }
        };
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Customer/js/model/customer-addresses', [
    'jquery',
    'ko',
    './customer/address'
], function ($, ko, Address) {
    'use strict';

    var isLoggedIn = ko.observable(window.isCustomerLoggedIn);

    return {
        /**
         * @return {Array}
         */
        getAddressItems: function () {
            var items = [],
                customerData = window.customerData;

            if (isLoggedIn()) {
                if (Object.keys(customerData).length) {
                    $.each(customerData.addresses, function (key, item) {
                        items.push(new Address(item));
                    });
                }
            }

            return items;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Customer/js/model/address-list', [
    'ko',
    './customer-addresses'
], function (ko, defaultProvider) {
    'use strict';

    return ko.observableArray(defaultProvider.getAddressItems());
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Customer/js/model/customer', [
    'jquery',
    'ko',
    'underscore',
    './address-list'
], function ($, ko, _, addressList) {
    'use strict';

    var isLoggedIn = ko.observable(window.isCustomerLoggedIn),
        customerData = {};

    if (isLoggedIn()) {
        customerData = window.customerData;
    } else {
        customerData = {};
    }

    return {
        customerData: customerData,
        customerDetails: {},
        isLoggedIn: isLoggedIn,

        /**
         * @param {Boolean} flag
         */
        setIsLoggedIn: function (flag) {
            isLoggedIn(flag);
        },

        /**
         * @return {Array}
         */
        getBillingAddressList: function () {
            return addressList();
        },

        /**
         * @return {Array}
         */
        getShippingAddressList: function () {
            return addressList();
        },

        /**
         * @param {String} fieldName
         * @param {*} value
         */
        setDetails: function (fieldName, value) {
            if (fieldName) {
                this.customerDetails[fieldName] = value;
            }
        },

        /**
         * @param {String} fieldName
         * @return {*}
         */
        getDetails: function (fieldName) {
            if (fieldName) {
                if (this.customerDetails.hasOwnProperty(fieldName)) {
                    return this.customerDetails[fieldName];
                }

                return undefined;
            }

            return this.customerDetails;
        },

        /**
         * @param {Array} address
         * @return {Number}
         */
        addCustomerAddress: function (address) {
            var fields = [
                    'customer_id', 'country_id', 'street', 'company', 'telephone', 'fax', 'postcode', 'city',
                    'firstname', 'lastname', 'middlename', 'prefix', 'suffix', 'vat_id', 'default_billing',
                    'default_shipping'
                ],
                customerAddress = {},
                hasAddress = 0,
                existingAddress;

            if (!this.customerData.addresses) {
                this.customerData.addresses = [];
            }

            customerAddress = _.pick(address, fields);

            if (address.hasOwnProperty('region_id')) {
                customerAddress.region = {
                    'region_id': address['region_id'],
                    region: address.region
                };
            }

            for (existingAddress in this.customerData.addresses) {
                if (this.customerData.addresses.hasOwnProperty(existingAddress)) {
                    if (_.isEqual(this.customerData.addresses[existingAddress], customerAddress)) { //eslint-disable-line
                        hasAddress = existingAddress;
                        break;
                    }
                }
            }

            if (hasAddress === 0) {
                return this.customerData.addresses.push(customerAddress) - 1;
            }

            return hasAddress;
        },

        /**
         * @param {*} addressId
         * @return {Boolean}
         */
        setAddressAsDefaultBilling: function (addressId) {
            if (this.customerData.addresses[addressId]) {
                this.customerData.addresses[addressId]['default_billing'] = 1;

                return true;
            }

            return false;
        },

        /**
         * @param {*} addressId
         * @return {Boolean}
         */
        setAddressAsDefaultShipping: function (addressId) {
            if (this.customerData.addresses[addressId]) {
                this.customerData.addresses[addressId]['default_shipping'] = 1;

                return true;
            }

            return false;
        }
    };
});

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/view/payment/utilities', 
    [
        'jquery',
        'CheckoutCom_Magento2/js/view/payment/config-loader',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/checkout-data',
        'mage/url',
        'Magento_Checkout/js/action/redirect-on-success',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Customer/js/model/customer',
        'mage/translate',
        'mage/cookies'
    ],
    function ($, Config, Quote, CheckoutData, Url, RedirectOnSuccessAction, FullScreenLoader, Customer, __) {
        'use strict';

        const KEY_CONFIG = 'checkoutcom_configuration';
        const KEY_DATA = 'checkoutcom_data';

        return {
            /**
             * Gets a field value.
             *
             * @param  {string}  methodId The method id
             * @param  {string}  field    The field
             * @param  {bool}  strict     The strict value
             * @return {mixed}            The value
             */
            getValue: function (methodId, field, strict) {
                var val = null;
                strict = (strict === undefined ? false : strict);
                if (methodId && Config.hasOwnProperty(methodId) && Config[methodId].hasOwnProperty(field)) {
                    val = Config[methodId][field]
                } else if (Config.hasOwnProperty(KEY_CONFIG) && Config[KEY_CONFIG].hasOwnProperty(field) && !strict) {
                    val = Config[KEY_CONFIG][field];
                }

                return val;
            },

            /**
             * Load a CSS file
             *
             * @return {void}
             */
            loadCss: function (fileName, folderPath) {
                // Prepare the folder path
                folderPath = (folderPath) ? '/' + folderPath : '';

                // Get the CSS config parameters
                var useMinCss = window.checkoutConfig.payment.checkoutcom_magento2.checkoutcom_data.use_minified_css;
                var ext = (useMinCss == '1') ? '.min.css' : '.css';

                // Build the payment form CSS path
                var cssPath = window.checkoutConfig.payment.checkoutcom_magento2.checkoutcom_data.css_path;
                cssPath += folderPath + '/' + fileName + ext;

                // Append the CSS file
                $('head').append('<link rel="stylesheet" href="' + cssPath + '" type="text/css"/>');
            },

            /**
             * Load a remote JS file
             *
             * @return {void}
             */
            loadRemoteJs: function (jsUrl) {
                // Append the CSS file
                $('head').append('<script type="text/javascript" src="' + jsUrl + '"></script>');
            },

            /**
             * Get the store name.
             *
             * @return {string}  The store name.
             */
            getStoreName: function () {
                return Config[KEY_DATA].store.name;
            },

            /**
             * Get the store country.
             *
             * @return {string}  The store country.
             */
            getStoreCountry: function () {
                return Config[KEY_DATA].store.country;
            },

            /**
             * Get the quote value.
             *
             * @return {float}  The quote value.
             */
            getQuoteValue: function () {
                var data = this.getRestQuoteData('payment-information');
                var collectTotals = data.totals.total_segments;
                var amount = null;

                collectTotals.forEach(function (total) {
                    if (total.code === "grand_total") {
                        amount = parseFloat(total.value);
                    }
                });

                return amount.toFixed(2);
            },

            /**
             * Get the updated quote data from the core REST API.
             *
             * @return {object}  The quote data.
             */
            getRestQuoteData: function (endpoint) {
                endpoint = (endpoint === null ? '' : '/' + endpoint);

                // Prepare the required parameters
                var self = this;
                var result = null;
                var restUrl = window.BASE_URL;

                // Build the rest URL
                if (Customer.isLoggedIn()) {
                    var store = window.checkoutConfig.storeCode ? window.checkoutConfig.storeCode : 'default';
                    restUrl += 'rest/';
                    restUrl += store;
                    restUrl += '/V1/';
                    restUrl += 'carts/mine';
                    restUrl += endpoint;
                    restUrl += '?form_key=' + window.checkoutConfig.formKey;
                } else {
                    restUrl += 'rest/all/V1/guest-carts/' + window.checkoutConfig.quoteData.entity_id;
                    restUrl += endpoint;
                    restUrl += '?form_key=' + window.checkoutConfig.formKey;
                }

                // Send the AJAX request
                $.ajax({
                    url: restUrl,
                    type: 'GET',
                    contentType: "application/json",
                    dataType: "json",
                    async: false,
                    showLoader: true,
                    success: function (data, status, xhr) {
                        result = data;
                    },
                    error: function (request, status, error) {
                        self.log(error);
                    }
                });

                return result;
            },

            /**
             * Get the quote currency.
             *
             * @return {string}  The quote currency.
             */
            getQuoteCurrency: function () {
                var data = this.getRestQuoteData('payment-information');
                return data.totals.quote_currency_code;
            },

            /**
             * Check if APM should be auto selected.
             *
             * @return {void}
             */
            checkLastPaymentMethod: function () {
                var userData = this.getValue('checkoutcom_data', 'user');

                if (userData['previous_method'] == 'checkoutcom_apm') {
                    // Select the previous apm if it's available
                    if ($('.cko-apm#' + userData['previous_source']).length) {
                        $('.cko-apm#' + userData['previous_source']).trigger('click');
                    }
                }
            },

            /**
             * Check if stored card should be auto selected.
             *
             * @return {void}
             */
            checkStoredCard: function () {
                var userData = this.getValue('checkoutcom_data', 'user');
                if (userData['previous_method'] == 'checkoutcom_vault'
                && $('input[name=\'publicHash\'][value=\''+userData['previous_source']+'\']').length) {
                    $('input[name=\'publicHash\'][value=\''+userData['previous_source']+'\']').trigger('click');
                }
            },

            /**
             * Gets the card form language fallback.
             *
             * @return {string}
             */
            getLangageFallback: function () {
                return Config[KEY_DATA].user.language_fallback;
            },

            /**
             * Get the card form shop language
             *
             * @return {string}
             */
            getShopLanguage: function () {
                let mageShopLanguage = Config[KEY_DATA].store.language;
                let framesLanguage;
                switch (mageShopLanguage) {
                    case 'nl_NL':
                        framesLanguage = 'NL-NL';
                        break;
                    case 'en_GB':
                        framesLanguage = 'EN-GB';
                        break;
                    case 'fr_FR':
                        framesLanguage = 'FR-FR';
                        break;
                    case 'de_DE':
                        framesLanguage = 'DE-DE';
                        break;
                    case 'it_IT':
                        framesLanguage = 'IT-IT';
                        break;
                    case 'ko_KR':
                        framesLanguage = 'KR-KR';
                        break;
                    case 'es_ES':
                        framesLanguage = 'ES-ES';
                        break;
                    default:
                        framesLanguage = this.getLangageFallback().toUpperCase().split("_").join('-');
                }

                return framesLanguage;
            },

            /**
             * Get the supported cards.
             *
             * @return {array}
             */
            getSupportedCards: function () {
                return Config[KEY_DATA].cards;
            },

            /**
             * Builds the controller URL.
             *
             * @param  {string}  path  The path
             * @return {string}
             */
            getUrl: function (path) {
                return Url.build('checkout_com/' + path);
            },

            /**
             * Customer name.
             *
             * @param  {bool} return in object format.
             * @return {mixed}  The billing address.
             */
            getCustomerName: function () {
                var billingAddress = this.getBillingAddress();
                var customerName = '';
                if (billingAddress && billingAddress.firstname && billingAddress.lastname) {
                        customerName += billingAddress.firstname;
                        customerName += ' ' + billingAddress.lastname;
                }

                return customerName;
            },

            /**
             * Billing address.
             *
             * @return {object}  The billing address.
             */
            getBillingAddress: function () {
                return this.getRestQuoteData('billing-address');
            },

            /**
             * @return {string}
             */
            getEmail: function () {
                var emailCookieName = this.getValue(null, 'email_cookie_name');
                return window.checkoutConfig.customerData.email
                || Quote.guestEmail
                || CheckoutData.getValidatedEmailValue()
                || $.cookie(emailCookieName);
            },

            /**
             * @return {void}
             */
            setEmail: function () {
                var userEmail = this.getEmail();
                var emailCookieName = this.getValue(null, 'email_cookie_name');
                $.cookie(emailCookieName, userEmail);

                // If no email found, observe the core email field
                if (!userEmail) {
                    $('#customer-email').off('change').on('change', function () {
                        userEmail = Quote.guestEmail || CheckoutData.getValidatedEmailValue();
                        $.cookie(emailCookieName, userEmail);
                    });
                }
            },

            /**
             * @return {object}
             */
            getPhone: function () {
                var billingAddress = this.getBillingAddress();

                return {
                    number: billingAddress.telephone
                };
            },

            /**
             * Handle error logging.
             */
            log: function (val) {
                if (this.getValue(null, 'debug')
                    && this.getValue(null, 'console_logging')
                ) {
                    console.log(val);
                }
            },

            /**
             * Show a message.
             */
            showMessage: function (type, message, methodId) {
                this.clearMessages(methodId);
                var messageContainer = this.getMethodContainer(methodId).find('.message-cko');
                messageContainer.addClass('message-' + type + ' ' + type);
                messageContainer.append('<div>' + __(message) + '</div>');
                messageContainer.show();
            },

            /**
             * Show debug message.
             */
            showDebugMessage: function (type, message, methodId) {
                var messageContainer = this.getMethodContainer(methodId).find('.debug-message');
                messageContainer.addClass('message-' + type + ' ' + type);
                messageContainer.append('<div><pre style="white-space:pre-wrap;word-break: break-word;">' + message + '</pre></div>');
                messageContainer.show();
            },

            /**
             * Show response code.
             */
            showResponseCode: function (type, message, methodId) {
                var messageContainer = this.getMethodContainer(methodId).find('.message-response-code');
                messageContainer.addClass('message-' + type + ' ' + type);
                messageContainer.append('<div>Response Code: ' + __(message) + '</div>');
                messageContainer.show();
            },

            /**
             * Clear all messages.
             */
            clearMessages: function (methodId) {
                var messageContainer = this.getMethodContainer(methodId).find('.message');
                messageContainer.hide();
                messageContainer.empty();
            },

            /**
             * Get a payment method container instance.
             */
            getMethodContainer: function (methodId) {
                return $('#' + methodId + '_container');
            },

            /**
             * Check if an URL is valid.
             */
            isUrl: function (str) {
                var pattern = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
                return pattern.test(str);
            },

            /**
             * Handle the place order button state.
             */
            allowPlaceOrder: function (buttonId, yesNo) {
                $('#' + buttonId).prop('disabled', !yesNo);
            },

            /**
             * Check if a payment option is active.
             */
            methodIsSelected: function (idSelector) {
                var id = idSelector.replace('#', '');
                var selected = CheckoutData.getSelectedPaymentMethod();
                return id == selected || selected == null;
            },

            /**
             * Place a new order.
             *
             * @return {void}
             */
            placeOrder: function (payload, methodId) {
                var self = this;

                // Start the loader
                FullScreenLoader.startLoader();

                // Send the request
                $.ajax({
                    type: 'POST',
                    url: self.getUrl('payment/placeorder'),
                    data: payload,
                    success: function (data) {
                        if (!data.success) {
                            FullScreenLoader.stopLoader();
                            self.showMessage('error', data.message, methodId);
                            if (data.debugMessage) {
                                self.showDebugMessage('error', data.debugMessage, methodId);
                            }
                            if (data.responseCode) {
                                self.showResponseCode('error', data.responseCode, methodId);
                            }
                            self.allowPlaceOrder(methodId + '_btn', false)
                        } else if (data.success && data.url) {
                            // Handle 3DS redirection
                            window.location.href = data.url;
                        } else {
                            // Normal redirection
                            RedirectOnSuccessAction.execute();
                        }
                    },
                    error: function (request, status, error) {
                        self.showMessage('error', error, methodId);
                        FullScreenLoader.stopLoader();
                    }
                });
            },

            /**
             * Clean Checkout data
             */
            cleanCustomerShippingAddress: function() {
                CheckoutData.setNewCustomerShippingAddress(null);
            }
        };
    }
);

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/view/payment/applepay-utilities', 
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Customer/js/model/customer',
        "CheckoutCom_Magento2/js/view/payment/utilities"
    ],
    function ($, Quote, Customer, Utilities) {
        'use strict';

        return {
            /**
             * Is Virtual.
             *
             * @return {object}  The is virtual status.
             */
            getIsVirtual: function () {
                return Utilities.getRestQuoteData(null).is_virtual
            },

            /**
             * Make a call to the Magento API
             */
            getRestData: function(requestBody, m2ApiEndpoint) {
                let restUrl =
                    window.BASE_URL +
                    "rest/all/V1/guest-carts/" +
                    window.checkoutConfig.quoteData.entity_id +
                    "/" +
                    m2ApiEndpoint;
                "?form_key=" + window.checkoutConfig.formKey;

                if (Customer.isLoggedIn()) {
                    var store = window.checkoutConfig.storeCode ? window.checkoutConfig.storeCode : 'default';
                    restUrl =
                        window.BASE_URL +
                        "rest/" + store + "/V1/carts/mine/" +
                        m2ApiEndpoint +
                        "?form_key=" +
                        window.checkoutConfig.formKey;
                }

                let result = null;
                let postType = m2ApiEndpoint == 'totals' ? "GET" : "POST";

                $.ajax({
                    url: restUrl,
                    type: postType,
                    async: false,
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(requestBody),
                    success: function (data, status, xhr) {
                        result = data;
                    },
                    error: function (request, status, error) {
                        Utilities.log(error);
                    },
                });
                return result;

            },

            /**
             * Get the area code based on zip and country code.
             * Used for ApplePay payments
             */
            getAreaCode: function(zipCode, countryCode) {
                // Ensure we have exactly 5 characters to parse
                if (zipCode.length === 5 && countryCode.toLowerCase() === "us") {
                    // Ensure we don't parse strings starting with 0 as octal values
                    const thiszip = parseInt(zipCode, 10);

                    let st = null;
                    if (thiszip >= 35000 && thiszip <= 36999) {
                        st = "AL";
                    } else if (thiszip >= 99500 && thiszip <= 99999) {
                        st = "AK";
                    } else if (thiszip >= 85000 && thiszip <= 86999) {
                        st = "AZ";
                    } else if (thiszip >= 71600 && thiszip <= 72999) {
                        st = "AR";
                    } else if (thiszip >= 90000 && thiszip <= 96699) {
                        st = "CA";
                    } else if (thiszip >= 80000 && thiszip <= 81999) {
                        st = "CO";
                    } else if (thiszip >= 6000 && thiszip <= 6999) {
                        st = "CT";
                    } else if (thiszip >= 19700 && thiszip <= 19999) {
                        st = "DE";
                    } else if (thiszip >= 32000 && thiszip <= 34999) {
                        st = "FL";
                    } else if (thiszip >= 30000 && thiszip <= 31999) {
                        st = "GA";
                    } else if (thiszip >= 96700 && thiszip <= 96999) {
                        st = "HI";
                    } else if (thiszip >= 83200 && thiszip <= 83999) {
                        st = "ID";
                    } else if (thiszip >= 60000 && thiszip <= 62999) {
                        st = "IL";
                    } else if (thiszip >= 46000 && thiszip <= 47999) {
                        st = "IN";
                    } else if (thiszip >= 50000 && thiszip <= 52999) {
                        st = "IA";
                    } else if (thiszip >= 66000 && thiszip <= 67999) {
                        st = "KS";
                    } else if (thiszip >= 40000 && thiszip <= 42999) {
                        st = "KY";
                    } else if (thiszip >= 70000 && thiszip <= 71599) {
                        st = "LA";
                    } else if (thiszip >= 3900 && thiszip <= 4999) {
                        st = "ME";
                    } else if (thiszip >= 20600 && thiszip <= 21999) {
                        st = "MD";
                    } else if (thiszip >= 1000 && thiszip <= 2799) {
                        st = "MA";
                    } else if (thiszip >= 48000 && thiszip <= 49999) {
                        st = "MI";
                    } else if (thiszip >= 55000 && thiszip <= 56999) {
                        st = "MN";
                    } else if (thiszip >= 38600 && thiszip <= 39999) {
                        st = "MS";
                    } else if (thiszip >= 63000 && thiszip <= 65999) {
                        st = "MO";
                    } else if (thiszip >= 59000 && thiszip <= 59999) {
                        st = "MT";
                    } else if (thiszip >= 27000 && thiszip <= 28999) {
                        st = "NC";
                    } else if (thiszip >= 58000 && thiszip <= 58999) {
                        st = "ND";
                    } else if (thiszip >= 68000 && thiszip <= 69999) {
                        st = "NE";
                    } else if (thiszip >= 88900 && thiszip <= 89999) {
                        st = "NV";
                    } else if (thiszip >= 3000 && thiszip <= 3899) {
                        st = "NH";
                    } else if (thiszip >= 7000 && thiszip <= 8999) {
                        st = "NJ";
                    } else if (thiszip >= 87000 && thiszip <= 88499) {
                        st = "NM";
                    } else if (thiszip >= 10000 && thiszip <= 14999) {
                        st = "NY";
                    } else if (thiszip >= 43000 && thiszip <= 45999) {
                        st = "OH";
                    } else if (thiszip >= 73000 && thiszip <= 74999) {
                        st = "OK";
                    } else if (thiszip >= 97000 && thiszip <= 97999) {
                        st = "OR";
                    } else if (thiszip >= 15000 && thiszip <= 19699) {
                        st = "PA";
                    } else if (thiszip >= 300 && thiszip <= 999) {
                        st = "PR";
                    } else if (thiszip >= 2800 && thiszip <= 2999) {
                        st = "RI";
                    } else if (thiszip >= 29000 && thiszip <= 29999) {
                        st = "SC";
                    } else if (thiszip >= 57000 && thiszip <= 57999) {
                        st = "SD";
                    } else if (thiszip >= 37000 && thiszip <= 38599) {
                        st = "TN";
                    } else if (
                        (thiszip >= 75000 && thiszip <= 79999) ||
                        (thiszip >= 88500 && thiszip <= 88599)
                    ) {
                        st = "TX";
                    } else if (thiszip >= 84000 && thiszip <= 84999) {
                        st = "UT";
                    } else if (thiszip >= 5000 && thiszip <= 5999) {
                        st = "VT";
                    } else if (thiszip >= 22000 && thiszip <= 24699) {
                        st = "VA";
                    } else if (thiszip >= 20000 && thiszip <= 20599) {
                        st = "DC";
                    } else if (thiszip >= 98000 && thiszip <= 99499) {
                        st = "WA";
                    } else if (thiszip >= 24700 && thiszip <= 26999) {
                        st = "WV";
                    } else if (thiszip >= 53000 && thiszip <= 54999) {
                        st = "WI";
                    } else if (thiszip >= 82000 && thiszip <= 83199) {
                        st = "WY";
                    }

                    return st;
                } else {
                    return "";
                }
            }
        };
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/place-order', [
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/place-order'
], function (quote, urlBuilder, customer, placeOrderService) {
    'use strict';

    return function (paymentData, messageContainer) {
        var serviceUrl, payload;

        payload = {
            cartId: quote.getQuoteId(),
            billingAddress: quote.billingAddress(),
            paymentMethod: paymentData
        };

        if (customer.isLoggedIn()) {
            serviceUrl = urlBuilder.createUrl('/carts/mine/payment-information', {});
        } else {
            serviceUrl = urlBuilder.createUrl('/guest-carts/:quoteId/payment-information', {
                quoteId: quote.getQuoteId()
            });
            payload.email = quote.guestEmail;
        }

        return placeOrderService(serviceUrl, payload, messageContainer);
    };
});

define('Aheadworks_Giftcard/js/model/resource-url-manager', [
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/url-builder',
    'mageUtils'
], function(customer, urlBuilder, utils) {
    "use strict";
    return {
        /**
         * Retrieve url for apply Gift Card code
         *
         * @param {String} giftcardCode
         * @param {Number} quoteId
         * @returns {String}
         */
        getApplyGiftcardUrl: function(giftcardCode, quoteId) {
            var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quoteId} : {},
                urls = {
                    'guest': '/guest-carts/' + quoteId + '/aw-giftcard/' + giftcardCode,
                    'customer': '/carts/mine/aw-giftcard/' + giftcardCode
                };

            return this.getUrl(urls, params);
        },

        /**
         * Retrieve url for remove Gift Card code
         *
         * @param {String} giftcardCode
         * @param {Number} quoteId
         * @returns {String}
         */
        getRemoveGiftcardUrl: function(giftcardCode, quoteId) {
            var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quoteId} : {},
                urls = {
                    'guest': '/guest-carts/' + quoteId + '/aw-giftcard/' + giftcardCode,
                    'customer': '/carts/mine/aw-giftcard/' + giftcardCode
                };

            return this.getUrl(urls, params);
        },

        /**
         * Retrieve customer Gift Card codes
         *
         * @returns {String}
         */
        getCustomerGiftcardsUrl: function() {
            var params = {},
                urls = {
                    'customer': '/carts/mine/aw-giftcard-get-customer-codes/'
                };

            return this.getUrl(urls, params);
        },

        /**
         * Get url for service
         *
         * @returns {String}
         */
        getUrl: function(urls, urlParams) {
            var url;

            if (utils.isEmpty(urls)) {
                return 'Provided service call does not exist.';
            }

            if (!utils.isEmpty(urls['default'])) {
                url = urls['default'];
            } else {
                url = urls[this.getCheckoutMethod()];
            }
            return urlBuilder.createUrl(url, urlParams);
        },

        /**
         * Retrieve checkout method
         *
         * @returns {String}
         */
        getCheckoutMethod: function() {
            return customer.isLoggedIn() ? 'customer' : 'guest';
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/model/resource-url-manager', [
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/url-builder',
    'mageUtils'
], function (customer, urlBuilder, utils) {
        'use strict';

        return {
            /**
             * @param {Object} quote
             * @return {*}
             */
            getUrlForTotalsEstimationForNewAddress: function (quote) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            cartId: quote.getQuoteId()
                        } : {},
                    urls = {
                        'guest': '/guest-carts/:cartId/totals-information',
                        'customer': '/carts/mine/totals-information'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {Object} quote
             * @return {*}
             */
            getUrlForEstimationShippingMethodsForNewAddress: function (quote) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            quoteId: quote.getQuoteId()
                        } : {},
                    urls = {
                        'guest': '/guest-carts/:quoteId/estimate-shipping-methods',
                        'customer': '/carts/mine/estimate-shipping-methods'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {Object} quote
             * @return {*}
             */
            getUrlForEstimationShippingMethodsByAddressId: function (quote) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            quoteId: quote.getQuoteId()
                        } : {},
                    urls = {
                        'default': '/carts/mine/estimate-shipping-methods-by-address-id'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {String} couponCode
             * @param {String} quoteId
             * @return {*}
             */
            getApplyCouponUrl: function (couponCode, quoteId) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            quoteId: quoteId
                        } : {},
                    urls = {
                        'guest': '/guest-carts/' + quoteId + '/coupons/' + encodeURIComponent(couponCode),
                        'customer': '/carts/mine/coupons/' + encodeURIComponent(couponCode)
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {String} quoteId
             * @return {*}
             */
            getCancelCouponUrl: function (quoteId) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            quoteId: quoteId
                        } : {},
                    urls = {
                        'guest': '/guest-carts/' + quoteId + '/coupons/',
                        'customer': '/carts/mine/coupons/'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {Object} quote
             * @return {*}
             */
            getUrlForCartTotals: function (quote) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            quoteId: quote.getQuoteId()
                        } : {},
                    urls = {
                        'guest': '/guest-carts/:quoteId/totals',
                        'customer': '/carts/mine/totals'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * @param {Object} quote
             * @return {*}
             */
            getUrlForSetShippingInformation: function (quote) {
                var params = this.getCheckoutMethod() == 'guest' ? //eslint-disable-line eqeqeq
                        {
                            cartId: quote.getQuoteId()
                        } : {},
                    urls = {
                        'guest': '/guest-carts/:cartId/shipping-information',
                        'customer': '/carts/mine/shipping-information'
                    };

                return this.getUrl(urls, params);
            },

            /**
             * Get url for service.
             *
             * @param {*} urls
             * @param {*} urlParams
             * @return {String|*}
             */
            getUrl: function (urls, urlParams) {
                var url;

                if (utils.isEmpty(urls)) {
                    return 'Provided service call does not exist.';
                }

                if (!utils.isEmpty(urls['default'])) {
                    url = urls['default'];
                } else {
                    url = urls[this.getCheckoutMethod()];
                }

                return urlBuilder.createUrl(url, urlParams);
            },

            /**
             * @return {String}
             */
            getCheckoutMethod: function () {
                return customer.isLoggedIn() ? 'customer' : 'guest';
            }
        };
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/get-totals', [
    'jquery',
    '../model/quote',
    'Magento_Checkout/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'mage/storage',
    'Magento_Checkout/js/model/totals'
], function ($, quote, resourceUrlManager, errorProcessor, storage, totals) {
    'use strict';

    return function (callbacks, deferred) {
        deferred = deferred || $.Deferred();
        totals.isLoading(true);

        return storage.get(
            resourceUrlManager.getUrlForCartTotals(quote),
            false
        ).done(function (response) {
            var proceed = true;

            totals.isLoading(false);

            if (callbacks.length > 0) {
                $.each(callbacks, function (index, callback) {
                    proceed = proceed && callback();
                });
            }

            if (proceed) {
                quote.setTotals(response);
                deferred.resolve();
            }
        }).fail(function (response) {
            totals.isLoading(false);
            deferred.reject();
            errorProcessor.process(response);
        }).always(function () {
            totals.isLoading(false);
        });
    };
});

define('MediaLounge_PaymentMethodDiscount/js/action/select-payment-method', 
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/action/get-totals',
        'mage/url'
    ],
    function ($, quote, fullScreenLoader, getTotalsAction, url) {
        'use strict';
        return function (paymentMethod) {
            if (paymentMethod) {
                paymentMethod.__disableTmpl = {
                    title: true
                };
            }
            quote.paymentMethod(paymentMethod);

            fullScreenLoader.startLoader();

            $.ajax(url.build('ml_pmd/checkout/applyPaymentMethod'), {
                data: {payment_method: paymentMethod},
                complete: function () {
                    getTotalsAction([]);
                    fullScreenLoader.stopLoader();
                }
            });

        }
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment-service', [
    'underscore',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/payment/method-list',
    'Magento_Checkout/js/action/select-payment-method'
], function (_, quote, methodList, selectPaymentMethod) {
    'use strict';

    /**
    * Free method filter
    * @param {Object} paymentMethod
    * @return {Boolean}
    */
    var isFreePaymentMethod = function (paymentMethod) {
            return paymentMethod.method === 'free';
        },

        /**
         * Grabs the grand total from quote
         * @return {Number}
         */
        getGrandTotal = function () {
            return quote.totals()['grand_total'];
        };

    return {
        isFreeAvailable: false,

        /**
         * Populate the list of payment methods
         * @param {Array} methods
         */
        setPaymentMethods: function (methods) {
            var freeMethod,
                filteredMethods,
                methodIsAvailable,
                methodNames,
                isCurrentPaymenthMethodPresent;
            
            isCurrentPaymenthMethodPresent = false;

            freeMethod = _.find(methods, isFreePaymentMethod);
            this.isFreeAvailable = !!freeMethod;

            if (freeMethod && getGrandTotal() <= 0) {
                methods.splice(0, methods.length, freeMethod);
                selectPaymentMethod(freeMethod);
            }

            filteredMethods = _.without(methods, freeMethod);

            if (filteredMethods.length === 1) {
                selectPaymentMethod(filteredMethods[0]);
            } else if (quote.paymentMethod()) {
                methodIsAvailable = methods.some(function (item) {
                    return item.method === quote.paymentMethod().method;
                });
                //Unset selected payment method if not available
                if (!methodIsAvailable) {
                    selectPaymentMethod(null);
                } else {
                    isCurrentPaymenthMethodPresent = true;
                }
            }

            /**
             * Overwrite methods with existing methods to preserve ko array references.
             * This prevent ko from re-rendering those methods.
             */
            methodNames = _.pluck(methods, 'method');

            _.map(methodList(), function (existingMethod) {
                var existingMethodIndex = methodNames.indexOf(existingMethod.method);

                if (existingMethodIndex !== -1) {
                    methods[existingMethodIndex] = existingMethod;
                }
            });

            var defaultPaymentMethod = null;
            if (quote.paymentMethod() === null) {
                _.map(methods, function(method) {
                    if (method.method === 'checkoutcom_card_payment' && !defaultPaymentMethod) {
                        defaultPaymentMethod = method;
                    } else if (method.method === 'paypal_express' && !defaultPaymentMethod) {
                        defaultPaymentMethod = method;
                    }
                });
    
                if (!isCurrentPaymenthMethodPresent && defaultPaymentMethod) {
                    quote.paymentMethod(defaultPaymentMethod);
                }
            }

            methodList(methods);
        },

        /**
         * Get the list of available payment methods.
         * @return {Array}
         */
        getAvailablePaymentMethods: function () {
            var allMethods = methodList().slice(),
                grandTotalOverZero = getGrandTotal() > 0;

            if (!this.isFreeAvailable) {
                return allMethods;
            }

            if (grandTotalOverZero) {
                return _.reject(allMethods, isFreePaymentMethod);
            }

            return _.filter(allMethods, isFreePaymentMethod);
        }
    };
});

define('MediaLounge_CheckoutCom/js/model/checkout-data-resolver-mixin', [
    'underscore',
    'mage/utils/wrapper',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/action/select-payment-method',
    'jquery',
    'mage/cookies'
],function (_, wrapper, checkoutData, paymentService, selectPaymentMethodAction, $) {
    'use strict';

    return function (checkoutDataResolver) {
        var check = window.checkoutConfig.payment['checkoutcom_magento2'];
        var ckoConfig = window.checkoutConfig.payment['checkoutcom_magento2'].checkoutcom_configuration

        /**
         * Auto select the last used payment method. If this is unavailable select the default.
         */
        var resolvePaymentMethod = wrapper.wrap(
            
            checkoutDataResolver.resolvePaymentMethod,
            function (originalResolvePaymentMethod) {
                var availablePaymentMethods = paymentService.getAvailablePaymentMethods();
                var method = this.getMethod(checkoutData.getSelectedPaymentMethod(), availablePaymentMethods);

                if ((!checkoutData.getSelectedPaymentMethod() && _.size(availablePaymentMethods) > 1) || _.isUndefined(method)) {
                    var method = this.getMethod(ckoConfig.default_method, availablePaymentMethods);

                    const ppeMethodCode = "paypal_express";
                    const ppeMethod = this.getMethod(ppeMethodCode, availablePaymentMethods);

                    if (!_.isUndefined(ppeMethod)) {
                        method = ppeMethod;
                    }

                    if (!_.isUndefined(method)) {
                        selectPaymentMethodAction(method);
                    }
                }


                return originalResolvePaymentMethod();
            }
        )

        return _.extend(checkoutDataResolver, {
            resolvePaymentMethod: resolvePaymentMethod,

            /**
             * Get the payment method
             *
             * @param  {Array} availableMethods
             * @return {Object|undefined}
             */
            getMethod: function (method, availableMethods) {
                var autoselectMethod = method
                var matchedMethod;
                if (!_.isUndefined(autoselectMethod)) {
                    var matchedIndex = availableMethods.map(function(e) { return e.method; }).indexOf(autoselectMethod)
                    
                    if (matchedIndex !== -1) {
                        matchedMethod = availableMethods[matchedIndex]
                    }
                }

                return matchedMethod;
            }
        });
    };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_SalesRule/js/model/place-order-mixin', [
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Magento_SalesRule/js/model/coupon',
    'Magento_Checkout/js/action/get-totals'
], function ($, wrapper, quote, coupon, getTotalsAction) {
    'use strict';

    return function (placeOrderAction) {
        return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
            var result;

            $.when(
                result = originalAction(paymentData, messageContainer)
            ).fail(
                function () {
                    var deferred = $.Deferred(),

                        /**
                         * Update coupon form
                         */
                        updateCouponCallback = function () {
                            if (quote.totals() && !quote.totals()['coupon_code']) {
                                coupon.setCouponCode('');
                                coupon.setIsApplied(false);
                            }
                        };

                    getTotalsAction([], deferred);
                    $.when(deferred).done(updateCouponCallback);
                }
            );

            return result;
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/cart/totals-processor/default', [
    'underscore',
    'Magento_Checkout/js/model/resource-url-manager',
    'Magento_Checkout/js/model/quote',
    'mage/storage',
    'Magento_Checkout/js/model/totals',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Checkout/js/model/cart/cache',
    'Magento_Customer/js/customer-data'
], function (_, resourceUrlManager, quote, storage, totalsService, errorProcessor, cartCache, customerData) {
    'use strict';

    /**
     * Load data from server.
     *
     * @param {Object} address
     */
    var loadFromServer = function (address) {
        var serviceUrl,
            payload;

        // Start loader for totals block
        totalsService.isLoading(true);
        serviceUrl = resourceUrlManager.getUrlForTotalsEstimationForNewAddress(quote);
        payload = {
            addressInformation: {
                address: _.pick(address, cartCache.requiredFields)
            }
        };

        if (quote.shippingMethod() && quote.shippingMethod()['method_code']) {
            payload.addressInformation['shipping_method_code'] = quote.shippingMethod()['method_code'];
            payload.addressInformation['shipping_carrier_code'] = quote.shippingMethod()['carrier_code'];
        }

        return storage.post(
            serviceUrl, JSON.stringify(payload), false
        ).done(function (result) {
            var data = {
                totals: result,
                address: address,
                cartVersion: customerData.get('cart')()['data_id'],
                shippingMethodCode: null,
                shippingCarrierCode: null
            };

            if (quote.shippingMethod() && quote.shippingMethod()['method_code']) {
                data.shippingMethodCode = quote.shippingMethod()['method_code'];
                data.shippingCarrierCode = quote.shippingMethod()['carrier_code'];
            }

            quote.setTotals(result);
            cartCache.set('cart-data', data);
        }).fail(function (response) {
            errorProcessor.process(response);
        }).always(function () {
            // Stop loader for totals block
            totalsService.isLoading(false);
        });
    };

    return {
        /**
         * Array of required address fields.
         * @property {Array.String} requiredFields
         * @deprecated Use cart cache.
         */
        requiredFields: cartCache.requiredFields,

        /**
         * Get shipping rates for specified address.
         * @param {Object} address
         */
        estimateTotals: function (address) {
            var data = {
                shippingMethodCode: null,
                shippingCarrierCode: null
            };

            if (quote.shippingMethod() && quote.shippingMethod()['method_code']) {
                data.shippingMethodCode = quote.shippingMethod()['method_code'];
                data.shippingCarrierCode = quote.shippingMethod()['carrier_code'];
            }

            return loadFromServer(address);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/create-shipping-address', [
    'Magento_Customer/js/model/address-list',
    'Magento_Checkout/js/model/address-converter'
], function (addressList, addressConverter) {
    'use strict';

    return function (addressData) {
        var address = addressConverter.formAddressDataToQuoteAddress(addressData),
            isAddressUpdated = addressList().some(function (currentAddress, index, addresses) {
                if (currentAddress.getKey() == address.getKey()) { //eslint-disable-line eqeqeq
                    addresses[index] = address;

                    return true;
                }

                return false;
            });

        if (!isAddressUpdated) {
            addressList.push(address);
        } else {
            addressList.valueHasMutated();
        }

        return address;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Checkout adapter for customer data storage
 */
define('Magento_Checkout/js/model/checkout-data-resolver', [
    'Magento_Customer/js/model/address-list',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/action/create-shipping-address',
    'Magento_Checkout/js/action/select-shipping-address',
    'Magento_Checkout/js/action/select-shipping-method',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/action/select-payment-method',
    'Magento_Checkout/js/model/address-converter',
    'Magento_Checkout/js/action/select-billing-address',
    'Magento_Checkout/js/action/create-billing-address',
    'underscore'
], function (
    addressList,
    quote,
    checkoutData,
    createShippingAddress,
    selectShippingAddress,
    selectShippingMethodAction,
    paymentService,
    selectPaymentMethodAction,
    addressConverter,
    selectBillingAddress,
    createBillingAddress,
    _
) {
    'use strict';

    var isBillingAddressResolvedFromBackend = false;

    return {

        /**
         * Resolve estimation address. Used local storage
         */
        resolveEstimationAddress: function () {
            var address;

            if (quote.isVirtual()) {
                if (checkoutData.getBillingAddressFromData()) {
                    address = addressConverter.formAddressDataToQuoteAddress(
                        checkoutData.getBillingAddressFromData()
                    );
                    selectBillingAddress(address);
                } else {
                    this.resolveBillingAddress();
                }
            } else if (checkoutData.getShippingAddressFromData()) {
                address = addressConverter.formAddressDataToQuoteAddress(checkoutData.getShippingAddressFromData());
                selectShippingAddress(address);
            } else {
                this.resolveShippingAddress();
            }
        },

        /**
         * Resolve shipping address. Used local storage
         */
        resolveShippingAddress: function () {
            var newCustomerShippingAddress;

            if (!checkoutData.getShippingAddressFromData() &&
                window.checkoutConfig.shippingAddressFromData
            ) {
                checkoutData.setShippingAddressFromData(window.checkoutConfig.shippingAddressFromData);
            }

            newCustomerShippingAddress = checkoutData.getNewCustomerShippingAddress();

            if (newCustomerShippingAddress) {
                createShippingAddress(newCustomerShippingAddress);
            }
            this.applyShippingAddress();
        },

        /**
         * Apply resolved estimated address to quote
         *
         * @param {Object} isEstimatedAddress
         */
        applyShippingAddress: function (isEstimatedAddress) {
            var address,
                shippingAddress,
                isConvertAddress;

            if (addressList().length === 0) {
                address = addressConverter.formAddressDataToQuoteAddress(
                    checkoutData.getShippingAddressFromData()
                );
                selectShippingAddress(address);
            }
            shippingAddress = quote.shippingAddress();
            isConvertAddress = isEstimatedAddress || false;

            if (!shippingAddress) {
                shippingAddress = this.getShippingAddressFromCustomerAddressList();

                if (shippingAddress) {
                    selectShippingAddress(
                        isConvertAddress ?
                            addressConverter.addressToEstimationAddress(shippingAddress)
                            : shippingAddress
                    );
                }
            }
        },

        /**
         * @param {Object} ratesData
         */
        resolveShippingRates: function (ratesData) {
            var selectedShippingRate = checkoutData.getSelectedShippingRate(),
                availableRate = false;

            if (ratesData.length === 1 && !quote.shippingMethod()) {
                //set shipping rate if we have only one available shipping rate
                selectShippingMethodAction(ratesData[0]);

                return;
            }

            if (quote.shippingMethod()) {
                availableRate = _.find(ratesData, function (rate) {
                    return rate['carrier_code'] == quote.shippingMethod()['carrier_code'] && //eslint-disable-line
                        rate['method_code'] == quote.shippingMethod()['method_code']; //eslint-disable-line eqeqeq
                });
            }

            if (!availableRate && selectedShippingRate) {
                availableRate = _.find(ratesData, function (rate) {
                    return rate['carrier_code'] + '_' + rate['method_code'] === selectedShippingRate;
                });
            }

            if (!availableRate && window.checkoutConfig.selectedShippingMethod) {
                availableRate = _.find(ratesData, function (rate) {
                    var selectedShippingMethod = window.checkoutConfig.selectedShippingMethod;

                    return rate['carrier_code'] == selectedShippingMethod['carrier_code'] && //eslint-disable-line
                        rate['method_code'] == selectedShippingMethod['method_code']; //eslint-disable-line eqeqeq
                });
            }

            //Unset selected shipping method if not available
            if (!availableRate) {
                selectShippingMethodAction(null);
            } else {
                selectShippingMethodAction(availableRate);
            }
        },

        /**
         * Resolve payment method. Used local storage
         */
        resolvePaymentMethod: function () {
            var availablePaymentMethods = paymentService.getAvailablePaymentMethods(),
                selectedPaymentMethod = checkoutData.getSelectedPaymentMethod();

            if (selectedPaymentMethod) {
                availablePaymentMethods.some(function (payment) {
                    if (payment.method == selectedPaymentMethod) { //eslint-disable-line eqeqeq
                        selectPaymentMethodAction(payment);
                    }
                });
            }
        },

        /**
         * Resolve billing address. Used local storage
         */
        resolveBillingAddress: function () {
            var selectedBillingAddress,
                newCustomerBillingAddressData;

            selectedBillingAddress = checkoutData.getSelectedBillingAddress();
            newCustomerBillingAddressData = checkoutData.getNewCustomerBillingAddress();

            if (selectedBillingAddress) {
                if (selectedBillingAddress === 'new-customer-billing-address' && newCustomerBillingAddressData) {
                    selectBillingAddress(createBillingAddress(newCustomerBillingAddressData));
                } else {
                    addressList.some(function (address) {
                        if (selectedBillingAddress === address.getKey()) {
                            selectBillingAddress(address);
                        }
                    });
                }
            } else {
                this.applyBillingAddress();
            }

            if (!isBillingAddressResolvedFromBackend &&
                !checkoutData.getBillingAddressFromData() &&
                !_.isEmpty(window.checkoutConfig.billingAddressFromData) &&
                !quote.billingAddress()
            ) {
                if (window.checkoutConfig.isBillingAddressFromDataValid === true) {
                    selectBillingAddress(createBillingAddress(window.checkoutConfig.billingAddressFromData));
                } else {
                    checkoutData.setBillingAddressFromData(window.checkoutConfig.billingAddressFromData);
                }
                isBillingAddressResolvedFromBackend = true;
            }
        },

        /**
         * Apply resolved billing address to quote
         */
        applyBillingAddress: function () {
            var shippingAddress,
                isBillingAddressInitialized;

            if (quote.billingAddress()) {
                selectBillingAddress(quote.billingAddress());

                return;
            }

            if (quote.isVirtual() || !quote.billingAddress()) {
                isBillingAddressInitialized = addressList.some(function (addrs) {
                    if (addrs.isDefaultBilling()) {
                        selectBillingAddress(addrs);

                        return true;
                    }

                    return false;
                });
            }

            shippingAddress = quote.shippingAddress();

            if (!isBillingAddressInitialized &&
                shippingAddress &&
                shippingAddress.canUseForBilling() &&
                (shippingAddress.isDefaultShipping() || !quote.isVirtual())
            ) {
                //set billing address same as shipping by default if it is not empty
                selectBillingAddress(quote.shippingAddress());
            }
        },

        /**
         * Get shipping address from address list
         *
         * @return {Object|null}
         */
        getShippingAddressFromCustomerAddressList: function () {
            var shippingAddress = _.find(
                    addressList(),
                    function (address) {
                        return checkoutData.getSelectedShippingAddress() == address.getKey() //eslint-disable-line
                    }
                );

            if (!shippingAddress) {
                shippingAddress = _.find(
                    addressList(),
                    function (address) {
                        return address.isDefaultShipping();
                    }
                );
            }

            if (!shippingAddress && addressList().length === 1) {
                shippingAddress = addressList()[0];
            }

            return shippingAddress;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/payment/default', [
    'ko',
    'jquery',
    'uiComponent',
    'Magento_Checkout/js/action/place-order',
    'Magento_Checkout/js/action/select-payment-method',
    'Magento_Checkout/js/model/quote',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'uiRegistry',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Ui/js/model/messages',
    'uiLayout',
    'Magento_Checkout/js/action/redirect-on-success'
], function (
    ko,
    $,
    Component,
    placeOrderAction,
    selectPaymentMethodAction,
    quote,
    customer,
    paymentService,
    checkoutData,
    checkoutDataResolver,
    registry,
    additionalValidators,
    Messages,
    layout,
    redirectOnSuccessAction
) {
    'use strict';

    return Component.extend({
        redirectAfterPlaceOrder: true,
        isPlaceOrderActionAllowed: ko.observable(quote.billingAddress() != null),

        /**
         * After place order callback
         */
        afterPlaceOrder: function () {
            // Override this function and put after place order logic here
        },

        /**
         * Initialize view.
         *
         * @return {exports}
         */
        initialize: function () {
            var billingAddressCode,
                billingAddressData,
                defaultAddressData;

            this._super().initChildren();
            quote.billingAddress.subscribe(function (address) {
                this.isPlaceOrderActionAllowed(address !== null);
            }, this);
            checkoutDataResolver.resolveBillingAddress();

            billingAddressCode = 'billingAddress' + this.getCode();
            registry.async('checkoutProvider')(function (checkoutProvider) {
                defaultAddressData = checkoutProvider.get(billingAddressCode);

                if (defaultAddressData === undefined) {
                    // Skip if payment does not have a billing address form
                    return;
                }
                billingAddressData = checkoutData.getBillingAddressFromData();

                if (billingAddressData) {
                    checkoutProvider.set(
                        billingAddressCode,
                        $.extend(true, {}, defaultAddressData, billingAddressData)
                    );
                }
                checkoutProvider.on(billingAddressCode, function (providerBillingAddressData) {
                    checkoutData.setBillingAddressFromData(providerBillingAddressData);
                }, billingAddressCode);
            });

            return this;
        },

        /**
         * Initialize child elements
         *
         * @returns {Component} Chainable.
         */
        initChildren: function () {
            this.messageContainer = new Messages();
            this.createMessagesComponent();

            return this;
        },

        /**
         * Create child message renderer component
         *
         * @returns {Component} Chainable.
         */
        createMessagesComponent: function () {

            var messagesComponent = {
                parent: this.name,
                name: this.name + '.messages',
                displayArea: 'messages',
                component: 'Magento_Ui/js/view/messages',
                config: {
                    messageContainer: this.messageContainer
                }
            };

            layout([messagesComponent]);

            return this;
        },

        /**
         * Place order.
         */
        placeOrder: function (data, event) {
            var self = this;

            if (event) {
                event.preventDefault();
            }

            if (this.validate() &&
                additionalValidators.validate() &&
                this.isPlaceOrderActionAllowed() === true
            ) {
                this.isPlaceOrderActionAllowed(false);

                this.getPlaceOrderDeferredObject()
                    .done(
                        function () {
                            self.afterPlaceOrder();

                            if (self.redirectAfterPlaceOrder) {
                                redirectOnSuccessAction.execute();
                            }
                        }
                    ).always(
                        function () {
                            self.isPlaceOrderActionAllowed(true);
                        }
                    );

                return true;
            }

            return false;
        },

        /**
         * @return {*}
         */
        getPlaceOrderDeferredObject: function () {
            return $.when(
                placeOrderAction(this.getData(), this.messageContainer)
            );
        },

        /**
         * @return {Boolean}
         */
        selectPaymentMethod: function () {
            selectPaymentMethodAction(this.getData());
            checkoutData.setSelectedPaymentMethod(this.item.method);

            return true;
        },

        isChecked: ko.computed(function () {
            return quote.paymentMethod() ? quote.paymentMethod().method : null;
        }),

        isRadioButtonVisible: ko.computed(function () {
            return paymentService.getAvailablePaymentMethods().length !== 1;
        }),

        /**
         * Get payment method data
         */
        getData: function () {
            return {
                'method': this.item.method,
                'po_number': null,
                'additional_data': null
            };
        },

        /**
         * Get payment method type.
         */
        getTitle: function () {
            return this.item.title;
        },

        /**
         * Get payment method code.
         */
        getCode: function () {
            return this.item.method;
        },

        /**
         * @return {Boolean}
         */
        validate: function () {
            return true;
        },

        /**
         * @return {String}
         */
        getBillingAddressFormName: function () {
            return 'billing-address-form-' + this.item.method;
        },

        /**
         * Dispose billing address subscriptions
         */
        disposeSubscriptions: function () {
            // dispose all active subscriptions
            var billingAddressCode = 'billingAddress' + this.getCode();

            registry.async('checkoutProvider')(function (checkoutProvider) {
                checkoutProvider.off(billingAddressCode);
            });
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/shipping-service', [
    'ko',
    'Magento_Checkout/js/model/checkout-data-resolver'
], function (ko, checkoutDataResolver) {
    'use strict';

    var shippingRates = ko.observableArray([]);

    return {
        isLoading: ko.observable(false),

        /**
         * Set shipping rates
         *
         * @param {*} ratesData
         */
        setShippingRates: function (ratesData) {
            shippingRates(ratesData);
            shippingRates.valueHasMutated();
            checkoutDataResolver.resolveShippingRates(ratesData);
        },

        /**
         * Get shipping rates
         *
         * @returns {*}
         */
        getShippingRates: function () {
            return shippingRates;
        }
    };
});

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

 define('CheckoutCom_Magento2/js/view/payment/cart/checkoutcom_applepay_cart', [
    "jquery",
    "Magento_Checkout/js/view/payment/default",
    "CheckoutCom_Magento2/js/view/payment/utilities",
    "CheckoutCom_Magento2/js/view/payment/applepay-utilities",
    "Magento_Checkout/js/model/full-screen-loader",
    "Magento_Checkout/js/model/payment/additional-validators",
    "Magento_Checkout/js/action/redirect-on-success",
    "Magento_Checkout/js/model/shipping-service",
    "Magento_Customer/js/model/customer",
    "Magento_Customer/js/model/authentication-popup",
    'Magento_Checkout/js/model/quote',
    "mage/translate",
], function (
    $,
    Component,
    Utilities,
    ApplePayUtilities,
    FullScreenLoader,
    AdditionalValidators,
    RedirectOnSuccessAction,
    shippingService,
    Customer,
    AuthPopup,
    Quote,
    $t
) {
    return function(config, button)
    {
        let checkoutConfig = window.checkoutConfig.payment["checkoutcom_magento2"];
        const methodId = "checkoutcom_apple_pay";
        let selectedShippingMethod = null;
        let shippingMethodsAvailable = null;
        let shippingAddress = null;
        let totalsBreakdown = null;
        const $applePayButton = $(button);

        //  Check Apple Pay is enabled for the merchant
        if (typeof checkoutConfig["checkoutcom_apple_pay"] !== 'undefined') {
            // If Apple Pay is enabled on the cart inject the button
            if (checkoutConfig["checkoutcom_apple_pay"][config.configName] == 1) {
                Utilities.log(`Apple Pay in ${config.type} is enabled`);

                // set the button theme and mode
                button.style["-apple-pay-button-style"] = getButtonTheme();

                launchApplePay();
            }
        }

        /**
         * Initialize Apple Pay and handle session events
         *
         * @return {undefined}
         */
        function launchApplePay()
        {
            // Check if Apple Pay is available in the browser
            if (window.ApplePaySession) {
                var merchantIdentifier = getValue("merchant_id");
                var canMakePayments = window.ApplePaySession.canMakePayments(
                    merchantIdentifier
                );
                // If Apple Pay is possible for the merchant id, display the button
                if (canMakePayments) {
                    Utilities.log("Apple Pay can be used for the merchant ID provided");
                    $applePayButton.css("display", "inline-block");
                }
            } else {
                Utilities.log("Apple Pay can not be used for the merchant ID provided");
                $applePayButton.css("display", "none");
            }

            // Handle the Apple Pay button being pressed
            $applePayButton.click(function (evt) {
                // Build the payment request
                if (ApplePayUtilities.getIsVirtual()) {
                    // Prepare the parameters
                    var runningTotal         = Utilities.getQuoteValue();

                    // Build the payment request
                    var paymentRequest = {
                        currencyCode: Utilities.getQuoteCurrency(),
                        countryCode: getCountryCode(),
                        total: {
                            label: window.location.host,
                            amount: runningTotal
                        },
                        supportedNetworks: getSupportedNetworks(),
                        merchantCapabilities: getMerchantCapabilities(),
                        requiredBillingContactFields: [
                            "postalAddress",
                            "name",
                            "phone",
                            "email"
                        ],
                        requiredShippingContactFields: [
                            "phone",
                            "email"
                        ],
                    };
                    if (!Customer.isLoggedIn()) {
                        paymentRequest.shippingMethods = [{
                            label: $t('Codes will be sent to email above'),
                            detail: '',
                            amount: '0',
                            identifier: 'info'
                        }];
                    }

                    // Start the payment session
                    Utilities.log(paymentRequest);
                    var session = new ApplePaySession(12, paymentRequest);
                } else {
                    var paymentRequest = {
                        currencyCode: Utilities.getQuoteCurrency(),
                        countryCode: getCountryCode(),
                        total: {
                            label: window.location.host,
                            amount: Utilities.getQuoteValue(),
                        },
                        supportedNetworks: getSupportedNetworks(),
                        merchantCapabilities: getMerchantCapabilities(),
                        requiredShippingContactFields: [
                            "postalAddress",
                            "name",
                            "phone",
                            "email",
                        ],
                        requiredBillingContactFields: [
                            "postalAddress",
                            "name",
                            "phone",
                            "email",
                        ],
                        shippingMethods: [],
                    };

                    // Start the payment session
                    Utilities.log(paymentRequest);
                    var session = new ApplePaySession(12, paymentRequest);
                }

                // Merchant Validation
                session.onvalidatemerchant = function (event) {
                    var promise = performValidation(event.validationURL);
                    promise
                        .then(function (merchantSession) {
                            Utilities.log("The Apple Pay session was generated");
                            session.completeMerchantValidation(merchantSession);
                        })
                        .catch(function (error) {
                            Utilities.log(error);
                        });
                };

                // When the shipping contact details are populated/selected
                session.onshippingcontactselected = function (event) {
                    shippingAddress = event.shippingContact;
                    // Get a list of available shipping methods for the shipping address of the customer
                    let shippingOptions = getShippingMethods(
                        shippingAddress.countryCode,
                        shippingAddress.postalCode
                    );

                    // Update the totals, so they reflect the all total items (shipping, tax...etc)
                    let totals = getCartTotals(shippingAddress);
                    totalsBreakdown = totals;

                    // Update the current totals breakdown
                    if (selectedShippingMethod) {
                        // Update the current totals breakdown
                        session.completeShippingContactSelection(
                            ApplePaySession.STATUS_SUCCESS,
                            shippingOptions,
                            totals.total,
                            totals.breakdown
                        );
                    } else {
                        session.completeShippingContactSelection({
                            status: "STATUS_FAILURE",
                            errors: [
                                new ApplePayError(
                                    "addressUnserviceable",
                                    "country",
                                    "No shipping methods available."
                                ),
                            ],
                            newTotal: totals.total,
                        });
                    }
                };

                // When the shipping method is populate/selected
                session.onshippingmethodselected = function (event) {
                    var status = ApplePaySession.STATUS_SUCCESS;

                    // Update the selected method
                    shippingMethodsAvailable.forEach(function (method) {
                        if (method.method_code == event.shippingMethod.identifier) {
                            selectedShippingMethod = method;
                        }
                    });
                    let totals = getCartTotals(shippingAddress);
                    totalsBreakdown = totals;

                    // Update the total to reflect the shipping method change
                    if (selectedShippingMethod) {
                        session.completeShippingMethodSelection(
                            status,
                            totals.total,
                            totals.breakdown
                        );
                    } else {
                        session.completeShippingMethodSelection(
                            ApplePaySession.STATUS_FAILURE
                        );
                    }
                };

                // When the payment method is populated/selected
                session.onpaymentmethodselected = function (event) {
                    // Update the totals, so they reflect the all total items (shipping, tax...etc)
                    let totals = getVirtualCartTotals();
                    totalsBreakdown = totals;

                    session.completePaymentMethodSelection(
                        totalsBreakdown.total,
                        totalsBreakdown.breakdown
                    );
                };

                // When the payment is authorized via biometrics
                session.onpaymentauthorized = function (event) {
                    // Prepare the payload
                    var payload = {
                        methodId: methodId,
                        cardToken: event.payment.token,
                        source: methodId,
                    };

                    if (ApplePayUtilities.getIsVirtual()) {
                        setBilling(
                            event.payment.shippingContact,
                            event.payment.billingContact
                        );
                    } else {
                        setShippingAndBilling(
                            event.payment.shippingContact,
                            event.payment.billingContact
                        );
                    }

                    // Send the request
                    var promise = sendPaymentRequest(payload);
                    promise
                        .then(function (data) {
                            var status;
                            if (data.success) {
                                status = ApplePaySession.STATUS_SUCCESS;
                            } else {
                                status = ApplePaySession.STATUS_FAILURE;
                            }

                            session.completePayment(status);

                            if (data.success && data.url) {
                                // Redirect to success page
                                FullScreenLoader.startLoader();
                                // Handle 3DS redirection
                                window.location.href = data.url;
                            } else {
                                // Set Success Redirect Path
                                RedirectOnSuccessAction.redirectUrl = 'checkout/onepage/success';
                                // Normal redirection
                                RedirectOnSuccessAction.execute();
                            }
                        })
                        .catch(function (error) {
                            Utilities.log(error);
                            status = ApplePaySession.STATUS_FAILURE;
                            session.completePayment(status);
                        });
                };

                // Session cancellation
                session.oncancel = function (event) {
                    Utilities.log(event);
                };

                // Begin session
                session.begin();
            });
        }

        /** Get the configured theme for the button
         * @return {string}
         */
        function getButtonTheme()
        {
            let theme = Utilities.getValue(methodId, "button_style");
            if (theme === "white-with-line") {
                return "white-outline"
            };
            return theme;
        }

        /**
         * Submit a payment for authorization
         *
         * @return {object}
         */
        function sendPaymentRequest(paymentData)
        {
            Utilities.log(paymentData);
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: Utilities.getUrl("payment/placeorder"),
                    type: "POST",
                    data: paymentData,
                    success: function (data, textStatus, xhr) {
                        if (data.success === true) {
                            resolve(data);
                        } else {
                            button.dispatchEvent(
                                new CustomEvent("ApplePayFail", {detail: { message: data.message }})
                            );
                            reject();
                        }
                    },
                    error: function (xhr, textStatus, error) {
                        Utilities.log(error);
                        reject();
                    },
                });
            });
        }

        /**
         * Call the back end controller with the validation URL to generate an Apple Session
         *
         * @return {object}
         */
        function performValidation(valURL)
        {
            var controllerUrl = Utilities.getUrl("applepay/validation");
            var validationUrl =
                controllerUrl + "?u=" + valURL + "&method_id=" + methodId;

            return new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.onload = function () {
                    Utilities.log(this.responseText);
                    var data = JSON.parse(this.responseText);
                    resolve(data);
                };
                xhr.onerror = reject;
                xhr.open("GET", validationUrl);
                xhr.send();
            });
        }

        /**
         * Get the schemes enabled in the plugin settings
         *
         * @return {array}
         */
        function getSupportedNetworks()
        {
            let networksEnabled = getValue("supported_networks").split(",");
            return processSupportedNetworks(networksEnabled);
        }

        /**
         * Process supported network based on store country (SA)
         *
         * @return {array}
         */
        function processSupportedNetworks (networksEnabled) {
            if (networksEnabled.includes("mada") && !(Utilities.getStoreCountry === "SA")) {
                networksEnabled.splice(networksEnabled.indexOf("mada"), 1);
            }

            return networksEnabled;
        }

        /**
         * Get country code
         *
         * @return {string}
         */
        function getCountryCode()
        {
            return Utilities.getStoreCountry == "SA" ? "SA" : window.checkoutConfig.defaultCountryId;
        }

        /**
         * Get the value of a plugin setting based on the field name
         *
         * @return {string}
         */
        function getValue(field)
        {
            return Utilities.getValue(methodId, field);
        }

        /**
         * Get a list of available shipping methods based on the countryId and postCode
         *
         * @return {array}
         */
        function getShippingMethods(countryId, postCode)
        {
            let requestBody = {
                address: {
                    country_id: countryId.toUpperCase(),
                    postcode: postCode,
                },
            };

            shippingMethodsAvailable = ApplePayUtilities.getRestData(
                requestBody,
                "estimate-shipping-methods"
            );
            selectedShippingMethod = shippingMethodsAvailable[0];

            if (Quote.shippingMethod() && Quote.shippingMethod()['method_code']) {
                let index = 0;
                shippingMethodsAvailable.forEach(function (method, i) {
                    if (method.method_code == Quote.shippingMethod()['method_code']) {
                        selectedShippingMethod = method;
                        index = i;
                    }
                });
                if (index !== 0) {
                    shippingMethodsAvailable.splice(index, 1);
                    shippingMethodsAvailable.unshift(selectedShippingMethod);
                }
            }

            return formatShipping(shippingMethodsAvailable);
        }

        /**
         * Format the shipping methods from Magento format to Apple accepted format
         *
         * @return {array}
         */
        function formatShipping(shippingData)
        {
            let formatted = [];

            shippingData.forEach(function (shippingMethod) {
                if (shippingMethod.available) {
                    formatted.push({
                        label: shippingMethod.method_title,
                        amount: shippingMethod.price_incl_tax.toFixed(2),
                        identifier: shippingMethod.method_code,
                        detail: shippingMethod.carrier_title ? shippingMethod.carrier_title : '',
                    });
                }
            });
            return formatted;
        }

        /**
         * Return the cart totals (grand total, and breakdown)
         *
         * @return {object}
         */
        function getVirtualCartTotals() {
            let totalInfo = ApplePayUtilities.getRestData(null, "totals");
            let breakdown = [];

            totalInfo.total_segments.forEach(function (totalItem) {
                // ignore the grand total since it's handled separately
                if (totalItem.code === "grand_total") return;
                if (totalItem.value === null) return;
                // if there is not tax applied, remove it from the line items
                if (totalItem.code === "tax" && totalItem.value === 0) return;
                // remove cdkoin earn/spent from line items
                if (totalItem.code === "mp_reward_earn") return;
                if (totalItem.code === "mp_reward_spent") return;
                breakdown.push({
                    type: "final",
                    label: totalItem.title,
                    amount: totalItem.value,
                });
            });

            return {
                breakdown: breakdown,
                total: {
                    type: "final",
                    label: window.location.host,
                    amount: Utilities.getQuoteValue(),
                },
            };
        }

        /**
         * Return the cart totals (grand total, and breakdown)
         *
         * @return {object}
         */
        function getCartTotals(address) {
            let countryId = address.countryCode;
            let postCode = address.postalCode;

            let requestBody = {
                addressInformation: {
                    address: {
                        country_id: countryId.toUpperCase(),
                        postcode: postCode,
                        region_code: ApplePayUtilities.getAreaCode(postCode, countryId),
                        region_id: 0
                    },
                    shipping_carrier_code: selectedShippingMethod ? selectedShippingMethod.carrier_code : "",
                    shipping_method_code: selectedShippingMethod ? selectedShippingMethod.method_code : "",
                },
            };

            let shippingInfo = ApplePayUtilities.getRestData(requestBody, "totals-information");

            let breakdown = [];

            let totalAmount = null;
            shippingInfo.total_segments.forEach(function (totalItem) {
                // ignore the grand total since it's handled separately
                if (totalItem.code === "grand_total") {
                    totalAmount = totalItem.value.toFixed(2)
                    return
                };
                // if there is not tax applied, remove it from the line items
                if (totalItem.code === "tax" && totalItem.value === 0) {
                    return
                };
                // fix null value of gift wrapping
                if (totalItem.code === "giftwrapping" && totalItem.value === null) {
                    return
                };
                breakdown.push({
                    type: "final",
                    label: totalItem.title,
                    amount: totalItem.value.toFixed(2),
                });
            });

            return {
                breakdown: breakdown,
                total: {
                    type: "final",
                    label: window.location.host,
                    amount: totalAmount ? totalAmount : Utilities.getQuoteValue(),
                },
            };
        }
        /**
         * Update the cart to include updated shipping/billing methods
         *
         * @return {undefined}
         */
        function setShippingAndBilling(shippingDetails, billingDetails)
        {
            let requestBody = {
                addressInformation: {
                    shipping_address: {
                        country_id: shippingDetails.countryCode.toUpperCase(),
                        region_code: ApplePayUtilities.getAreaCode(shippingDetails.postalCode, shippingDetails.countryCode),
                        region_id: 0,
                        street: shippingDetails.addressLines,
                        postcode: shippingDetails.postalCode,
                        city: shippingDetails.locality,
                        firstname: shippingDetails.givenName,
                        lastname: shippingDetails.familyName,
                        email: shippingDetails.emailAddress,
                        telephone: shippingDetails.phoneNumber,
                    },
                    billing_address: {
                        country_id: billingDetails.countryCode.toUpperCase(),
                        region_code: ApplePayUtilities.getAreaCode(billingDetails.postalCode, billingDetails.countryCode),
                        region_id: 0,
                        street: billingDetails.addressLines,
                        postcode: billingDetails.postalCode,
                        city: billingDetails.locality,
                        firstname: billingDetails.givenName,
                        lastname: billingDetails.familyName,
                        email: shippingDetails.emailAddress,
                        telephone: shippingDetails.phoneNumber,
                    },
                    shipping_carrier_code: selectedShippingMethod.carrier_code,
                    shipping_method_code: selectedShippingMethod.method_code,
                },
            };
            ApplePayUtilities.getRestData(requestBody, "shipping-information");
        }

        function setBilling(shippingDetails, billingDetails) {
            let requestBody = {
                address: {
                    country_id: billingDetails.countryCode.toUpperCase(),
                    region_code: ApplePayUtilities.getAreaCode(billingDetails.postalCode, billingDetails.countryCode),
                    region_id: 0,
                    street: billingDetails.addressLines,
                    postcode: billingDetails.postalCode,
                    city: billingDetails.locality || '.',
                    firstname: billingDetails.givenName,
                    lastname: billingDetails.familyName || '.',
                    email: shippingDetails.emailAddress,
                    telephone: shippingDetails.phoneNumber
                }
            };

            ApplePayUtilities.getRestData(requestBody, "billing-address");
        }

        /**
         * @return {array}
         */
        function getMerchantCapabilities()
        {
            var output = ["supports3DS"];
            var capabilities = getValue("merchant_capabilities").split(",");

            return output.concat(capabilities);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/view/cart/totals', [
    'jquery',
    'uiComponent',
    'Magento_Checkout/js/model/totals',
    'Magento_Checkout/js/model/shipping-service'
], function ($, Component, totalsService, shippingService) {
    'use strict';

    return Component.extend({
        isLoading: totalsService.isLoading,

        /**
         * @override
         */
        initialize: function () {
            this._super();
            totalsService.totals.subscribe(function () {
                $(window).trigger('resize');
            });
            shippingService.getShippingRates().subscribe(function () {
                $(window).trigger('resize');
            });
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/cart/shipping-rates', [
    'ko',
    'underscore',
    'uiComponent',
    'Magento_Checkout/js/model/shipping-service',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/select-shipping-method',
    'Magento_Checkout/js/checkout-data'
], function (ko, _, Component, shippingService, priceUtils, quote, selectShippingMethodAction, checkoutData) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/cart/shipping-rates'
        },
        isVisible: ko.observable(!quote.isVirtual()),
        isLoading: shippingService.isLoading,
        shippingRates: shippingService.getShippingRates(),
        shippingRateGroups: ko.observableArray([]),
        selectedShippingMethod: ko.computed(function () {
            return quote.shippingMethod() ?
                quote.shippingMethod()['carrier_code'] + '_' + quote.shippingMethod()['method_code'] :
                null;
        }),

        /**
         * @override
         */
        initObservable: function () {
            var self = this;

            this._super();

            this.shippingRates.subscribe(function (rates) {
                self.shippingRateGroups([]);
                _.each(rates, function (rate) {
                    var carrierTitle = rate['carrier_title'];

                    if (self.shippingRateGroups.indexOf(carrierTitle) === -1) {
                        self.shippingRateGroups.push(carrierTitle);
                    }
                });
            });

            return this;
        },

        /**
         * Get shipping rates for specific group based on title.
         * @returns Array
         */
        getRatesForGroup: function (shippingRateGroupTitle) {
            return _.filter(this.shippingRates(), function (rate) {
                return shippingRateGroupTitle === rate['carrier_title'];
            });
        },

        /**
         * Format shipping price.
         * @returns {String}
         */
        getFormattedPrice: function (price) {
            return priceUtils.formatPriceLocale(price, quote.getPriceFormat());
        },

        /**
         * Set shipping method.
         * @param {String} methodData
         * @returns bool
         */
        selectShippingMethod: function (methodData) {
            selectShippingMethodAction(methodData);
            checkoutData.setSelectedShippingRate(methodData['carrier_code'] + '_' + methodData['method_code']);

            return true;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment/method-converter', [
    'underscore'
], function (_) {
    'use strict';

    return function (methods) {
        _.each(methods, function (method) {
            if (method.hasOwnProperty('code')) {
                method.method = method.code;
                delete method.code;
            }
        });

        return methods;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/get-payment-information', [
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/payment/method-converter',
    'Magento_Checkout/js/model/payment-service'
], function ($, quote, urlBuilder, storage, errorProcessor, customer, methodConverter, paymentService) {
    'use strict';

    return function (deferred, messageContainer) {
        var serviceUrl;

        deferred = deferred || $.Deferred();

        /**
         * Checkout for guest and registered customer.
         */
        if (!customer.isLoggedIn()) {
            serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/payment-information', {
                cartId: quote.getQuoteId()
            });
        } else {
            serviceUrl = urlBuilder.createUrl('/carts/mine/payment-information', {});
        }

        return storage.get(
            serviceUrl, false
        ).done(function (response) {
            quote.setTotals(response.totals);
            paymentService.setPaymentMethods(methodConverter(response['payment_methods']));
            deferred.resolve();
        }).fail(function (response) {
            errorProcessor.process(response, messageContainer);
            deferred.reject();
        });
    };
});

define('Aheadworks_Giftcard/js/model/payment/giftcard-messages', [
    'Magento_Ui/js/model/messages'
], function (Messages) {
    'use strict';
    return new Messages();
});

define('Aheadworks_Giftcard/js/model/customer/giftcard', [
    'ko'
], function (ko) {
    'use strict';
    return {
        giftcardCodes: ko.observableArray([]),
        isLoading: ko.observable(false)
    };
});

define('Aheadworks_Giftcard/js/action/get-customer-giftcards', [
    'Aheadworks_Giftcard/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'Aheadworks_Giftcard/js/model/payment/giftcard-messages',
    'mage/storage',
    'Magento_Customer/js/model/customer',
    'Aheadworks_Giftcard/js/model/customer/giftcard'
], function (
    urlManager,
    errorProcessor,
    messageContainer,
    storage,
    customer,
    customerGiftcard
) {
    'use strict';
    return function () {
        if (customer.isLoggedIn()) {
            var url = urlManager.getCustomerGiftcardsUrl();

            customerGiftcard.isLoading(true);
            return storage.get(
                url,
                {},
                false
            ).done(
                function (response) {
                    if (response) {
                        customerGiftcard.giftcardCodes(response);
                    }
                }
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageContainer);
                }
            ).always(
                function() {
                    customerGiftcard.isLoading(false);
                }
            );
        }
    };
});

/* eslint-disable */
define('Aheadworks_Giftcard/js/action/remove-giftcard-code', [
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Aheadworks_Giftcard/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'Aheadworks_Giftcard/js/model/payment/total-messages',
    'mage/storage',
    'Magento_Checkout/js/model/totals',
    'mage/translate',
    'Magento_Checkout/js/action/get-payment-information',
    'Aheadworks_Giftcard/js/action/get-customer-giftcards',
    'Magento_Checkout/js/model/full-screen-loader'
], function(
    $,
    quote,
    urlManager,
    errorProcessor,
    messageList,
    storage,
    totals,
    $t,
    getPaymentInfoAction,
    getCustomerGiftcardsAction,
    fullScreenLoader
) {
    'use strict';
    return function(giftcardCode) {
        var quoteId = quote.getQuoteId(),
            url = urlManager.getRemoveGiftcardUrl(giftcardCode, quoteId),
            message = $t('Your Gift Card code was successfully removed');

        fullScreenLoader.startLoader();
        return storage
            .delete(url, false)
            .done(function(response) {
                if (response) {
                    var deferred = $.Deferred();

                    getCustomerGiftcardsAction();
                    totals.isLoading(true);
                    getPaymentInfoAction(deferred);
                    $.when(deferred).done(function() {
                        totals.isLoading(false);
                    });
                    messageList.addSuccessMessage({ message: message });
                }
            })
            .fail(function(response) {
                totals.isLoading(false);
                errorProcessor.process(response);
            })
            .always(function() {
                fullScreenLoader.stopLoader();
            });
    };
});

define('Aheadworks_Giftcard/js/view/checkout/summary/giftcard', [
    'jquery',
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/totals',
    'Aheadworks_Giftcard/js/action/remove-giftcard-code',
], function ($, Component, totals, removeAction) {
    'use strict';

    var giftcardRemoveUrl = window.checkoutConfig.awGiftcard.removeUrl;

    return Component.extend({
        defaults: {
            template: 'Aheadworks_Giftcard/checkout/summary/giftcard'
        },
        isAjaxRemoveLink: true,
        code: 'aw_giftcard',
        totals: totals.totals(),

        /**
         * Is display Gift Card totals
         *
         * @return {boolean}
         */
        isDisplayed: function() {
            return this.isFullMode() && this.totals
                && totals.getSegment(this.code) && totals.getSegment(this.code).value != 0;
        },

        /**
         * Retrieve applied Gift Card codes
         *
         * @returns {Array}
         */
        getGiftcardCodes: function () {
            if (this.totals && totals.getSegment(this.code)) {
                var giftcardCodes = totals.getSegment(this.code).extension_attributes.aw_giftcard_codes;
                giftcardCodes.forEach(function(giftcardCode, index) {
                    if (typeof giftcardCode == 'string') {
                        giftcardCodes[index] = JSON.parse(giftcardCode);
                    }
                });
                return giftcardCodes;
            }
            return [];
        },

        /**
         * Retrieve formatted value
         *
         * @param {Number} value
         * @returns {String}
         */
        getValue: function (value) {
            return this.getFormattedPrice(value);
        },

        /**
         * Remove Gift Card by code
         *
         * @param {String} code
         */
        removeByCode: function (code) {
            var form = 'form[data-role=aw-gc-remove-code-' + code + ']';

            if (this.isAjaxRemoveLink) {
                var giftcardCode = this._getGiftCardCodeFromForm(form);

                removeAction(giftcardCode)
            } else {
                $(form).attr('action', giftcardRemoveUrl);
                $(form).submit();
                return true;
            }
        },

        /**
         * Retrieve Gift Card code from form
         *
         * @param {String} form
         * @return {String|null}
         */
        _getGiftCardCodeFromForm: function(form) {
            var formDataArray = $(form).serializeArray(),
                giftcardCode = null;

            formDataArray.forEach(function (entry) {
                if (entry.name === 'code') {
                    giftcardCode = entry.value;
                }
            });

            return giftcardCode;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/lib/validation/utils', function () {
    'use strict';

    var utils = {
        /**
         * Check if string is empty with trim.
         *
         * @param {String} value
         * @return {Boolean}
         */
        isEmpty: function (value) {
            return value === '' || value == null || value.length === 0 || /^\s+$/.test(value);
        },

        /**
         * Check if string is empty no trim.
         *
         * @param {String} value
         * @return {Boolean}
         */
        isEmptyNoTrim: function (value) {
            return value === '' || value == null || value.length === 0;
        },

        /**
         * Checks if {value} is between numbers {from} and {to}.
         *
         * @param {String} value
         * @param {String} from
         * @param {String} to
         * @return {Boolean}
         */
        isBetween: function (value, from, to) {
            return (from === null || from === '' || value >= utils.parseNumber(from)) &&
                   (to === null || to === '' || value <= utils.parseNumber(to));
        },

        /**
         * Parse price string.
         *
         * @param {String} value
         * @return {Number}
         */
        parseNumber: function (value) {
            var isDot, isComa;

            if (typeof value !== 'string') {
                return parseFloat(value);
            }
            isDot = value.indexOf('.');
            isComa = value.indexOf(',');

            if (isDot !== -1 && isComa !== -1) {
                if (isComa > isDot) {
                    value = value.replace('.', '').replace(',', '.');
                } else {
                    value = value.replace(',', '');
                }
            } else if (isComa !== -1) {
                value = value.replace(',', '.');
            }

            return parseFloat(value);
        },

        /**
         * Removes HTML tags and space characters, numbers and punctuation.
         *
         * @param {String} value -  Value being stripped.
         * @return {String}
         */
        stripHtml: function (value) {
            return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ')
                .replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g, '');
        }
    };

    return utils;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/lib/validation/rules', [
    'jquery',
    'underscore',
    './utils',
    'moment',
    'tinycolor',
    'jquery/validate',
    'mage/translate'
], function ($, _, utils, moment, tinycolor) {
    'use strict';

    /**
     * validate credit card number using mod10
     * @param {String} s
     * @return {Boolean}
     */
    function validateCreditCard(s) {
        // remove non-numerics
        var v = '0123456789',
            w = '',
            i, j, k, m, c, a, x;

        for (i = 0; i < s.length; i++) {
            x = s.charAt(i);

            if (v.indexOf(x, 0) !== -1) {
                w += x;
            }
        }
        // validate number
        j = w.length / 2;
        k = Math.floor(j);
        m = Math.ceil(j) - k;
        c = 0;

        for (i = 0; i < k; i++) {
            a = w.charAt(i * 2 + m) * 2;
            c += a > 9 ? Math.floor(a / 10 + a % 10) : a;
        }

        for (i = 0; i < k + m; i++) {
            c += w.charAt(i * 2 + 1 - m) * 1;
        }

        return c % 10 === 0;
    }

    /**
     * Collection of validation rules including rules from additional-methods.js
     * @type {Object}
     */
    return _.mapObject({
        'min_text_length': [
            function (value, params) {
                return _.isUndefined(value) || value.length === 0 || value.length >= +params;
            },
            $.mage.__('Please enter more or equal than {0} symbols.')
        ],
        'max_text_length': [
            function (value, params) {
                return !_.isUndefined(value) && value.length <= +params;
            },
            $.mage.__('Please enter less or equal than {0} symbols.')
        ],
        'max-words': [
            function (value, params) {
                return utils.isEmpty(value) || utils.stripHtml(value).match(/\b\w+\b/g).length < params;
            },
            $.mage.__('Please enter {0} words or less.')
        ],
        'min-words': [
            function (value, params) {
                return utils.isEmpty(value) || utils.stripHtml(value).match(/\b\w+\b/g).length >= params;
            },
            $.mage.__('Please enter at least {0} words.')
        ],
        'range-words': [
            function (value, params) {
                var match = utils.stripHtml(value).match(/\b\w+\b/g) || [];

                return utils.isEmpty(value) || match.length >= params[0] &&
                    match.length <= params[1];
            },
            $.mage.__('Please enter between {0} and {1} words.')
        ],
        'letters-with-basic-punc': [
            function (value) {
                return utils.isEmpty(value) || /^[a-z\-.,()\u0027\u0022\s]+$/i.test(value);
            },
            $.mage.__('Letters or punctuation only please')
        ],
        'alphanumeric': [
            function (value) {
                return utils.isEmpty(value) || /^\w+$/i.test(value);
            },
            $.mage.__('Letters, numbers, spaces or underscores only please')
        ],
        'letters-only': [
            function (value) {
                return utils.isEmpty(value) || /^[a-z]+$/i.test(value);
            },
            $.mage.__('Letters only please')
        ],
        'no-whitespace': [
            function (value) {
                return utils.isEmpty(value) || /^\S+$/i.test(value);
            },
            $.mage.__('No white space please')
        ],
        'no-marginal-whitespace': [
            function (value) {
                return !/^\s+|\s+$/i.test(value);
            },
            $.mage.__('No marginal white space please')
        ],
        'zip-range': [
            function (value) {
                return utils.isEmpty(value) || /^90[2-5]-\d{2}-\d{4}$/.test(value);
            },
            $.mage.__('Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx')
        ],
        'integer': [
            function (value) {
                return utils.isEmpty(value) || /^-?\d+$/.test(value);
            },
            $.mage.__('A positive or negative non-decimal number please')
        ],
        'vinUS': [
            function (value) {
                if (utils.isEmpty(value)) {
                    return true;
                }

                if (value.length !== 17) {
                    return false;
                }
                var i, n, d, f, cd, cdv,//eslint-disable-line vars-on-top
                    LL = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],//eslint-disable-line max-len
                    VL = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9],
                    FL = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2],
                    rs = 0;

                for (i = 0; i < 17; i++) {
                    f = FL[i];
                    d = value.slice(i, i + 1);

                    if (i === 8) {
                        cdv = d;
                    }

                    if (!isNaN(d)) {
                        d *= f;
                    } else {
                        for (n = 0; n < LL.length; n++) {//eslint-disable-line max-depth
                            if (d.toUpperCase() === LL[n]) {//eslint-disable-line max-depth
                                d = VL[n];
                                d *= f;

                                if (isNaN(cdv) && n === 8) {//eslint-disable-line max-depth
                                    cdv = LL[n];
                                }
                                break;
                            }
                        }
                    }
                    rs += d;
                }
                cd = rs % 11;

                if (cd === 10) {
                    cd = 'X';
                }

                if (cd === cdv) {
                    return true;
                }

                return false;
            },
            $.mage.__('The specified vehicle identification number (VIN) is invalid.')
        ],
        'dateITA': [
            function (value) {
                var check = false,
                    re = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
                    adata, gg, mm, aaaa, xdata;

                if (re.test(value)) {
                    adata = value.split('/');
                    gg = parseInt(adata[0], 10);
                    mm = parseInt(adata[1], 10);
                    aaaa = parseInt(adata[2], 10);
                    xdata = new Date(aaaa, mm - 1, gg);

                    if (xdata.getFullYear() === aaaa &&
                        xdata.getMonth() === mm - 1 &&
                        xdata.getDate() === gg
                    ) {
                        check = true;
                    } else {
                        check = false;
                    }
                } else {
                    check = false;
                }

                return check;
            },
            $.mage.__('Please enter a correct date')
        ],
        'dateNL': [
            function (value) {
                return /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
            },
            $.mage.__('Vul hier een geldige datum in.')
        ],
        'time': [
            function (value) {
                return utils.isEmpty(value) || /^([01]\d|2[0-3])(:[0-5]\d){0,2}$/.test(value);
            },
            $.mage.__('Please enter a valid time, between 00:00 and 23:59')
        ],
        'time12h': [
            function (value) {
                return utils.isEmpty(value) || /^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\s[AP]M))$/i.test(value);
            },
            $.mage.__('Please enter a valid time, between 00:00 am and 12:00 pm')
        ],
        'phoneUS': [
            function (value) {
                value = value.replace(/\s+/g, '');

                return utils.isEmpty(value) || value.length > 9 &&
                    value.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
            },
            $.mage.__('Please specify a valid phone number')
        ],
        'phoneUK': [
            function (value) {
                return utils.isEmpty(value) || value.length > 9 &&
                    value.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
            },
            $.mage.__('Please specify a valid phone number')
        ],
        'mobileUK': [
            function (value) {
                return utils.isEmpty(value) || value.length > 9 && value.match(/^((0|\+44)7\d{3}\s?\d{6})$/);
            },
            $.mage.__('Please specify a valid mobile number')
        ],
        'stripped-min-length': [
            function (value, param) {
                return _.isUndefined(value) || value.length === 0 || utils.stripHtml(value).length >= param;
            },
            $.mage.__('Please enter at least {0} characters')
        ],
        'email2': [
            function (value) {
                return utils.isEmpty(value) || /^((([a-z]|\d|[!#\$%&\u0027\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&\u0027\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\u0022)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\u0022)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);//eslint-disable-line max-len
            },
            $.validator.messages.email
        ],
        'url2': [
            function (value) {
                return utils.isEmpty(value) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\u0027\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\u0027\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\u0027\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\u0027\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\u0027\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);//eslint-disable-line max-len
            },
            $.validator.messages.url
        ],
        'credit-card-types': [
            function (value, param) {
                var validTypes;

                if (utils.isEmpty(value)) {
                    return true;
                }

                if (/[^0-9-]+/.test(value)) {
                    return false;
                }
                value = value.replace(/\D/g, '');
                validTypes = 0x0000;

                if (param.mastercard) {
                    validTypes |= 0x0001;
                }

                if (param.visa) {
                    validTypes |= 0x0002;
                }

                if (param.amex) {
                    validTypes |= 0x0004;
                }

                if (param.dinersclub) {
                    validTypes |= 0x0008;
                }

                if (param.enroute) {
                    validTypes |= 0x0010;
                }

                if (param.discover) {
                    validTypes |= 0x0020;
                }

                if (param.jcb) {
                    validTypes |= 0x0040;
                }

                if (param.unknown) {
                    validTypes |= 0x0080;
                }

                if (param.all) {
                    validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
                }

                if (validTypes & 0x0001 && /^(51|52|53|54|55)/.test(value)) { //mastercard
                    return value.length === 16;
                }

                if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
                    return value.length === 16;
                }

                if (validTypes & 0x0004 && /^(34|37)/.test(value)) { //amex
                    return value.length === 15;
                }

                if (validTypes & 0x0008 && /^(300|301|302|303|304|305|36|38)/.test(value)) { //dinersclub
                    return value.length === 14;
                }

                if (validTypes & 0x0010 && /^(2014|2149)/.test(value)) { //enroute
                    return value.length === 15;
                }

                if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
                    return value.length === 16;
                }

                if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
                    return value.length === 16;
                }

                if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
                    return value.length === 15;
                }

                if (validTypes & 0x0080) { //unknown
                    return true;
                }

                return false;
            },
            $.mage.__('Please enter a valid credit card number.')
        ],
        'ipv4': [
            function (value) {
                return utils.isEmpty(value) || /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i.test(value);//eslint-disable-line max-len
            },
            $.mage.__('Please enter a valid IP v4 address.')
        ],
        'ipv6': [
            function (value) {
                return utils.isEmpty(value) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);//eslint-disable-line max-len
            },
            $.mage.__('Please enter a valid IP v6 address.')
        ],
        'pattern': [
            function (value, param) {
                return utils.isEmpty(value) || new RegExp(param).test(value);
            },
            $.mage.__('Invalid format.')
        ],
        'validate-no-html-tags': [
            function (value) {
                return !/<(\/)?\w+/.test(value);
            },
            $.mage.__('HTML tags are not allowed.')
        ],
        'validate-select': [
            function (value) {
                return value !== 'none' && value != null && value.length !== 0;
            },
            $.mage.__('Please select an option.')
        ],
        'validate-no-empty': [
            function (value) {
                return !utils.isEmpty(value);
            },
            $.mage.__('Empty Value.')
        ],
        'validate-alphanum-with-spaces': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[a-zA-Z0-9 ]+$/.test(value);
            },
            $.mage.__('Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.')
        ],
        'validate-data': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[A-Za-z]+[A-Za-z0-9_]+$/.test(value);
            },
            $.mage.__('Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.')//eslint-disable-line max-len
        ],
        'validate-street': [
            function (value) {
                return utils.isEmptyNoTrim(value) ||
                    /^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/.test(value);
            },
            $.mage.__('Please use only letters (a-z or A-Z), numbers (0-9), spaces and "#" in this field.')
        ],
        'validate-phoneStrict': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(value);
            },
            $.mage.__('Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.')
        ],
        'validate-phoneLax': [
            function (value) {
                return utils.isEmptyNoTrim(value) ||
                    /^((\d[\-. ]?)?((\(\d{3}\))|\d{3}))?[\-. ]?\d{3}[\-. ]?\d{4}$/.test(value);
            },
            $.mage.__('Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.')
        ],
        'validate-fax': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(value);
            },
            $.mage.__('Please enter a valid fax number (Ex: 123-456-7890).')
        ],
        'validate-email': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*@([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*\.(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,})$/i.test(value);//eslint-disable-line max-len
            },
            $.mage.__('Please enter a valid email address (Ex: johndoe@domain.com).')
        ],
        'validate-emailSender': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[\S ]+$/.test(value);
            },
            $.mage.__('Please enter a valid email address (Ex: johndoe@domain.com).')
        ],
        'validate-password': [
            function (value) {
                var pass;

                if (value == null) {
                    return false;
                }

                pass = value.trim();

                if (!pass.length) {
                    return true;
                }

                return !(pass.length > 0 && pass.length < 6);
            },
            $.mage.__('Please enter 6 or more characters. Leading and trailing spaces will be ignored.')
        ],
        'validate-admin-password': [
            function (value) {
                var pass;

                if (value == null) {
                    return false;
                }

                pass = value.trim();

                if (pass.length === 0) {
                    return true;
                }

                if (!/[a-z]/i.test(value) || !/[0-9]/.test(value)) {
                    return false;
                }

                if (pass.length < 7) {
                    return false;
                }

                return true;
            },
            $.mage.__('Please enter 7 or more characters, using both numeric and alphabetic.')
        ],
        'validate-customer-password': [
            function (v, elm) {
                var validator = this,
                    counter = 0,
                    passwordMinLength = $(elm).data('password-min-length'),
                    passwordMinCharacterSets = $(elm).data('password-min-character-sets'),
                    pass = v.trim(),
                    result = pass.length >= passwordMinLength;

                if (result === false) {
                    validator.passwordErrorMessage = $.mage.__('Minimum length of this field must be equal or greater than %1 symbols. Leading and trailing spaces will be ignored.').replace('%1', passwordMinLength);//eslint-disable-line max-len

                    return result;
                }

                if (pass.match(/\d+/)) {
                    counter++;
                }

                if (pass.match(/[a-z]+/)) {
                    counter++;
                }

                if (pass.match(/[A-Z]+/)) {
                    counter++;
                }

                if (pass.match(/[^a-zA-Z0-9]+/)) {
                    counter++;
                }

                if (counter < passwordMinCharacterSets) {
                    result = false;
                    validator.passwordErrorMessage = $.mage.__('Minimum of different classes of characters in password is %1. Classes of characters: Lower Case, Upper Case, Digits, Special Characters.').replace('%1', passwordMinCharacterSets);//eslint-disable-line max-len
                }

                return result;
            }, function () {
                return this.passwordErrorMessage;
            }
        ],
        'validate-url': [
            function (value) {
                if (utils.isEmptyNoTrim(value)) {
                    return true;
                }
                value = (value || '').replace(/^\s+/, '').replace(/\s+$/, '');

                return (/^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?(.*)?$/i).test(value);//eslint-disable-line max-len

            },
            $.mage.__('Please enter a valid URL. Protocol is required (http://, https:// or ftp://).')
        ],
        'validate-clean-url': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(value) || /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(value);//eslint-disable-line max-len

            },
            $.mage.__('Please enter a valid URL. For example http://www.example.com or www.example.com.')
        ],
        'validate-xml-identifier': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[A-Z][A-Z0-9_\/-]*$/i.test(value);

            },
            $.mage.__('Please enter a valid XML-identifier (Ex: something_1, block5, id-4).')
        ],
        'validate-ssn': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^\d{3}-?\d{2}-?\d{4}$/.test(value);

            },
            $.mage.__('Please enter a valid social security number (Ex: 123-45-6789).')
        ],
        'validate-zip-us': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value);

            },
            $.mage.__('Please enter a valid zip code (Ex: 90602 or 90602-1234).')
        ],
        'validate-date-au': [
            function (value) {
                var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/,
                    d;

                if (utils.isEmptyNoTrim(value)) {
                    return true;
                }

                if (utils.isEmpty(value) || !regex.test(value)) {
                    return false;
                }
                d = new Date(value.replace(regex, '$2/$1/$3'));

                return parseInt(RegExp.$2, 10) === 1 + d.getMonth() &&
                    parseInt(RegExp.$1, 10) === d.getDate() &&
                    parseInt(RegExp.$3, 10) === d.getFullYear();

            },
            $.mage.__('Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.')
        ],
        'validate-currency-dollar': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(value);//eslint-disable-line max-len

            },
            $.mage.__('Please enter a valid $ amount. For example $100.00.')
        ],
        'validate-not-negative-number': [
            function (value) {
                return utils.isEmptyNoTrim(value) || !isNaN(utils.parseNumber(value))
                    && value >= 0 && (/^\s*-?\d+([,.]\d+)*\s*%?\s*$/).test(value);

            },
            $.mage.__('Please enter a number 0 or greater, without comma in this field.')
        ],
        // validate-not-negative-number should be replaced in all places with this one and then removed
        'validate-zero-or-greater': [
            function (value) {
                return utils.isEmptyNoTrim(value) || !isNaN(utils.parseNumber(value))
                    && value >= 0 && (/^\s*-?\d+([,.]\d+)*\s*%?\s*$/).test(value);
            },
            $.mage.__('Please enter a number 0 or greater, without comma in this field.')
        ],
        'validate-greater-than-zero': [
            function (value) {
                return utils.isEmptyNoTrim(value) || !isNaN(utils.parseNumber(value))
                    && value > 0 && (/^\s*-?\d+([,.]\d+)*\s*%?\s*$/).test(value);
            },
            $.mage.__('Please enter a number greater than 0, without comma in this field.')
        ],
        'validate-css-length': [
            function (value) {
                if (value !== '') {
                    return (/^[0-9]*\.*[0-9]+(px|pc|pt|ex|em|mm|cm|in|%)?$/).test(value);
                }

                return true;
            },
            $.mage.__('Please input a valid CSS-length (Ex: 100px, 77pt, 20em, .5ex or 50%).')
        ],
        'validate-number': [
            function (value) {
                return utils.isEmptyNoTrim(value) ||
                    !isNaN(utils.parseNumber(value)) &&
                    /^\s*-?\d*(?:[.,|'|\s]\d+)*(?:[.,|'|\s]\d{2})?-?\s*$/.test(value);
            },
            $.mage.__('Please enter a valid number in this field.')
        ],
        'validate-integer': [
            function (value) {
                return utils.isEmptyNoTrim(value) || !isNaN(utils.parseNumber(value)) && /^\s*-?\d*\s*$/.test(value);
            },
            $.mage.__('Please enter a valid integer in this field.')
        ],
        'validate-number-range': [
            function (value, param) {
                var numValue, dataAttrRange, result, range, m;

                if (utils.isEmptyNoTrim(value)) {
                    return true;
                }

                numValue = utils.parseNumber(value);

                if (isNaN(numValue)) {
                    return false;
                }

                dataAttrRange = /^(-?[\d.,]+)?-(-?[\d.,]+)?$/;
                result = true;
                range = param;

                if (range) {
                    m = dataAttrRange.exec(range);

                    if (m) {
                        result = result && utils.isBetween(numValue, m[1], m[2]);
                    }
                }

                return result;
            },
            $.mage.__('The value is not within the specified range.')
        ],
        'validate-positive-percent-decimal': [
            function (value) {
                var numValue;

                if (utils.isEmptyNoTrim(value) || !/^\s*-?\d*(\.\d*)?\s*$/.test(value)) {
                    return false;
                }

                numValue = utils.parseNumber(value);

                if (isNaN(numValue)) {
                    return false;
                }

                return utils.isBetween(numValue, 0.01, 100);
            },
            $.mage.__('Please enter a valid percentage discount value greater than 0.')
        ],
        'validate-digits': [
            function (value) {
                return utils.isEmptyNoTrim(value) || !/[^\d]/.test(value);
            },
            $.mage.__('Please enter a valid number in this field.')
        ],
        'validate-digits-range': [
            function (value, param) {
                var numValue, dataAttrRange, result, range, m;

                if (utils.isEmptyNoTrim(value)) {
                    return true;
                }

                numValue = utils.parseNumber(value);

                if (isNaN(numValue)) {
                    return false;
                }

                dataAttrRange = /^(-?\d+)?-(-?\d+)?$/;
                result = true;
                range = param;

                if (range) {
                    m = dataAttrRange.exec(range);

                    if (m) {
                        result = result && utils.isBetween(numValue, m[1], m[2]);
                    }
                }

                return result;
            },
            $.mage.__('The value is not within the specified range.')
        ],
        'validate-range': [
            function (value) {
                var minValue, maxValue, ranges;

                if (utils.isEmptyNoTrim(value)) {
                    return true;
                } else if ($.validator.methods['validate-digits'] && $.validator.methods['validate-digits'](value)) {
                    minValue = maxValue = utils.parseNumber(value);
                } else {
                    ranges = /^(-?\d+)?-(-?\d+)?$/.exec(value);

                    if (ranges) {
                        minValue = utils.parseNumber(ranges[1]);
                        maxValue = utils.parseNumber(ranges[2]);

                        if (minValue > maxValue) {//eslint-disable-line max-depth
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            },
            $.mage.__('The value is not within the specified range.')
        ],
        'validate-alpha': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[a-zA-Z]+$/.test(value);
            },
            $.mage.__('Please use letters only (a-z or A-Z) in this field.')
        ],
        'validate-code': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[a-z]+[a-z0-9_]+$/.test(value);
            },
            $.mage.__('Please use only lowercase letters (a-z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.')//eslint-disable-line max-len
        ],
        'validate-alphanum': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[a-zA-Z0-9]+$/.test(value);
            },
            $.mage.__('Please use only letters (a-z or A-Z) or numbers (0-9) in this field. No spaces or other characters are allowed.')//eslint-disable-line max-len
        ],
        'validate-not-number-first': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[^0-9-\.].*$/.test(value.trim());
            },
            $.mage.__('First character must be letter.')
        ],
        'validate-date': [
            function (value, params, additionalParams) {
                var test = moment(value, additionalParams.dateFormat);

                return utils.isEmptyNoTrim(value) || test.isValid();
            },
            $.mage.__('Please enter a valid date.')
        ],
        'validate-date-range': [
            function (value, params) {
                var fromDate = $('input[name*="' + params + '"]').val();

                return moment.utc(value).unix() >= moment.utc(fromDate).unix() || isNaN(moment.utc(value).unix());
            },
            $.mage.__('Make sure the To Date is later than or the same as the From Date.')
        ],
        'validate-identifier': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^[a-z0-9][a-z0-9_\/-]+(\.[a-z0-9_-]+)?$/.test(value);
            },
            $.mage.__('Please enter a valid URL Key (Ex: "example-page", "example-page.html" or "anotherlevel/example-page").')//eslint-disable-line max-len
        ],
        'validate-trailing-hyphen': [
            function (value) {
                return utils.isEmptyNoTrim(value) || /^(?!-)(?!.*-$).+$/.test(value);
            },
            $.mage.__('Trailing hyphens are not allowed.')
        ],
        'validate-zip-international': [

            /*function(v) {
            // @TODO: Cleanup
            return Validation.get('IsEmpty').test(v) || /(^[A-z0-9]{2,10}([\s]{0,1}|[\-]{0,1})[A-z0-9]{2,10}$)/.test(v);
            }*/
            function () {
                return true;
            },
            $.mage.__('Please enter a valid zip code.')
        ],
        'validate-state': [
            function (value) {
                return value !== 0;
            },
            $.mage.__('Please select State/Province.')
        ],
        'less-than-equals-to': [
            function (value, params) {
                value = utils.parseNumber(value);

                if (isNaN(parseFloat(params))) {
                    params = $(params).val();
                }

                params = utils.parseNumber(params);

                if (!isNaN(params) && !isNaN(value)) {
                    this.lteToVal = params;

                    return value <= params;
                }

                return true;
            },
            function () {
                return $.mage.__('Please enter a value less than or equal to %s.').replace('%s', this.lteToVal);
            }
        ],
        'greater-than-equals-to': [
            function (value, params) {
                value = utils.parseNumber(value);

                if (isNaN(parseFloat(params))) {
                    params = $(params).val();
                }

                params = utils.parseNumber(params);

                if (!isNaN(params) && !isNaN(value)) {
                    this.gteToVal = params;

                    return value >= params;
                }

                return true;
            },
            function () {
                return $.mage.__('Please enter a value greater than or equal to %s.').replace('%s', this.gteToVal);
            }
        ],
        'validate-emails': [
            function (value) {
                var validRegexp, emails, i;

                if (utils.isEmpty(value)) {
                    return true;
                }
                validRegexp = /^[a-z0-9\._-]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i;
                emails = value.split(/[\s\n\,]+/g);

                for (i = 0; i < emails.length; i++) {
                    if (!validRegexp.test(emails[i].strip())) {
                        return false;
                    }
                }

                return true;
            },
            $.mage.__('Please enter valid email addresses, separated by commas. For example, johndoe@domain.com, johnsmith@domain.com.')//eslint-disable-line max-len
        ],
        'validate-cc-number': [

            /**
             * Validate credit card number based on mod 10.
             *
             * @param {String} value - credit card number
             * @return {Boolean}
             */
            function (value) {
                if (value) {
                    return validateCreditCard(value);
                }

                return true;
            },
            $.mage.__('Please enter a valid credit card number.')
        ],
        'validate-cc-ukss': [

            /**
             * Validate Switch/Solo/Maestro issue number and start date is filled.
             *
             * @param {String} value - input field value
             * @return {*}
             */
            function (value) {
                return value;
            },
            $.mage.__('Please enter issue number or start date for switch/solo card type.')
        ],
        'required-entry': [
            function (value) {
                return !utils.isEmpty(value);
            },
            $.mage.__('This is a required field.')
        ],
        'checked': [
            function (value) {
                return value;
            },
            $.mage.__('This is a required field.')
        ],
        'not-negative-amount': [
            function (value) {
                if (value.length) {
                    return (/^\s*\d+([,.]\d+)*\s*%?\s*$/).test(value);
                }

                return true;
            },
            $.mage.__('Please enter positive number in this field.')
        ],
        'validate-per-page-value-list': [
            function (value) {
                var isValid = true,
                    values = value.split(','),
                    i;

                if (utils.isEmpty(value)) {
                    return isValid;
                }

                for (i = 0; i < values.length; i++) {
                    if (!/^[0-9]+$/.test(values[i])) {
                        isValid = false;
                    }
                }

                return isValid;
            },
            $.mage.__('Please enter a valid value, ex: 10,20,30')
        ],
        'validate-new-password': [
            function (value) {
                if ($.validator.methods['validate-password'] && !$.validator.methods['validate-password'](value)) {
                    return false;
                }

                if (utils.isEmpty(value) && value !== '') {
                    return false;
                }

                return true;
            },
            $.mage.__('Please enter 6 or more characters. Leading and trailing spaces will be ignored.')
        ],
        'validate-item-quantity': [
            function (value, params) {
                var validator = this,
                    result = false,
                    // obtain values for validation
                    qty = utils.parseNumber(value),
                    isMinAllowedValid = typeof params.minAllowed === 'undefined' ||
                        qty >= utils.parseNumber(params.minAllowed),
                    isMaxAllowedValid = typeof params.maxAllowed === 'undefined' ||
                        qty <= utils.parseNumber(params.maxAllowed),
                    isQtyIncrementsValid = typeof params.qtyIncrements === 'undefined' ||
                        qty % utils.parseNumber(params.qtyIncrements) === 0;

                result = qty > 0;

                if (result === false) {
                    validator.itemQtyErrorMessage = $.mage.__('Please enter a quantity greater than 0.');//eslint-disable-line max-len

                    return result;
                }

                result = isMinAllowedValid;

                if (result === false) {
                    validator.itemQtyErrorMessage = $.mage.__('The fewest you may purchase is %1.').replace('%1', params.minAllowed);//eslint-disable-line max-len

                    return result;
                }

                result = isMaxAllowedValid;

                if (result === false) {
                    validator.itemQtyErrorMessage = $.mage.__('The maximum you may purchase is %1.').replace('%1', params.maxAllowed);//eslint-disable-line max-len

                    return result;
                }

                result = isQtyIncrementsValid;

                if (result === false) {
                    validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len

                    return result;
                }

                return result;
            }, function () {
                return this.itemQtyErrorMessage;
            }
        ],
        'equalTo': [
            function (value, param) {
                return value === $(param).val();
            },
            $.validator.messages.equalTo
        ],
        'validate-file-type': [
            function (name, types) {
                var extension = name.split('.').pop().toLowerCase();

                if (types && typeof types === 'string') {
                    types = types.split(' ');
                }

                return !types || !types.length || ~types.indexOf(extension);
            },
            $.mage.__('We don\'t recognize or support this file extension type.')
        ],
        'validate-max-size': [
            function (size, maxSize) {
                return maxSize === false || size < maxSize;
            },
            $.mage.__('File you are trying to upload exceeds maximum file size limit.')
        ],
        'validate-if-tag-script-exist': [
            function (value) {
                return !value || (/<script\b[^>]*>([\s\S]*?)<\/script>$/ig).test(value);
            },
            $.mage.__('Please use tag SCRIPT with SRC attribute or with proper content to include JavaScript to the document.')//eslint-disable-line max-len
        ],
        'date_range_min': [
            function (value, minValue, params) {
                return moment.utc(value, params.dateFormat).unix() >= minValue;
            },
            $.mage.__('The date is not within the specified range.')
        ],
        'date_range_max': [
            function (value, maxValue, params) {
                return moment.utc(value, params.dateFormat).unix() <= maxValue;
            },
            $.mage.__('The date is not within the specified range.')
        ],
        'validate-color': [
            function (value) {
                if (value === '') {
                    return true;
                }

                return tinycolor(value).isValid();
            },
            $.mage.__('Wrong color format. Please specify color in HEX, RGBa, HSVa, HSLa or use color name.')
        ],
        'blacklist-url': [
            function (value, param) {
                return new RegExp(param).test(value);
            },
            $.mage.__('This link is not allowed.')
        ],
        'validate-dob': [
            function (value, param, params) {
                if (value === '') {
                    return true;
                }

                return moment.utc(value, params.dateFormat).isSameOrBefore(moment.utc());
            },
            $.mage.__('The Date of Birth should not be greater than today.')
        ],
        'validate-no-utf8mb4-characters': [
            function (value) {
                var validator = this,
                    message = $.mage.__('Please remove invalid characters: {0}.'),
                    matches = value.match(/(?:[\uD800-\uDBFF][\uDC00-\uDFFF])/g),
                    result = matches === null;

                if (!result) {
                    validator.charErrorMessage = message.replace('{0}', matches.join());
                }

                return result;
            }, function () {
                return this.charErrorMessage;
            }
        ]
    }, function (data) {
        return {
            handler: data[0],
            message: data[1]
        };
    });
});

/*
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/lib/validation/validator', [
    'underscore',
    './rules'
], function (_, rulesList) {
    'use strict';

    /**
     * Validates provided value be the specified rule.
     *
     * @param {String} id - Rule identifier.
     * @param {*} value - Value to be checked.
     * @param {*} [params]
     * @param {*} additionalParams - additional validation params set by method caller
     * @returns {Object}
     */
    function validate(id, value, params, additionalParams) {
        var rule,
            message,
            valid,
            result = {
                rule: id,
                passed: true,
                message: ''
            };

        if (_.isObject(params)) {
            message = params.message || '';
        }

        if (!rulesList[id]) {
            return result;
        }

        rule    = rulesList[id];
        message = message || rule.message;
        valid   = rule.handler(value, params, additionalParams);

        if (!valid) {
            params = Array.isArray(params) ?
                params :
                [params];

            if (typeof message === 'function') {
                message = message.call(rule);
            }

            message = params.reduce(function (msg, param, idx) {
                return msg.replace(new RegExp('\\{' + idx + '\\}', 'g'), param);
            }, message);

            result.passed = false;
            result.message = message;
        }

        return result;
    }

    /**
     * Validates provided value by a specified set of rules.
     *
     * @param {(String|Object)} rules - One or many validation rules.
     * @param {*} value - Value to be checked.
     * @param {*} additionalParams - additional validation params set by method caller
     * @returns {Object}
     */
    function validator(rules, value, additionalParams) {
        var result;

        if (typeof rules === 'object') {
            result = {
                passed: true
            };

            _.every(rules, function (ruleParams, id) {
                if (ruleParams.validate || ruleParams !== false || additionalParams) {
                    result = validate(id, value, ruleParams, additionalParams);

                    return result.passed;
                }

                return true;
            });

            return result;
        }

        return validate.apply(null, arguments);
    }

    /**
     * Adds new validation rule.
     *
     * @param {String} id - Rule identifier.
     * @param {Function} handler - Validation function.
     * @param {String} message - Error message.
     */
    validator.addRule = function (id, handler, message) {
        rulesList[id] = {
            handler: handler,
            message: message
        };
    };

    /**
     * Returns rule object found by provided identifier.
     *
     * @param {String} id - Rule identifier.
     * @returns {Object}
     */
    validator.getRule = function (id) {
        return rulesList[id];
    };

    return validator;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/element/abstract', [
    'underscore',
    'mageUtils',
    'uiLayout',
    'uiElement',
    'Magento_Ui/js/lib/validation/validator'
], function (_, utils, layout, Element, validator) {
    'use strict';

    return Element.extend({
        defaults: {
            visible: true,
            preview: '',
            focused: false,
            required: false,
            disabled: false,
            valueChangedByUser: false,
            elementTmpl: 'ui/form/element/input',
            tooltipTpl: 'ui/form/element/helper/tooltip',
            fallbackResetTpl: 'ui/form/element/helper/fallback-reset',
            'input_type': 'input',
            placeholder: false,
            description: '',
            labelVisible: true,
            label: '',
            error: '',
            warn: '',
            notice: '',
            customScope: '',
            default: '',
            isDifferedFromDefault: false,
            showFallbackReset: false,
            additionalClasses: {},
            isUseDefault: '',
            serviceDisabled: false,
            valueUpdate: false, // ko binding valueUpdate

            switcherConfig: {
                component: 'Magento_Ui/js/form/switcher',
                name: '${ $.name }_switcher',
                target: '${ $.name }',
                property: 'value'
            },
            listens: {
                visible: 'setPreview',
                value: 'setDifferedFromDefault',
                '${ $.provider }:data.reset': 'reset',
                '${ $.provider }:data.overload': 'overload',
                '${ $.provider }:${ $.customScope ? $.customScope + "." : ""}data.validate': 'validate',
                'isUseDefault': 'toggleUseDefault'
            },
            ignoreTmpls: {
                value: true
            },

            links: {
                value: '${ $.provider }:${ $.dataScope }'
            }
        },

        /**
         * Invokes initialize method of parent class,
         * contains initialization logic
         */
        initialize: function () {
            _.bindAll(this, 'reset');

            this._super()
                .setInitialValue()
                ._setClasses()
                .initSwitcher();

            return this;
        },

        /**
         * Checks if component has error.
         *
         * @returns {Object}
         */
        checkInvalid: function () {
            return this.error() && this.error().length ? this : null;
        },

        /**
         * Initializes observable properties of instance
         *
         * @returns {Abstract} Chainable.
         */
        initObservable: function () {
            var rules = this.validation = this.validation || {};

            this._super();

            this.observe('error disabled focused preview visible value warn notice isDifferedFromDefault')
                .observe('isUseDefault serviceDisabled')
                .observe({
                    'required': !!rules['required-entry']
                });

            return this;
        },

        /**
         * Initializes regular properties of instance.
         *
         * @returns {Abstract} Chainable.
         */
        initConfig: function () {
            var uid = utils.uniqueid(),
                name,
                valueUpdate,
                scope;

            this._super();

            scope = this.dataScope.split('.');
            name = scope.length > 1 ? scope.slice(1) : scope;

            valueUpdate = this.showFallbackReset ? 'afterkeydown' : this.valueUpdate;

            _.extend(this, {
                uid: uid,
                noticeId: 'notice-' + uid,
                errorId: 'error-' + uid,
                tooltipId: 'tooltip-' + uid,
                inputName: utils.serializeName(name.join('.')),
                valueUpdate: valueUpdate
            });

            return this;
        },

        /**
         * Initializes switcher element instance.
         *
         * @returns {Abstract} Chainable.
         */
        initSwitcher: function () {
            if (this.switcherConfig.enabled) {
                layout([this.switcherConfig]);
            }

            return this;
        },

        /**
         * Sets initial value of the element and subscribes to it's changes.
         *
         * @returns {Abstract} Chainable.
         */
        setInitialValue: function () {
            this.initialValue = this.getInitialValue();

            if (this.value.peek() !== this.initialValue) {
                this.value(this.initialValue);
            }

            this.on('value', this.onUpdate.bind(this));
            this.isUseDefault(this.disabled());

            return this;
        },

        /**
         * Extends 'additionalClasses' object.
         *
         * @returns {Abstract} Chainable.
         */
        _setClasses: function () {
            var additional = this.additionalClasses;

            if (_.isString(additional)) {
                this.additionalClasses = {};

                if (additional.trim().length) {
                    additional = additional.trim().split(' ');

                    additional.forEach(function (name) {
                        if (name.length) {
                            this.additionalClasses[name] = true;
                        }
                    }, this);
                }
            }

            _.extend(this.additionalClasses, {
                _required: this.required,
                _error: this.error,
                _warn: this.warn,
                _disabled: this.disabled
            });

            return this;
        },

        /**
         * Gets initial value of element
         *
         * @returns {*} Elements' value.
         */
        getInitialValue: function () {
            var values = [this.value(), this.default],
                value;

            values.some(function (v) {
                if (v !== null && v !== undefined) {
                    value = v;

                    return true;
                }

                return false;
            });

            return this.normalizeData(value);
        },

        /**
         * Sets 'value' as 'hidden' property's value, triggers 'toggle' event,
         * sets instance's hidden identifier in params storage based on
         * 'value'.
         *
         * @returns {Abstract} Chainable.
         */
        setVisible: function (isVisible) {
            this.visible(isVisible);

            return this;
        },

        /**
         * Show element.
         *
         * @returns {Abstract} Chainable.
         */
        show: function () {
            this.visible(true);

            return this;
        },

        /**
         * Hide element.
         *
         * @returns {Abstract} Chainable.
         */
        hide: function () {
            this.visible(false);

            return this;
        },

        /**
         * Disable element.
         *
         * @returns {Abstract} Chainable.
         */
        disable: function () {
            this.disabled(true);

            return this;
        },

        /**
         * Enable element.
         *
         * @returns {Abstract} Chainable.
         */
        enable: function () {
            this.disabled(false);

            return this;
        },

        /**
         *
         * @param {(String|Object)} rule
         * @param {(Object|Boolean)} [options]
         * @returns {Abstract} Chainable.
         */
        setValidation: function (rule, options) {
            var rules = utils.copy(this.validation),
                changed;

            if (_.isObject(rule)) {
                _.extend(this.validation, rule);
            } else {
                this.validation[rule] = options;
            }

            changed = !utils.compare(rules, this.validation).equal;

            if (changed) {
                this.required(!!rules['required-entry']);
                this.validate();
            }

            return this;
        },

        /**
         * Returns unwrapped preview observable.
         *
         * @returns {String} Value of the preview observable.
         */
        getPreview: function () {
            return this.value();
        },

        /**
         * Checks if element has addons
         *
         * @returns {Boolean}
         */
        hasAddons: function () {
            return this.addbefore || this.addafter;
        },

        /**
         * Checks if element has service setting
         *
         * @returns {Boolean}
         */
        hasService: function () {
            return this.service && this.service.template;
        },

        /**
         * Defines if value has changed.
         *
         * @returns {Boolean}
         */
        hasChanged: function () {
            var notEqual = this.value() !== this.initialValue;

            return !this.visible() ? false : notEqual;
        },

        /**
         * Checks if 'value' is not empty.
         *
         * @returns {Boolean}
         */
        hasData: function () {
            return !utils.isEmpty(this.value());
        },

        /**
         * Sets value observable to initialValue property.
         *
         * @returns {Abstract} Chainable.
         */
        reset: function () {
            this.value(this.initialValue);
            this.error(false);

            return this;
        },

        /**
         * Sets current state as initial.
         */
        overload: function () {
            this.setInitialValue();
            this.bubble('update', this.hasChanged());
        },

        /**
         * Clears 'value' property.
         *
         * @returns {Abstract} Chainable.
         */
        clear: function () {
            this.value('');

            return this;
        },

        /**
         * Converts values like 'null' or 'undefined' to an empty string.
         *
         * @param {*} value - Value to be processed.
         * @returns {*}
         */
        normalizeData: function (value) {
            return utils.isEmpty(value) ? '' : value;
        },

        /**
         * Validates itself by it's validation rules using validator object.
         * If validation of a rule did not pass, writes it's message to
         * 'error' observable property.
         *
         * @returns {Object} Validate information.
         */
        validate: function () {
            var value = this.value(),
                result = validator(this.validation, value, this.validationParams),
                message = !this.disabled() && this.visible() ? result.message : '',
                isValid = this.disabled() || !this.visible() || result.passed;

            this.error(message);
            this.error.valueHasMutated();
            this.bubble('error', message);

            //TODO: Implement proper result propagation for form
            if (this.source && !isValid) {
                this.source.set('params.invalid', true);
            }

            return {
                valid: isValid,
                target: this
            };
        },

        /**
         * Callback that fires when 'value' property is updated.
         */
        onUpdate: function () {
            this.bubble('update', this.hasChanged());

            this.validate();
        },

        /**
         * Restore value to default
         */
        restoreToDefault: function () {
            this.value(this.default);
            this.focused(true);
        },

        /**
         * Update whether value differs from default value
         */
        setDifferedFromDefault: function () {
            var value = typeof this.value() != 'undefined' && this.value() !== null ? this.value() : '',
                defaultValue = typeof this.default != 'undefined' && this.default !== null ? this.default : '';

            this.isDifferedFromDefault(value !== defaultValue);
        },

        /**
         * @param {Boolean} state
         */
        toggleUseDefault: function (state) {
            this.disabled(state);

            if (this.source && this.hasService()) {
                this.source.set('data.use_default.' + this.index, Number(state));
            }
        },

        /**
         *  Callback when value is changed by user
         */
        userChanges: function () {
            this.valueChangedByUser = true;
        },

        /**
         * Returns correct id for 'aria-describedby' accessibility attribute
         *
         * @returns {Boolean|String}
         */
        getDescriptionId: function () {
            var id = false;

            if (this.error()) {
                id = this.errorId;
            } else if (this.notice()) {
                id = this.noticeId;
            }

            return id;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/element/select', [
    'underscore',
    'mageUtils',
    'uiRegistry',
    './abstract',
    'uiLayout'
], function (_, utils, registry, Abstract, layout) {
    'use strict';

    var inputNode = {
        parent: '${ $.$data.parentName }',
        component: 'Magento_Ui/js/form/element/abstract',
        template: '${ $.$data.template }',
        provider: '${ $.$data.provider }',
        name: '${ $.$data.index }_input',
        dataScope: '${ $.$data.customEntry }',
        customScope: '${ $.$data.customScope }',
        sortOrder: {
            after: '${ $.$data.name }'
        },
        displayArea: 'body',
        label: '${ $.$data.label }'
    };

    /**
     * Parses incoming options, considers options with undefined value property
     *     as caption
     *
     * @param  {Array} nodes
     * @return {Object}
     */
    function parseOptions(nodes, captionValue) {
        var caption,
            value;

        nodes = _.map(nodes, function (node) {
            value = node.value;

            if (value === null || value === captionValue) {
                if (_.isUndefined(caption)) {
                    caption = node.label;
                }
            } else {
                return node;
            }
        });

        return {
            options: _.compact(nodes),
            caption: _.isString(caption) ? caption : false
        };
    }

    /**
     * Recursively loops over data to find non-undefined, non-array value
     *
     * @param  {Array} data
     * @return {*} - first non-undefined value in array
     */
    function findFirst(data) {
        var value;

        data.some(function (node) {
            value = node.value;

            if (Array.isArray(value)) {
                value = findFirst(value);
            }

            return !_.isUndefined(value);
        });

        return value;
    }

    /**
     * Recursively set to object item like value and item.value like key.
     *
     * @param {Array} data
     * @param {Object} result
     * @returns {Object}
     */
    function indexOptions(data, result) {
        var value;

        result = result || {};

        data.forEach(function (item) {
            value = item.value;

            if (Array.isArray(value)) {
                indexOptions(value, result);
            } else {
                result[value] = item;
            }
        });

        return result;
    }

    return Abstract.extend({
        defaults: {
            customName: '${ $.parentName }.${ $.index }_input',
            elementTmpl: 'ui/form/element/select',
            caption: '',
            options: []
        },

        /**
         * Extends instance with defaults, extends config with formatted values
         *     and options, and invokes initialize method of AbstractElement class.
         *     If instance's 'customEntry' property is set to true, calls 'initInput'
         */
        initialize: function () {
            this._super();

            if (this.customEntry) {
                registry.get(this.name, this.initInput.bind(this));
            }

            if (this.filterBy) {
                this.initFilter();
            }

            return this;
        },

        /**
         * Calls 'initObservable' of parent, initializes 'options' and 'initialOptions'
         *     properties, calls 'setOptions' passing options to it
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super();

            this.initialOptions = this.options;

            this.observe('options caption')
                .setOptions(this.options());

            return this;
        },

        /**
         * Set link for filter.
         *
         * @returns {Object} Chainable
         */
        initFilter: function () {
            var filter = this.filterBy;

            this.filter(this.default, filter.field);
            this.setLinks({
                filter: filter.target
            }, 'imports');

            return this;
        },

        /**
         * Creates input from template, renders it via renderer.
         *
         * @returns {Object} Chainable.
         */
        initInput: function () {
            layout([utils.template(inputNode, this)]);

            return this;
        },

        /**
         * Matches specified value with existing options
         * or, if value is not specified, returns value of the first option.
         *
         * @returns {*}
         */
        normalizeData: function () {
            var value = this._super(),
                option;

            if (value !== '') {
                option = this.getOption(value);

                return option && option.value;
            }

            if (!this.caption()) {
                return findFirst(this.options);
            }
        },

        /**
         * Filters 'initialOptions' property by 'field' and 'value' passed,
         * calls 'setOptions' passing the result to it
         *
         * @param {*} value
         * @param {String} field
         */
        filter: function (value, field) {
            var source = this.initialOptions,
                result;

            field = field || this.filterBy.field;

            result = _.filter(source, function (item) {
                return item[field] === value || item.value === '';
            });

            this.setOptions(result);
        },

        /**
         * Change visibility for input.
         *
         * @param {Boolean} isVisible
         */
        toggleInput: function (isVisible) {
            registry.get(this.customName, function (input) {
                input.setVisible(isVisible);
            });
        },

        /**
         * Sets 'data' to 'options' observable array, if instance has
         * 'customEntry' property set to true, calls 'setHidden' method
         *  passing !options.length as a parameter
         *
         * @param {Array} data
         * @returns {Object} Chainable
         */
        setOptions: function (data) {
            var captionValue = this.captionValue || '',
                result = parseOptions(data, captionValue),
                isVisible;

            this.indexedOptions = indexOptions(result.options);

            this.options(result.options);

            if (!this.caption()) {
                this.caption(result.caption);
            }

            if (this.customEntry) {
                isVisible = !!result.options.length;

                this.setVisible(isVisible);
                this.toggleInput(!isVisible);
            }

            return this;
        },

        /**
         * Processes preview for option by it's value, and sets the result
         * to 'preview' observable
         *
         * @returns {Object} Chainable.
         */
        getPreview: function () {
            var value = this.value(),
                option = this.indexedOptions[value],
                preview = option ? option.label : '';

            this.preview(preview);

            return preview;
        },

        /**
         * Get option from indexedOptions list.
         *
         * @param {Number} value
         * @returns {Object} Chainable
         */
        getOption: function (value) {
            return this.indexedOptions[value];
        },

        /**
         * Select first available option
         *
         * @returns {Object} Chainable.
         */
        clear: function () {
            var value = this.caption() ? '' : findFirst(this.options);

            this.value(value);

            return this;
        },

        /**
         * Initializes observable properties of instance
         *
         * @returns {Object} Chainable.
         */
        setInitialValue: function () {
            if (_.isUndefined(this.value()) && !this.default) {
                this.clear();
            }

            return this._super();
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/element/region', [
    'underscore',
    'uiRegistry',
    './select',
    'Magento_Checkout/js/model/default-post-code-resolver'
], function (_, registry, Select, defaultPostCodeResolver) {
    'use strict';

    return Select.extend({
        defaults: {
            skipValidation: false,
            imports: {
                countryOptions: '${ $.parentName }.country_id:indexedOptions',
                update: '${ $.parentName }.country_id:value'
            }
        },

        /**
         * {@inheritdoc}
         */
        initialize: function () {
            var option;

            this._super();

            option = _.find(this.countryOptions, function (row) {
                return row['is_default'] === true;
            });
            this.hideRegion(option);

            return this;
        },

        /**
         * Method called every time country selector's value gets changed.
         * Updates all validations and requirements for certain country.
         * @param {String} value - Selected country ID.
         */
        update: function (value) {
            var isRegionRequired,
                option;

            if (!value) {
                return;
            }

            option = _.isObject(this.countryOptions) && this.countryOptions[value];

            if (!option) {
                return;
            }

            this.hideRegion(option);

            defaultPostCodeResolver.setUseDefaultPostCode(!option['is_zipcode_optional']);

            isRegionRequired = !this.skipValidation && !!option['is_region_required'];

            if (!isRegionRequired) {
                this.error(false);
            }

            this.required(isRegionRequired);
            this.validation['required-entry'] = isRegionRequired;

            registry.get(this.customName, function (input) {
                input.required(isRegionRequired);
                input.validation['required-entry'] = isRegionRequired;
                input.validation['validate-not-number-first'] = !this.options().length;
            }.bind(this));
        },

        /**
         * Hide select and corresponding text input field if region must not be shown for selected country.
         *
         * @private
         * @param {Object}option
         */
        hideRegion: function (option) {
            if (!option || option['is_region_visible'] !== false) {
                return;
            }

            this.setVisible(false);

            if (this.customEntry) {
                this.toggleInput(false);
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/shipping-rate-registry', [], function () {
    'use strict';

    var cache = [];

    return {
        /**
         * @param {String} addressKey
         * @return {*}
         */
        get: function (addressKey) {
            if (cache[addressKey]) {
                return cache[addressKey];
            }

            return false;
        },

        /**
         * @param {String} addressKey
         * @param {*} data
         */
        set: function (addressKey, data) {
            cache[addressKey] = data;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/model/shipping-rate-processor/new-address', [
    'Magento_Checkout/js/model/resource-url-manager',
    'Magento_Checkout/js/model/quote',
    'mage/storage',
    'Magento_Checkout/js/model/shipping-service',
    'Magento_Checkout/js/model/shipping-rate-registry',
    'Magento_Checkout/js/model/error-processor'
], function (resourceUrlManager, quote, storage, shippingService, rateRegistry, errorProcessor) {
    'use strict';

    return {
        /**
         * Get shipping rates for specified address.
         * @param {Object} address
         */
        getRates: function (address) {
            var cache, serviceUrl, payload;

            shippingService.isLoading(true);
            cache = rateRegistry.get(address.getCacheKey());
            serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(quote);
            payload = JSON.stringify({
                    address: {
                        'street': address.street,
                        'city': address.city,
                        'region_id': address.regionId,
                        'region': address.region,
                        'country_id': address.countryId,
                        'postcode': address.postcode,
                        'email': address.email,
                        'customer_id': address.customerId,
                        'firstname': address.firstname,
                        'lastname': address.lastname,
                        'middlename': address.middlename,
                        'prefix': address.prefix,
                        'suffix': address.suffix,
                        'vat_id': address.vatId,
                        'company': address.company,
                        'telephone': address.telephone,
                        'fax': address.fax,
                        'custom_attributes': address.customAttributes,
                        'save_in_address_book': address.saveInAddressBook
                    }
                }
            );

            if (cache) {
                shippingService.setShippingRates(cache);
                shippingService.isLoading(false);
            } else {
                storage.post(
                    serviceUrl, payload, false
                ).done(function (result) {
                    rateRegistry.set(address.getCacheKey(), result);
                    shippingService.setShippingRates(result);
                }).fail(function (response) {
                    shippingService.setShippingRates([]);
                    errorProcessor.process(response);
                }).always(function () {
                    shippingService.isLoading(false);
                });
            }
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/cart/estimate-service', [
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/shipping-rate-processor/new-address',
    'Magento_Checkout/js/model/cart/totals-processor/default',
    'Magento_Checkout/js/model/shipping-service',
    'Magento_Checkout/js/model/cart/cache',
    'Magento_Customer/js/customer-data'
], function (quote, defaultProcessor, totalsDefaultProvider, shippingService, cartCache, customerData) {
    'use strict';

    var rateProcessors = {},
        totalsProcessors = {},

        /**
         * Estimate totals for shipping address and update shipping rates.
         */
        estimateTotalsAndUpdateRates = function () {
            var type = quote.shippingAddress().getType();

            if (
                quote.isVirtual() ||
                window.checkoutConfig.activeCarriers && window.checkoutConfig.activeCarriers.length === 0
            ) {
                // update totals block when estimated address was set
                totalsProcessors['default'] = totalsDefaultProvider;
                totalsProcessors[type] ?
                    totalsProcessors[type].estimateTotals(quote.shippingAddress()) :
                    totalsProcessors['default'].estimateTotals(quote.shippingAddress());
            } else {
                // check if user data not changed -> load rates from cache
                if (!cartCache.isChanged('address', quote.shippingAddress()) &&
                    !cartCache.isChanged('cartVersion', customerData.get('cart')()['data_id']) &&
                    cartCache.get('rates')
                ) {
                    shippingService.setShippingRates(cartCache.get('rates'));

                    return;
                }

                // update rates list when estimated address was set
                rateProcessors['default'] = defaultProcessor;
                rateProcessors[type] ?
                    rateProcessors[type].getRates(quote.shippingAddress()) :
                    rateProcessors['default'].getRates(quote.shippingAddress());

                // save rates to cache after load
                shippingService.getShippingRates().subscribe(function (rates) {
                    cartCache.set('rates', rates);
                });
            }
        },

        /**
         * Estimate totals for shipping address.
         */
        estimateTotalsShipping = function () {
            totalsDefaultProvider.estimateTotals(quote.shippingAddress());
        },

        /**
         * Estimate totals for billing address.
         */
        estimateTotalsBilling = function () {
            var type = quote.billingAddress().getType();

            if (quote.isVirtual()) {
                // update totals block when estimated address was set
                totalsProcessors['default'] = totalsDefaultProvider;
                totalsProcessors[type] ?
                    totalsProcessors[type].estimateTotals(quote.billingAddress()) :
                    totalsProcessors['default'].estimateTotals(quote.billingAddress());
            }
        };

    quote.shippingAddress.subscribe(estimateTotalsAndUpdateRates);
    quote.shippingMethod.subscribe(estimateTotalsShipping);
    quote.billingAddress.subscribe(estimateTotalsBilling);
});

define('text!Magento_GiftMessage/template/gift-message.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isActive() || hasActiveOptions() -->\n<div class="cart-gift-item">\n    <div class="gift-item-block block"\n         data-collapsible="true"\n         data-bind="css: {_active: formBlockVisibility() || resultBlockVisibility()}">\n        <div class="title" data-role="title" data-bind="click: $data.toggleFormBlockVisibility.bind($data)">\n            <span data-bind="i18n: \'Gift options\'"></span>\n        </div>\n        <div class="content" data-role="content" data-bind="visible: formBlockVisibility() || resultBlockVisibility()">\n            <!-- ko ifnot: resultBlockVisibility() -->\n            <div class="gift-options">\n                <!-- ko foreach: getRegion(\'additionalOptions\') -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                <!-- /ko -->\n                <!-- ko template: formTemplate --><!--/ko-->\n            </div>\n            <!-- /ko -->\n            <div class="gift-summary">\n                <!-- ko if: resultBlockVisibility() -->\n                    <!-- ko foreach: getRegion(\'additionalOptions\') -->\n                         <!--ko template: appliedTemplate --><!-- /ko -->\n                    <!-- /ko -->\n\n                    <!-- ko if: getObservable(\'message\') -->\n                        <div class="gift-message-summary">\n                            <span data-bind="i18n: \'Message:\'"></span>\n                            <!-- ko text: getObservable(\'message\') --><!-- /ko -->\n                        </div>\n                    <!-- /ko -->\n                    <div class="actions-toolbar">\n                        <div class="secondary">\n                            <button type="submit"\n                                    class="action action-edit"\n                                    data-bind="attr: {title: $t(\'Edit\')}, click: $data.editOptions.bind($data)">\n                                <span data-bind="i18n: \'Edit\'"></span>\n                            </button>\n                            <button class="action action-delete"\n                                    data-bind="attr: {title: $t(\'Delete\')}, click: $data.deleteOptions.bind($data)">\n                                <span data-bind="i18n: \'Delete\'"></span>\n                            </button>\n                        </div>\n                    </div>\n                <!-- /ko -->\n            </div>\n        </div>\n    </div>\n</div>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/cart/totals.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="table-wrapper" data-bind="blockLoader: isLoading">\n    <table class="data table totals">\n        <caption class="table-caption" data-bind="text: $t(\'Total\')"></caption>\n        <tbody>\n        <!-- ko foreach: elems() -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n        <!-- /ko -->\n        </tbody>\n    </table>\n</div>\n';
});
define('text!Magento_Checkout/template/cart/shipping-rates.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<form id="co-shipping-method-form" data-bind="blockLoader: isLoading, visible: isVisible()">\n    <p class="field note" data-bind="visible: (!isLoading() && shippingRates().length <= 0)">\n        <!-- ko text: $t(\'Sorry, no quotes are available for this order at this time\')--><!-- /ko -->\n    </p>\n    <fieldset class="fieldset rate" data-bind="visible: (shippingRates().length > 0)">\n        <dl class="items methods" data-bind="foreach: shippingRateGroups">\n            <dt class="item-title"><span data-bind="text: $data"></span></dt>\n            <dd class="item-options" data-bind="foreach: { data:$parent.getRatesForGroup($data), as: \'method\' }">\n                <div data-bind="css: {\'field choice item\': available, \'message error\': !available} ">\n                    <!-- ko ifnot: (available) -->\n                    <div data-bind="text: error_message"></div>\n                    <!-- /ko -->\n                    <!-- ko if: (available) -->\n                    <input type="radio"\n                           class="radio"\n                           data-bind="\n                                click: $parents[1].selectShippingMethod,\n                                checked: $parents[1].selectedShippingMethod,\n                                attr: {\n                                        value: carrier_code + \'_\' + method_code,\n                                        id: \'s_method_\' + carrier_code + \'_\' + method_code,\n                                        disabled: false\n                                        }\n                                "/>\n                    <label class="label" data-bind="attr: {for: \'s_method_\' + carrier_code + \'_\' + method_code}">\n                        <!-- ko text: $data.method_title --><!-- /ko -->\n                        <each args="element.getRegion(\'price\')" render=""></each>\n                    </label>\n                    <!-- /ko -->\n                </div>\n            </dd>\n        </dl>\n    </fieldset>\n</form>\n';
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/adapter/buttons', function () {
    'use strict';

    return {
        'reset': '#reset',
        'save': '#save',
        'saveAndContinue': '#save_and_continue'
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/adapter', [
    'jquery',
    'underscore',
    'Magento_Ui/js/form/adapter/buttons'
], function ($, _, buttons) {
    'use strict';

    var selectorPrefix = '',
        eventPrefix;

    /**
     * Initialize listener.
     *
     * @param {Function} callback
     * @param {String} action
     */
    function initListener(callback, action) {
        var selector    = selectorPrefix ? selectorPrefix + ' ' + buttons[action] : buttons[action],
            elem        = $(selector)[0];

        if (!elem) {
            return;
        }

        if (elem.onclick) {
            elem.onclick = null;
        }

        $(elem).on('click' + eventPrefix, callback);
    }

    /**
     * Destroy listener.
     *
     * @param {String} action
     */
    function destroyListener(action) {
        var selector    = selectorPrefix ? selectorPrefix + ' ' + buttons[action] : buttons[action],
            elem        = $(selector)[0];

        if (!elem) {
            return;
        }

        if (elem.onclick) {
            elem.onclick = null;
        }

        $(elem).off('click' + eventPrefix);
    }

    return {

        /**
         * Attaches events handlers.
         *
         * @param {Object} handlers
         * @param {String} selectorPref
         * @param {String} eventPref
         */
        on: function (handlers, selectorPref, eventPref) {
            selectorPrefix = selectorPrefix || selectorPref;
            eventPrefix = eventPref;
            _.each(handlers, initListener);
            selectorPrefix = '';
        },

        /**
         * Removes events handlers.
         *
         * @param {Object} handlers
         * @param {String} eventPref
         */
        off: function (handlers, eventPref) {
            eventPrefix = eventPref;
            _.each(handlers, destroyListener);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/form', [
    'underscore',
    'Magento_Ui/js/lib/spinner',
    'rjsResolver',
    './adapter',
    'uiCollection',
    'mageUtils',
    'jquery',
    'Magento_Ui/js/core/app',
    'mage/validation'
], function (_, loader, resolver, adapter, Collection, utils, $, app) {
    'use strict';

    /**
     * Format params
     *
     * @param {Object} params
     * @returns {Array}
     */
    function prepareParams(params) {
        var result = '?';

        _.each(params, function (value, key) {
            result += key + '=' + value + '&';
        });

        return result.slice(0, -1);
    }

    /**
     * Collect form data.
     *
     * @param {Array} items
     * @returns {Object}
     */
    function collectData(items) {
        var result = {},
            name;

        items = Array.prototype.slice.call(items);

        items.forEach(function (item) {
            switch (item.type) {
                case 'checkbox':
                    result[item.name] = +!!item.checked;
                    break;

                case 'radio':
                    if (item.checked) {
                        result[item.name] = item.value;
                    }
                    break;

                case 'select-multiple':
                    name = item.name.substring(0, item.name.length - 2); //remove [] from the name ending
                    result[name] = _.pluck(item.selectedOptions, 'value');
                    break;

                default:
                    result[item.name] = item.value;
            }
        });

        return result;
    }

    /**
     * Makes ajax request
     *
     * @param {Object} params
     * @param {Object} data
     * @param {String} url
     * @returns {*}
     */
    function makeRequest(params, data, url) {
        var save = $.Deferred();

        data = utils.serialize(data);
        data['form_key'] = window.FORM_KEY;

        if (!url) {
            save.resolve();
        }

        $('body').trigger('processStart');

        $.ajax({
            url: url + prepareParams(params),
            data: data,
            dataType: 'json',

            /**
             * Success callback.
             * @param {Object} resp
             * @returns {Boolean}
             */
            success: function (resp) {
                if (resp.ajaxExpired) {
                    window.location.href = resp.ajaxRedirect;
                }

                if (!resp.error) {
                    save.resolve(resp);

                    return true;
                }

                $('body').notification('clear');
                $.each(resp.messages, function (key, message) {
                    $('body').notification('add', {
                        error: resp.error,
                        message: message,

                        /**
                         * Inserts message on page
                         * @param {String} msg
                         */
                        insertMethod: function (msg) {
                            $('.page-main-actions').after(msg);
                        }
                    });
                });
            },

            /**
             * Complete callback.
             */
            complete: function () {
                $('body').trigger('processStop');
            }
        });

        return save.promise();
    }

    /**
     * Check if fields is valid.
     *
     * @param {Array}items
     * @returns {Boolean}
     */
    function isValidFields(items) {
        var result = true;

        _.each(items, function (item) {
            if (!$.validator.validateSingleElement(item)) {
                result = false;
            }
        });

        return result;
    }

    return Collection.extend({
        defaults: {
            additionalFields: [],
            additionalInvalid: false,
            selectorPrefix: '.page-content',
            messagesClass: 'messages',
            errorClass: '.admin__field._error',
            eventPrefix: '.${ $.index }',
            ajaxSave: false,
            ajaxSaveType: 'default',
            imports: {
                reloadUrl: '${ $.provider}:reloadUrl'
            },
            listens: {
                selectorPrefix: 'destroyAdapter initAdapter',
                '${ $.name }.${ $.reloadItem }': 'params.set reload'
            },
            exports: {
                selectorPrefix: '${ $.provider }:client.selectorPrefix',
                messagesClass: '${ $.provider }:client.messagesClass'
            }
        },

        /** @inheritdoc */
        initialize: function () {
            this._super()
                .initAdapter();

            resolver(this.hideLoader, this);

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            return this._super()
                .observe([
                    'responseData',
                    'responseStatus'
                ]);
        },

        /** @inheritdoc */
        initConfig: function () {
            this._super();

            this.selector = '[data-form-part=' + this.namespace + ']';

            return this;
        },

        /**
         * Initialize adapter handlers.
         *
         * @returns {Object}
         */
        initAdapter: function () {
            adapter.on({
                'reset': this.reset.bind(this),
                'save': this.save.bind(this, true, {}),
                'saveAndContinue': this.save.bind(this, false, {})
            }, this.selectorPrefix, this.eventPrefix);

            return this;
        },

        /**
         * Destroy adapter handlers.
         *
         * @returns {Object}
         */
        destroyAdapter: function () {
            adapter.off([
                'reset',
                'save',
                'saveAndContinue'
            ], this.eventPrefix);

            return this;
        },

        /**
         * Hide loader.
         *
         * @returns {Object}
         */
        hideLoader: function () {
            loader.get(this.name).hide();

            return this;
        },

        /**
         * Validate and save form.
         *
         * @param {String} redirect
         * @param {Object} data
         */
        save: function (redirect, data) {
            this.validate();

            if (!this.additionalInvalid && !this.source.get('params.invalid')) {
                this.setAdditionalData(data)
                    .submit(redirect);
            } else {
                this.focusInvalid();
            }
        },

        /**
         * Tries to set focus on first invalid form field.
         *
         * @returns {Object}
         */
        focusInvalid: function () {
            var invalidField = _.find(this.delegate('checkInvalid'));

            if (!_.isUndefined(invalidField) && _.isFunction(invalidField.focused)) {
                invalidField.focused(true);
            }

            return this;
        },

        /**
         * Set additional data to source before form submit and after validation.
         *
         * @param {Object} data
         * @returns {Object}
         */
        setAdditionalData: function (data) {
            _.each(data, function (value, name) {
                this.source.set('data.' + name, value);
            }, this);

            return this;
        },

        /**
         * Submits form
         *
         * @param {String} redirect
         */
        submit: function (redirect) {
            var additional = collectData(this.additionalFields),
                source = this.source;

            _.each(additional, function (value, name) {
                source.set('data.' + name, value);
            });

            source.save({
                redirect: redirect,
                ajaxSave: this.ajaxSave,
                ajaxSaveType: this.ajaxSaveType,
                response: {
                    data: this.responseData,
                    status: this.responseStatus
                },
                attributes: {
                    id: this.namespace
                }
            });
        },

        /**
         * Validates each element and returns true, if all elements are valid.
         */
        validate: function () {
            this.additionalFields = document.querySelectorAll(this.selector);
            this.source.set('params.invalid', false);
            this.source.trigger('data.validate');
            this.set('additionalInvalid', !isValidFields(this.additionalFields));
        },

        /**
         * Trigger reset form data.
         */
        reset: function () {
            this.source.trigger('data.reset');
            $('[data-bind*=datepicker]').val('');
        },

        /**
         * Trigger overload form data.
         */
        overload: function () {
            this.source.trigger('data.overload');
        },

        /**
         * Updates data from server.
         */
        reload: function () {
            makeRequest(this.params, this.data, this.reloadUrl).then(function (data) {
                app(data, true);
            });
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/view/cart/shipping-estimation', 
    [
        'jquery',
        'Magento_Ui/js/form/form',
        'Magento_Checkout/js/action/select-shipping-address',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/model/cart/estimate-service',
        'Magento_Checkout/js/checkout-data',
        'Magento_Checkout/js/model/shipping-rates-validator',
        'uiRegistry',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/checkout-data-resolver',
        'Magento_Checkout/js/model/shipping-service',
        'mage/validation'
    ],
    function (
        $,
        Component,
        selectShippingAddress,
        addressConverter,
        estimateService,
        checkoutData,
        shippingRatesValidator,
        registry,
        quote,
        checkoutDataResolver,
        shippingService
    ) {
        'use strict';

        return Component.extend({
            defaults: {
                template: 'Magento_Checkout/cart/shipping-estimation'
            },
            isVirtual: quote.isVirtual(),

            /**
             * @override
             */
            initialize: function () {
                this._super();

                // Prevent shipping methods showing none available whilst we resolve
                shippingService.isLoading(true);

                registry.async('checkoutProvider')(function (checkoutProvider) {
                    var address, estimatedAddress;

                    shippingService.isLoading(false);

                    checkoutDataResolver.resolveEstimationAddress();
                    address = quote.isVirtual() ? quote.billingAddress() : quote.shippingAddress();

                    if (!address && quote.isVirtual()) {
                        address = addressConverter.formAddressDataToQuoteAddress(
                            checkoutData.getSelectedBillingAddress()
                        );
                    }

                    if (address) {
                        estimatedAddress = address.isEditable() ?
                            addressConverter.quoteAddressToFormAddressData(address) :
                            {
                                // only the following fields must be used by estimation form data provider
                                'country_id': address.countryId,
                                region: address.region,
                                'region_id': address.regionId,
                                postcode: address.postcode
                            };
                        checkoutProvider.set(
                            'shippingAddress',
                            $.extend({}, checkoutProvider.get('shippingAddress'), estimatedAddress)
                        );
                    }

                    if (!quote.isVirtual()) {
                        checkoutProvider.on('shippingAddress', function (shippingAddressData) {
                            //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
                            if (quote.shippingAddress().countryId !== shippingAddressData.country_id ||
                                (shippingAddressData.postcode || shippingAddressData.region_id)
                            ) {
                                checkoutData.setShippingAddressFromData(shippingAddressData);
                            }
                            //jscs:enable requireCamelCaseOrUpperCaseIdentifiers
                        });
                    } else {
                        checkoutProvider.on('shippingAddress', function (shippingAddressData) {
                            checkoutData.setBillingAddressFromData(shippingAddressData);
                        });
                    }
                });

                return this;
            },

            /**
             * @override
             */
            initElement: function (element) {
                this._super();

                if (element.index === 'address-fieldsets') {
                    shippingRatesValidator.bindChangeHandlers(element.elems(), true, 500);
                    element.elems.subscribe(function (elems) {
                        shippingRatesValidator.doElementBinding(elems[elems.length - 1], true, 500);
                    });
                }

                return this;
            },

            /**
             * Returns shipping rates for address
             * @returns void
             */
            getEstimationInfo: function () {
                var addressData = null;

                this.source.set('params.invalid', false);
                this.source.trigger('shippingAddress.data.validate');

                if (!this.source.get('params.invalid')) {
                    addressData = this.source.get('shippingAddress');
                    selectShippingAddress(addressConverter.formAddressDataToQuoteAddress(addressData));
                }
            }
        });
    }
);

define('text!Mageplaza_RewardPoints/template/totals/label.html', function() {
    return '<!--\n/**\n* Mageplaza\n*\n* NOTICE OF LICENSE\n*\n* This source file is subject to the mageplaza.com license that is\n* available through the world-wide-web at this URL:\n* https://www.mageplaza.com/LICENSE.txt\n*\n* DISCLAIMER\n*\n* Do not edit or add to this file if you wish to upgrade this extension to newer\n* version in the future.\n*\n* @category    Mageplaza\n* @package     Mageplaza_RewardPoints\n* @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)\n* @license     https://www.mageplaza.com/LICENSE.txt\n*/\n-->\n\n<!-- ko if: getSpending() -->\n<tr class="totals sub">\n    <th class="mark" scope="row" data-bind="i18n: getSpending().title"></th>\n    <td class="amount">\n        <span class="price" data-bind="html: getSpendingValue(), style: {fontWeight: \'bold\'}"></span>\n    </td>\n</tr>\n<!-- /ko -->';
});
define('text!MediaLounge_AmountSaved/template/checkout/summary/saved.html', function() {
    return '<!--\n/**\n * Copyright \xA9 MediaLounge, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: getValue() -->\n<tr class="totals sub excl">\n    <th class="mark" scope="row">\n        <span data-bind="i18n: \'Total saved\'"></span>\n    </th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValue()"></span>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_Tax/template/checkout/summary/subtotal.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isBothPricesDisplayed() -->\n<tr class="totals sub excl">\n    <th class="mark" scope="row">\n        <span data-bind="i18n: title"></span>\n        <span data-bind="i18n: excludingTaxMessage"></span>\n    </th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValue(), attr: {\'data-th\': excludingTaxMessage}"></span>\n    </td>\n</tr>\n<tr class="totals sub incl">\n    <th class="mark" scope="row">\n        <span data-bind="i18n: title"></span>\n        <span data-bind="i18n: includingTaxMessage"></span>\n    </th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValueInclTax(), attr: {\'data-th\': includingTaxMessage}"></span>\n    </td>\n</tr>\n<!-- /ko -->\n<!-- ko if: !isBothPricesDisplayed() && isIncludingTaxDisplayed() -->\n<tr class="totals sub">\n    <th data-bind="i18n: title" class="mark" scope="row"></th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValueInclTax(), attr: {\'data-th\': title}"></span>\n    </td>\n</tr>\n<!-- /ko -->\n<!-- ko if: !isBothPricesDisplayed() && !isIncludingTaxDisplayed() -->\n<tr class="totals sub">\n    <th data-bind="i18n: title" class="mark" scope="row"></th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValue(), attr: {\'data-th\': title}"></span>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_SalesRule/template/cart/totals/discount.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isDisplayed() -->\n<tr class="totals">\n    <th colspan="1" style="" class="mark" scope="row">\n        <span class="title" data-bind="text: getTitle()"></span>\n        <span class="discount coupon" data-bind="text: getCouponLabel()"></span>\n    </th>\n    <td class="amount" data-bind="attr: {\'data-th\': title}">\n        <span><span class="price" data-bind="text: getValue()"></span></span>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Aheadworks_Giftcard/template/checkout/summary/giftcard.html', function() {
    return '<!-- ko if: isDisplayed() -->\n<tr class="totals aw-giftcard-totals" repeat="foreach: getGiftcardCodes(), item: \'$giftcard\'">\n    <th class="mark" scope="row">\n        <form data-bind="attr: {\'data-role\': \'aw-gc-remove-code-\' + $giftcard().giftcard_code}" method="post">\n            <input type="hidden" name="code" data-bind="value: $giftcard().giftcard_code">\n            <span class="title" data-bind="i18n: $giftcard().title"></span>\n            <a role="button"\n               class="action-delete"\n               data-bind="attr: {\'title\': $t(\'Remove\')},click: removeByCode.bind($data, $giftcard().giftcard_code)"\n               title="Remove">\n               <span data-bind="i18n: \'Remove\'"></span>\n            </a>\n        </form>\n    </th>\n\n    <td class="amount" data-bind="attr: {\'data-th\': $t($giftcard().title) }">\n        <span class="price" data-bind="text: getValue($giftcard().value)"></span>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_Tax/template/checkout/cart/totals/grand-total.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isTaxDisplayedInGrandTotal && isDisplayed() -->\n<tr class="grand totals incl">\n    <th class="mark" scope="row">\n        <strong data-bind="i18n: inclTaxLabel"></strong>\n    </th>\n    <td data-bind="attr: {\'data-th\': inclTaxLabel}" class="amount">\n        <strong><span class="price" data-bind="text: getValue()"></span></strong>\n    </td>\n</tr>\n<tr class="grand totals excl">\n    <th class="mark" scope="row">\n        <strong data-bind="i18n: exclTaxLabel"></strong>\n    </th>\n    <td data-bind="attr: {\'data-th\': exclTaxLabel}" class="amount">\n        <strong><span class="price" data-bind="text: getGrandTotalExclTax()"></span></strong>\n    </td>\n</tr>\n<!-- /ko -->\n<!-- ko if: !isTaxDisplayedInGrandTotal && isDisplayed() -->\n<tr class="grand totals">\n    <th class="mark" scope="row">\n        <strong data-bind="i18n: title"></strong>\n    </th>\n    <td data-bind="attr: {\'data-th\': title}" class="amount">\n        <strong><span class="price" data-bind="text: getValue()"></span></strong>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_Tax/template/checkout/cart/totals/shipping.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isCalculated() && quoteIsVirtual == 0 -->\n    <!-- ko if: isBothPricesDisplayed() -->\n    <tr class="totals shipping excl">\n        <th class="mark" scope="row">\n            <span class="label" data-bind="text: title + \' \' + excludingTaxMessage"></span>\n            <!-- ko if: haveToShowCoupon() -->\n                <span class="label description" data-bind="text: getCouponDescription()"></span>\n            <!-- /ko -->\n            <span class="value" data-bind="text: getShippingMethodTitle()"></span>\n        </th>\n        <td class="amount">\n            <span class="price"\n                  data-bind="text: getExcludingValue(), attr: {\'data-th\': excludingTaxMessage}"></span>\n        </td>\n    </tr>\n    <tr class="totals shipping incl">\n        <th class="mark" scope="row">\n            <span class="label" data-bind="text: title + \' \' + includingTaxMessage"></span>\n            <!-- ko if: haveToShowCoupon() -->\n                <span class="label description" data-bind="text: getCouponDescription()"></span>\n            <!-- /ko -->\n            <span class="value" data-bind="text: getShippingMethodTitle()"></span>\n        </th>\n        <td class="amount">\n            <span class="price"\n                  data-bind="text: getIncludingValue(), attr: {\'data-th\': title + \' \' + excludingTaxMessage}"></span>\n        </td>\n    </tr>\n    <!-- /ko -->\n    <!-- ko if: isIncludingDisplayed() -->\n    <tr class="totals shipping incl">\n        <th class="mark" scope="row">\n            <span class="label" data-bind="i18n: title"></span>\n            <!-- ko if: haveToShowCoupon() -->\n                <span class="label description" data-bind="text: getCouponDescription()"></span>\n            <!-- /ko -->\n            <span class="value" data-bind="text: getShippingMethodTitle()"></span>\n        </th>\n        <td class="amount">\n            <span class="price"\n                  data-bind="text: getIncludingValue(), attr: {\'data-th\': title}"></span>\n        </td>\n    </tr>\n    <!-- /ko -->\n    <!-- ko if: isExcludingDisplayed() -->\n    <tr class="totals shipping excl">\n        <th class="mark" scope="row">\n            <span class="label" data-bind="i18n: title"></span>\n            <!-- ko if: haveToShowCoupon() -->\n                <span class="label description" data-bind="text: getCouponDescription()"></span>\n            <!-- /ko -->\n            <span class="value" data-bind="text: getShippingMethodTitle()"></span>\n        </th>\n        <td class="amount">\n            <span class="price"\n                  data-bind="text: getValue(), attr: {\'data-th\': title}"></span>\n        </td>\n    </tr>\n    <!-- /ko -->\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/cart/shipping-estimation.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<form method="post" id="shipping-zip-form">\n    <fieldset class="fieldset estimate">\n        <legend class="legend">\n            <span data-bind="text: isVirtual ? $t(\'Estimate Tax\') : $t(\'Estimate Shipping and Tax\') "></span>\n        </legend><br/>\n        <p class="field note" data-bind="text: isVirtual ? $t(\'Enter your billing address to get a tax estimate.\') : $t(\'Enter your destination to get a shipping estimate.\')"></p>\n        <!-- ko foreach: getRegion(\'address-fieldsets\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n    </fieldset>\n</form>\n';
});
define('text!ui/template/form/field.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="field" data-bind="visible: visible, attr: {\'name\': element.dataScope}, css: additionalClasses">\n\n    <label class="label" data-bind="attr: { for: element.uid }"><!-- ko if: element.label --><span translate="element.label"></span><!-- /ko --></label>\n\n    <div class="control" data-bind="css: {\'_with-tooltip\': element.tooltip}">\n        <!-- ko ifnot: element.hasAddons() -->\n            <!-- ko template: element.elementTmpl --><!-- /ko -->\n        <!-- /ko -->\n\n        <!-- ko if: element.hasAddons() -->\n            <div class="control-addon">\n                <!-- ko template: element.elementTmpl --><!-- /ko -->\n\n                <!-- ko if: element.addbefore -->\n                    <label class="addon-prefix" data-bind="attr: { for: element.uid }"><span data-bind="text: element.addbefore"></span></label>\n                <!-- /ko -->\n\n                <!-- ko if: element.addafter -->\n                    <label class="addon-suffix" data-bind="attr: { for: element.uid }"><span data-bind="text: element.addafter"></span></label>\n                <!-- /ko -->\n            </div>\n        <!-- /ko -->\n\n        <!-- ko if: element.tooltip -->\n            <!-- ko template: element.tooltipTpl --><!-- /ko -->\n        <!-- /ko -->\n\n        <!-- ko if: element.notice -->\n            <div class="field-note" data-bind="attr: { id: element.noticeId }">\n                <span data-bind="text: element.notice"></span>\n            </div>\n        <!-- /ko -->\n\n        <!-- ko if: element.error() -->\n            <div class="field-error" data-bind="attr: { id: element.errorId }" generated="true">\n                <span data-bind="text: element.error"></span>\n            </div>\n        <!-- /ko -->\n\n        <!-- ko if: element.warn() -->\n            <div role="alert" class="message warning" data-bind="attr: { id: element.warningId }" generated="true">\n                <span data-bind="text: element.warn"></span>\n            </div>\n        <!-- /ko -->\n    </div>\n</div>\n';
});
define('text!ui/template/form/element/select.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<select class="select" data-bind="\n    attr: {\n        name: inputName,\n        id: uid,\n        disabled: disabled,\n        \'aria-describedby\': getDescriptionId(),\n        \'aria-required\': required,\n        \'aria-invalid\': error() ? true : \'false\',\n        placeholder: placeholder\n    },\n    hasFocus: focused,\n    optgroup: options,\n    value: value,\n    optionsCaption: caption,\n    optionsValue: \'value\',\n    optionsText: \'label\',\n    optionsAfterRender: function(option, item) {\n        if (item && item.disabled) {\n            ko.applyBindingsToNode(option, {attr: {disabled: true}}, item);\n        }\n    }"\n></select>\n';
});
define('text!ui/template/form/element/input.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<input class="input-text" type="text" data-bind="\n    value: value,\n    valueUpdate: \'keyup\',\n    hasFocus: focused,\n    attr: {\n        name: inputName,\n        placeholder: placeholder,\n        \'aria-describedby\': getDescriptionId(),\n        \'aria-required\': required,\n        \'aria-invalid\': error() ? true : \'false\',\n        id: uid,\n        disabled: disabled\n    }" />\n';
});
"use strict";

define('Magento_Checkout/js/logo-intercept.babel', ['jquery'], $ => {
  'use strict';

  return (config, element) => {
    const elLogo = document.querySelector('a.logo');
    const elPageHeader = document.querySelector('.page-header');

    const _logo = $(elLogo);

    _logo.on('setCssProperties', () => {
      let offsetLeft = elLogo.getBoundingClientRect().left - (element.offsetWidth - elLogo.offsetWidth) / 2;
      let offsetTop = window.reactNative ? elPageHeader.offsetHeight - 80 : elPageHeader.offsetHeight;

      if (offsetLeft < 10) {
        offsetLeft = 10;
      }

      document.documentElement.style.setProperty('--logo-intercept-top', `${offsetTop}px`);
      document.documentElement.style.setProperty('--logo-intercept-left', `${offsetLeft}px`);
    }).on('click', event => {
      event.preventDefault();

      _logo.trigger('setCssProperties');

      document.body.classList.add('__show-logo-intercept');
    });

    $(window).on('resize', () => {
      _logo.trigger('setCssProperties');
    });
  };
});
/**
 * Copyright © 2019 Media Lounge. All rights reserved.
 */

define('MediaLounge_TagManager/js/checkout/onepage.babel', [
    'jquery',
    'dataLayers'
], ($, e) => {

    return function (config, element) {

        $(document).on('ajax:couponFailure', (event, data) => {
            const coupon = {};
            let msg = JSON.parse(data.message);

            coupon.code = $('#discount-code').val();
            coupon.message = msg.message;
            e.discountFailure(coupon);
        });

        $(document).on('ajax:couponSuccess', (event, data) => {
            const coupon = {};
            coupon.code = $('#discount-code').val();

            e.discountApply(coupon);
        });

        $(document).on('ajax:giftCardFailure', (event, data) => {
            const giftcard = {};
            giftcard.message = data;
            e.giftCardFailure(giftcard);
        });

        $(document).on('ajax:giftCardSuccess', (event, data) => {
            e.giftCardApply();
        });

        config.step = 2;

        e.onePageCheckout(config);

    };

});

define('Lof_SocialLogin/js/sociallogin', ['prototype'],function(){var a=new Class.create;return a.prototype={initialize:function(b,c,d,e){this.screenX='undefined'==typeof window.screenX?window.screenLeft:window.screenX,this.screenY='undefined'==typeof window.screenY?window.screenTop:window.screenY,this.outerWidth='undefined'==typeof window.outerWidth?document.body.clientWidth:window.outerWidth,this.outerHeight='undefined'==typeof window.outerHeight?document.body.clientHeight-22:window.outerHeight,this.width=b?b:1e3,this.height=c?c:700,this.left=d?d:parseInt(this.screenX+(this.outerWidth-this.width)/2,10),this.top=e?e:parseInt(this.screenY+(this.outerHeight-this.height)/2.5,10),this.features='width='+this.width+',height='+this.height+',left='+this.left+',top='+this.top},openPopup:function(b,c){window.open(b,c,this.features)},closePopup:function(){window.close()}},a});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/checkout-loader', [
    'rjsResolver'
], function (resolver) {
    'use strict';

    /**
     * Removes provided loader element from DOM.
     *
     * @param {HTMLElement} $loader - Loader DOM element.
     */
    function hideLoader($loader) {
        $loader.parentNode.removeChild($loader);
    }

    /**
     * Initializes assets loading process listener.
     *
     * @param {Object} config - Optional configuration
     * @param {HTMLElement} $loader - Loader DOM element.
     */
    function init(config, $loader) {
        resolver(hideLoader.bind(null, $loader));
    }

    return init;
});

"use strict";

define('MediaLounge_PayPalPayLater/js/paylaterPayment.babel', ['jquery', 'Magento_Checkout/js/model/totals', 'mage/cookies'], ($, totals) => {
  'use strict';

  let locale = $.cookie('geoipcountrycode') ? $.cookie('geoipcountrycode') : null;
  let scriptIsLoaded = false;
  let tmr;
  return (config, element) => {
    let elMessage = element.querySelector('[data-pp-message]');
    let elTarget;

    if (locale && locale === 'US') {
      tmr = setInterval(() => {
        elTarget = document.querySelector('.opc-block-summary');

        if (elTarget) {
          if (window.checkoutConfig.paymentMethods.findIndex(payment => payment.method === 'paypal_express') === -1) {
            return;
          }

          clearInterval(tmr);
          element.classList.add('__show');
          elTarget.insertAdjacentElement('beforebegin', element);
        }
      }, 1000);

      if (!scriptIsLoaded) {
        let script = document.createElement('script');
        script.setAttribute('src', `https://www.paypal.com/sdk/js?client-id=${config.client_id}&components=messages`);
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('data-namespace', 'paypal_sdk');
        document.getElementsByTagName('head')[0].appendChild(script);
        scriptIsLoaded = true;
      }
    }

    elMessage.setAttribute('data-pp-amount', totals.totals().base_grand_total);
    totals.totals.subscribe(() => {
      elMessage.setAttribute('data-pp-amount', totals.totals().base_grand_total);
    });
  };
});
define('Aheadworks_Giftcard/js/view/payment/giftcard-mixin', ['jquery'], $ => {
    const mixin = {
        /**
         * {@inheritdoc}
         */
        initialize: function() {
            this._super();

            $(document).on('ajax:giftCardSuccess', () => {
                this.giftcardCode('');
            });
        }
    };

    return target => target.extend(mixin);
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/onepage', ['jquery', 'uiComponent', 'ko', 'Magento_Customer/js/model/customer'], function(
    $,
    Component,
    ko,
    customer
) {
    'use strict';

    return Component.extend({
        /**
         * Initializes component
         *
         * @returns {Form} Chainable
         */
        initialize: function() {
            this._super();

            // Workaround for default payment method not showing correctly //
            let elActiveMethod = null;
            let that = this;

            this.intervalCheck = setInterval(function() {
                elActiveMethod = document.querySelector('.payment-method._active');

                if (elActiveMethod) {
                    if (elActiveMethod.id === 'checkoutcom_card_payment_container') {
                        $(elActiveMethod).trigger('click');
                    }

                    clearInterval(that.intervalCheck);
                }
            }, 1000);

            // Show/Hide the region field //
            $(document).on('change', '[name="country_id"]', event => {
                const elRegion = document.querySelector(
                    '.field[name="billingAddressshared.region"]'
                );

                if (event.currentTarget.value === 'GB') {
                    elRegion.classList.add('__hidden');
                } else {
                    elRegion.classList.remove('__hidden');
                }
            });

            const tmrCheckCountry = setInterval(() => {
                const elCountryField = document.querySelector('[name="country_id"]');

                if (elCountryField) {
                    clearInterval(tmrCheckCountry);
                    $('[name="country_id"]').trigger('change');
                }
            }, 500);

            const ivlPayPal = setInterval(() => {
                const elFrame = document.querySelector('.actions-toolbar.--card .paypal-buttons-context-iframe iframe');

                const strClassPayPalCardActive = '__paypal-card-active';

                if (elFrame) {
                    if (elFrame.offsetHeight > 400) {
                        if (!document.body.classList.contains(strClassPayPalCardActive)) {
                            document.body.classList.add(strClassPayPalCardActive);
                            elFrame.scrollTo({top: 0, behavior: 'smooth'});
                        }
                    } else {
                        if (document.body.classList.contains(strClassPayPalCardActive)) {
                            document.body.classList.remove(strClassPayPalCardActive);
                        }
                    }
                }
            }, 100);

            return this;
        },

        isCustomerLoggedIn: customer.isLoggedIn
    });
});

define('Lof_SocialLogin/js/sociallogin/social-buttons', 
    [
        'jquery',
        'ko',
        'uiComponent',
        'lof/sociallogin'
    ],
    function ($, ko, Component, SocialLoginPopup) {
        'use strict';

        ko.bindingHandlers.socialButton = {
            init: function (element, valueAccessor, allBindings) { 
                var popup = new SocialLoginPopup();
                jQuery(element).on('click', function () { 
                    popup.openPopup(allBindings.get('url'), allBindings.get('label'));
                }); 
            }
        };

        return Component.extend({
            defaults: {
                template: 'Lof_SocialLogin/social-buttons'
            },
            buttonLists: window.socialAuthenticationPopup,

            socials: function () { 
                var socials = [];

                $.each(this.buttonLists, function (key, social) {
                    socials.push(social);
                }); 
                return socials;
            },

            isActive: function () {
                return (typeof this.buttonLists !== 'undefined');
            }
        });
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary', [
    'uiComponent',
    'Magento_Checkout/js/model/totals'
], function (Component, totals) {
    'use strict';

    return Component.extend({
        isLoading: totals.isLoading
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/discount-wrapper', ['uiComponent', 'Magento_Checkout/js/model/totals'], function(Component, totals) {
    'use strict';

    return Component.extend({
        /**
         * initialize
         */
        initialize: function() {
            this._super();
        },

        isDisplayed: function() {
            return (
                totals.getSegment('mp_reward_discount') !== null ||
                totals.getSegment('discount') !== null ||
                totals.getSegment('aw_giftcard') !== null &&
                    totals.getSegment('aw_giftcard').value != 0
            );
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/item/details/thumbnail', ['uiComponent'], function (Component) {
    'use strict';

    var imageData = window.checkoutConfig.imageData;

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/item/details/thumbnail'
        },
        displayArea: 'before_details',
        imageData: imageData,

        /**
         * @param {Object} item
         * @return {Array}
         */
        getImageItem: function (item) {
            if (this.imageData[item['item_id']]) {
                return this.imageData[item['item_id']];
            }

            return [];
        },

        /**
         * @param {Object} item
         * @return {null}
         */
        getSrc: function (item) {
            if (this.imageData[item['item_id']]) {
                return this.imageData[item['item_id']].src;
            }

            return null;
        },

        /**
         * @param {Object} item
         * @return {null}
         */
        getWidth: function (item) {
            if (this.imageData[item['item_id']]) {
                return this.imageData[item['item_id']].width;
            }

            return null;
        },

        /**
         * @param {Object} item
         * @return {null}
         */
        getHeight: function (item) {
            if (this.imageData[item['item_id']]) {
                return this.imageData[item['item_id']].height;
            }

            return null;
        },

        /**
         * @param {Object} item
         * @return {null}
         */
        getAlt: function (item) {
            if (this.imageData[item['item_id']]) {
                return this.imageData[item['item_id']].alt;
            }

            return null;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/billing-address/list', [
    'uiComponent',
    'Magento_Customer/js/model/address-list',
    'mage/translate',
    'Magento_Customer/js/model/customer'
], function (Component, addressList, $t, customer) {
    'use strict';

    var newAddressOption = {
            /**
             * Get new address label
             * @returns {String}
             */
            getAddressInline: function () {
                return $t('New Address');
            },
            customerAddressId: null
        },
        addressOptions = addressList().filter(function (address) {
            return address.getType() === 'customer-address';
        }),
        addressDefaultIndex = addressOptions.findIndex(function (address) {
            return address.isDefaultBilling();
        });

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/billing-address',
            selectedAddress: null,
            isNewAddressSelected: false,
            addressOptions: addressOptions,
            exports: {
                selectedAddress: '${ $.parentName }:selectedAddress'
            }
        },

        /**
         * @returns {Object} Chainable.
         */
        initConfig: function () {
            this._super();
            this.addressOptions.push(newAddressOption);

            return this;
        },

        /**
         * @return {exports.initObservable}
         */
        initObservable: function () {
            this._super()
                .observe('selectedAddress isNewAddressSelected')
                .observe({
                    isNewAddressSelected: !customer.isLoggedIn() || !addressOptions.length,
                    selectedAddress: this.addressOptions[addressDefaultIndex]
                });

            return this;
        },

        /**
         * @param {Object} address
         * @return {*}
         */
        addressOptionsText: function (address) {
            return address.getAddressInline();
        },

        /**
         * @param {Object} address
         */
        onAddressChange: function (address) {
            this.isNewAddressSelected(address === newAddressOption);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/components/group', [
    'underscore',
    'uiCollection'
], function (_, Collection) {
    'use strict';

    return Collection.extend({
        defaults: {
            visible: true,
            label: '',
            showLabel: true,
            required: false,
            template: 'ui/group/group',
            fieldTemplate: 'ui/form/field',
            breakLine: true,
            validateWholeGroup: false,
            additionalClasses: {}
        },

        /**
         * Extends this with defaults and config.
         * Then calls initObservable, iniListenes and extractData methods.
         */
        initialize: function () {
            this._super()
                ._setClasses();

            return this;
        },

        /**
         * Calls initObservable of parent class.
         * Defines observable properties of instance.
         *
         * @return {Object} - reference to instance
         */
        initObservable: function () {
            this._super()
                .observe('visible')
                .observe({
                    required: !!+this.required
                });

            return this;
        },

        /**
         * Extends 'additionalClasses' object.
         *
         * @returns {Group} Chainable.
         */
        _setClasses: function () {
            var additional = this.additionalClasses,
                classes;

            if (_.isString(additional)) {
                additional = this.additionalClasses.split(' ');
                classes = this.additionalClasses = {};

                additional.forEach(function (name) {
                    classes[name] = true;
                }, this);
            }

            _.extend(this.additionalClasses, {
                'admin__control-grouped': !this.breakLine,
                'admin__control-fields': this.breakLine,
                required:   this.required,
                _error:     this.error,
                _disabled:  this.disabled
            });

            return this;
        },

        /**
         * Defines if group has only one element.
         * @return {Boolean}
         */
        isSingle: function () {
            return this.elems.getLength() === 1;
        },

        /**
         * Defines if group has multiple elements.
         * @return {Boolean}
         */
        isMultiple: function () {
            return this.elems.getLength() > 1;
        },

        /**
         * Returns an array of child components previews.
         *
         * @returns {Array}
         */
        getPreview: function () {
            return this.elems.map('getPreview');
        }
    });
});

define('MediaLounge_DoublePoints/js/view/payment/double-points', [
    'jquery',
    'uiComponent',
    'ko',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/model/quote',
    'mage/url'
], function($, Component, ko, Customer, quote, urlBuilder) {
    'use strict';
    return Component.extend({

        defaults: {
            activeMethod: 'checkoutcom_vault',
            countryId: null,
            doublePoints: false,
            tracks: {
                activeMethod: true,
                countryId: true,
                doublePoints: true
            }
        },

        initialize: function () {
            this._super();
            this.addressChange();
            this.paymentChange();
            return this;
        },

        checkAddress: function() {
            let self = this;
            $.ajax({
                url: urlBuilder.build(`points/address/check`),
                contentType: "application/json",
                dataType: 'json',
                data: {},
                success: function (result) {
                    if (result.success) {
                        self.doublePoints = result.points;
                    }
                }
            });
        },

        checkPoints: function() {
            setTimeout((e) => {
                if (this.isLoggedIn() && quote.billingAddress()) {
                    this.checkAddress();
                }
            }, 1500);
        },

        isLoggedIn: function () {
            return Customer.isLoggedIn();
        },

        paymentChange: function () {
            let self = this;
            quote.paymentMethod.subscribe(function(e) {
                if (e) {
                    self.activeMethod = e.method;
                } else {
                    self.activeMethod = null;
                }
            });
        },

        addressChange: function () {
            let self = this;
            quote.billingAddress.subscribe(function(e) {
                if (!e) return;
                if (self.countryId !== e.countryId) {
                    self.countryId = e.countryId;
                    self.checkPoints();
                }
            });
        },

    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('MediaLounge_FraudAccounts/js/view/device-registration', [
    'jquery',
    'uiComponent',
    'ko',
    'Magento_Customer/js/customer-data'
], function(
    $,
    Component,
    ko,
    customerData
) {
    'use strict';
    return Component.extend({

        initialize: function () {
            this._super();
            this.isDeviceRegistered();
            return this;
        },

        /**
         * @return {*|String}
         */
        isDeviceRegistered: function() {
            if (customerData.get('device')().restricted) {
                $('.form.form-email.form-login').hide();

                setTimeout(() => {
                    // Secondary hide with slight delay to account for this running
                    // before the login form has been rendered
                    $('.form.form-email.form-login').hide();
                }, 100);
                return false;
            }
            return true;
        },

        cancelDeviceRegistration: function() {
            customerData.set('device', false);
            $('.form.form-email.form-login').fadeIn();
            this.isDeviceRegistered();
        }

    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/item/details/message', ['uiComponent'], function (Component) {
    'use strict';

    var quoteMessages = window.checkoutConfig.quoteMessages;

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/item/details/message'
        },
        displayArea: 'item_message',
        quoteMessages: quoteMessages,

        /**
         * @param {Object} item
         * @return {null}
         */
        getMessage: function (item) {
            if (this.quoteMessages[item['item_id']]) {
                return this.quoteMessages[item['item_id']];
            }

            return null;
        }
    });
});

define('MediaLounge_PayPalPayLater/js/view/promotion', [
    'jquery',
    'uiElement',
], function( $, Component) {
    'use strict';

    return Component.extend({

        defaults: {
            message: null
        },

        initialize: function () {
            this._super();
            // component initialization logic
            this.getPromotionMessage();
            return this;
        },

        getPromotionMessage: function () {
            this.message = window.checkoutConfig['paypalPromotion'] ? window.checkoutConfig['paypalPromotion']['message'] : null;
        },

        isPromotionEnabled: function () {
            return this.message && $.cookie('geoipcountrycode') === 'GB'
        }
    });
});

define('MediaLounge_CheckoutMessage/js/view/promotion', [
    'jquery',
    'uiElement',
    'mage/url',
    'mage/cookies',
], function($, Component, url) {
    'use strict';

    return Component.extend({

        defaults: {
            message: null
        },

        initialize: function () {
            this._super();
            // component initialization logic
            this.getPromotionMessage();
            return this;
        },

        getMessageAsync: function() {
            const locale = $.cookie('geoipcountrycode') ? $.cookie('geoipcountrycode') : null;

            $.ajax({
                url: url.build('checkoutmessage'),
                data: { locale },
                success: (data) => {
                    if (data.success)
                    {
                        this.message = data.content;
                    }
                }
            });
        },

        getPromotionMessage: function () {
            this.message = window.checkoutConfig['checkoutMessage'] ? window.checkoutConfig['checkoutMessage']['message'] : null;
        },

        isPromotionEnabled: function () {
            // return this.message && $.cookie('geoipcountrycode') === 'GB'
        }
    });
});

define('MediaLounge_RegionalRestrictions/js/view/checkout', [
    'uiElement',
    'Magento_Customer/js/customer-data',
    'mage/translate',
    'ko',
    'Magento_Checkout/js/model/quote'

], function( Component, customerData, $t, ko, quote) {
    'use strict';

    return Component.extend({

        initialize: function () {
            this._super();
            // component initialization logic
            return this;
        },

        /**
         * @return {*|String}
         */
        isCheckoutRestricted: function() {
            return !!customerData.get('cart')().payment_restrictions;
        },

        /**
         * @return {*|String}
         */
        getCheckoutRestrictMessages: function() {
            if (customerData.get('cart')().payment_restrictions) {
                return customerData.get('cart')().payment_restrictions;
            }
        },
    });
});

define('MediaLounge_RegionalRestrictions/js/view/restrict', [
    'uiElement',
    'Magento_Customer/js/customer-data',
    'mage/translate',
    'ko',
    'Magento_Checkout/js/model/quote'
], function( Component, customerData, $t, ko, quote ) {
    'use strict';

    return Component.extend({
        multiple: $t('Warning: One or more products in your basket cannot be activated in your Country/Region. If you still want to purchase, click "Place Order".'),
        defaults: {
            countryId: null
        },

        initialize: function () {
            this._super();
            this.checkAddress();
            // component initialization logic
            return this;
        },

        /**
         * @return {*|String}
         */
        isRestricted: function() {
            return !!customerData.get('cart')().restrictions;
        },

        /**
         * @return {*|String}
         */
        getRestrictMessages: function() {
            if (customerData.get('cart')().restrictions) {
                return customerData.get('cart')().restrictions;
            }
        },

        checkAddress: function() {
            quote.billingAddress.subscribe((billing) => {
                if (billing && this.countryId !== billing.countryId) {
                    this.countryId = billing.countryId
                    setTimeout(() => {
                        customerData.invalidate(['cart']);
                        customerData.reload(['cart'], true);
                    }, 1000);
                }
            });
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/grand-total', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote'
], function (Component, quote) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/grand-total'
        },

        /**
         * @return {*}
         */
        isDisplayed: function () {
            return this.isFullMode();
        },

        /**
         * Get pure value.
         */
        getPureValue: function () {
            var totals = quote.getTotals()();

            if (totals) {
                return totals['grand_total'];
            }

            return quote['grand_total'];
        },

        /**
         * @return {*|String}
         */
        getValue: function () {
            return this.getFormattedPrice(this.getPureValue());
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/totals', [
    'Magento_Checkout/js/view/summary/abstract-total'
], function (Component) {
    'use strict';

    return Component.extend({
        /**
         * @return {*}
         */
        isDisplayed: function () {
            return this.isFullMode();
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/subtotal', [
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote'
], function (Component, quote) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/subtotal'
        },

        /**
         * Get pure value.
         *
         * @return {*}
         */
        getPureValue: function () {
            var totals = quote.getTotals()();

            if (totals) {
                return totals.subtotal;
            }

            return quote.subtotal;
        },

        /**
         * @return {*|String}
         */
        getValue: function () {
            return this.getFormattedPrice(this.getPureValue());
        }

    });
});

/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_RewardPoints
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
define('Mageplaza_RewardPoints/js/view/totals/discount', [
        'Magento_Checkout/js/view/summary/abstract-total',
        'Magento_Checkout/js/model/totals'
    ], function (Component, totals) {
        "use strict";
        return Component.extend({
            defaults: {
                template: 'Mageplaza_RewardPoints/totals/discount'
            },

            /**
             * Get reward discount total
             * @returns {*}
             */
            getTotal: function () {
                return totals.getSegment('mp_reward_discount');
            },

            /**
             * Get reward discount formatted
             * @returns {*|String}
             */
            getValue: function () {
                return this.getFormattedPrice(this.getTotal().value);
            }
        });
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/item/details/subtotal', [
    'Magento_Checkout/js/view/summary/abstract-total'
], function (viewModel) {
    'use strict';

    return viewModel.extend({
        defaults: {
            displayArea: 'after_details',
            template: 'Magento_Checkout/summary/item/details/subtotal'
        },

        /**
         * @param {Object} quoteItem
         * @return {*|String}
         */
        getValue: function (quoteItem) {
            return this.getFormattedPrice(quoteItem['row_total']);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/cart-items', [
    'ko',
    'Magento_Checkout/js/model/totals',
    'uiComponent',
    'Magento_Checkout/js/model/step-navigator',
    'Magento_Checkout/js/model/quote'
], function (ko, totals, Component, stepNavigator, quote) {
    'use strict';

    var useQty = window.checkoutConfig.useQty;

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/cart-items'
        },
        totals: totals.totals(),
        items: ko.observable([]),
        maxCartItemsToDisplay: window.checkoutConfig.maxCartItemsToDisplay,
        cartUrl: window.checkoutConfig.cartUrl,

        /**
         * @deprecated Please use observable property (this.items())
         */
        getItems: totals.getItems(),

        /**
         * Returns cart items qty
         *
         * @returns {Number}
         */
        getItemsQty: function () {
            return parseFloat(this.totals['items_qty']);
        },

        /**
         * Returns count of cart line items
         *
         * @returns {Number}
         */
        getCartLineItemsCount: function () {
            return parseInt(totals.getItems()().length, 10);
        },

        /**
         * Returns shopping cart items summary (includes config settings)
         *
         * @returns {Number}
         */
        getCartSummaryItemsCount: function () {
            return useQty ? this.getItemsQty() : this.getCartLineItemsCount();
        },

        /**
         * @inheritdoc
         */
        initialize: function () {
            this._super();
            // Set initial items to observable field
            this.setItems(totals.getItems()());
            // Subscribe for items data changes and refresh items in view
            totals.getItems().subscribe(function (items) {
                this.setItems(items);
            }.bind(this));
        },

        /**
         * Set items to observable field
         *
         * @param {Object} items
         */
        setItems: function (items) {
            if (items && items.length > 0) {
                items = items.slice(parseInt(-this.maxCartItemsToDisplay, 10));
            }
            this.items(items);
        },

        /**
         * Returns bool value for items block state (expanded or not)
         *
         * @returns {*|Boolean}
         */
        isItemsBlockExpanded: function () {
            return quote.isVirtual() || stepNavigator.isProcessed('shipping');
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/summary/item/details', [
    'uiComponent',
    'escaper'
], function (Component, escaper) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/summary/item/details',
            allowedTags: ['b', 'strong', 'i', 'em', 'u']
        },

        /**
         * @param {Object} quoteItem
         * @return {String}
         */
        getNameUnsanitizedHtml: function (quoteItem) {
            var txt = document.createElement('textarea');

            txt.innerHTML = quoteItem.name;

            return escaper.escapeHtml(txt.value, this.allowedTags);
        },

        /**
         * @param {Object} quoteItem
         * @return {String}Magento_Checkout/js/region-updater
         */
        getValue: function (quoteItem) {
            return quoteItem.name;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/model/agreement-validator', [
    'jquery',
    'mage/validation'
], function ($) {
    'use strict';

    var checkoutConfig = window.checkoutConfig,
        agreementsConfig = checkoutConfig ? checkoutConfig.checkoutAgreements : {},
        agreementsInputPath = '.payment-method._active div.checkout-agreements input';

    return {
        /**
         * Validate checkout agreements
         *
         * @returns {Boolean}
         */
        validate: function (hideError) {
            var isValid = true;

            if (!agreementsConfig.isEnabled || $(agreementsInputPath).length === 0) {
                return true;
            }

            $(agreementsInputPath).each(function (index, element) {
                if (!$.validator.validateSingleElement(element, {
                    errorElement: 'div',
                    hideError: hideError || false
                })) {
                    isValid = false;
                }
            });

            return isValid;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/view/agreement-validation', [
    'uiComponent',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_CheckoutAgreements/js/model/agreement-validator'
], function (Component, additionalValidators, agreementValidator) {
    'use strict';

    additionalValidators.registerValidator(agreementValidator);

    return Component.extend({});
});

define('MediaLounge_TazaPay/js/view/payment/config-loader', 
    [
        'jquery'
    ],
    function ($) {
        'use strict';
        const MODULE_ID = 'tazapay';
        return window.checkoutConfig.payment[MODULE_ID];
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment/renderer-list', [
    'ko'
], function (ko) {
    'use strict';

    return ko.observableArray([]);
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* @api */
define('Magento_OfflinePayments/js/view/payment/offline-payments', [
    'uiComponent',
    'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
    'use strict';

    rendererList.push(
        {
            type: 'checkmo',
            component: 'Magento_OfflinePayments/js/view/payment/method-renderer/checkmo-method'
        },
        {
            type: 'banktransfer',
            component: 'Magento_OfflinePayments/js/view/payment/method-renderer/banktransfer-method'
        },
        {
            type: 'cashondelivery',
            component: 'Magento_OfflinePayments/js/view/payment/method-renderer/cashondelivery-method'
        },
        {
            type: 'purchaseorder',
            component: 'Magento_OfflinePayments/js/view/payment/method-renderer/purchaseorder-method'
        }
    );

    /** Add view logic here if needed */
    return Component.extend({});
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Paypal/js/view/payment/paypal-payments', [
    'uiComponent',
    'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
    'use strict';

    var isContextCheckout = window.checkoutConfig.payment.paypalExpress.isContextCheckout,
        paypalExpress = 'Magento_Paypal/js/view/payment/method-renderer' +
            (isContextCheckout ? '/in-context/checkout-express' : '/paypal-express');

    rendererList.push(
        {
            type: 'paypal_express',
            component: paypalExpress,
            config: window.checkoutConfig.payment.paypalExpress.inContextConfig
        },
        {
            type: 'payflow_express',
            component: 'Magento_Paypal/js/view/payment/method-renderer/payflow-express'
        },
        {
            type: 'payflow_express_bml',
            component: 'Magento_Paypal/js/view/payment/method-renderer/payflow-express-bml'
        },
        {
            type: 'payflowpro',
            component: 'Magento_Paypal/js/view/payment/method-renderer/payflowpro-method'
        },
        {
            type: 'payflow_link',
            component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'
        },
        {
            type: 'payflow_advanced',
            component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'
        },
        {
            type: 'hosted_pro',
            component: 'Magento_Paypal/js/view/payment/method-renderer/iframe-methods'
        },
        {
            type: 'paypal_billing_agreement',
            component: 'Magento_Paypal/js/view/payment/method-renderer/paypal-billing-agreement'
        }
    );

    /**
     * Add view logic here if needed
     **/
    return Component.extend({});
});

define('MediaLounge_Coinify/js/view/payment/coinify', 
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/renderer-list'
    ],
    function (
        Component,
        rendererList
    ) {
        'use strict';
        rendererList.push(
            {
                type: 'coinify',
                component: 'MediaLounge_Coinify/js/view/payment/method-renderer/coinify'
            }
        );
        return Component.extend({});
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* @api */
define('Magento_Payment/js/view/payment/payments', [
    'uiComponent',
    'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
    'use strict';

    rendererList.push(
        {
            type: 'free',
            component: 'Magento_Payment/js/view/payment/method-renderer/free-method'
        }
    );

    /** Add view logic here if needed */
    return Component.extend({});
});

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/view/payment/method-renderer', 
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/renderer-list',
        'CheckoutCom_Magento2/js/view/payment/config-loader'
    ],
    function (
        Component,
        rendererList,
        Config
    ) {
        // Render the active payment methods
        for (var method in Config) {
            if (method === 'checkoutcom_apple_pay' && !window.ApplePaySession) {
                continue; // Skip render if Apple Pay is run in wrong browser
            } else {
                rendererList.push(
                    {
                        type: method,
                        component: 'CheckoutCom_Magento2/js/view/payment/method-renderer/' + method
                    }
                );
            }
        }

        return Component.extend({});
    }
);

/*browser:true*/
/*global define*/
define('MediaLounge_Credorax/js/view/payment/credorax', 
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/renderer-list'
    ],
    function (
        Component,
        rendererList
    ) {
        'use strict';
        rendererList.push(
            {
                type: 'credorax_alipay',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_giropay',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_ideal',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_p24',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_skrill',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_sofort',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        rendererList.push(
            {
                type: 'credorax_dumbdummy',
                component: 'MediaLounge_Credorax/js/view/payment/method-renderer/credorax'
            }
        );
        /** Add view logic here if needed */
        return Component.extend({});
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('MediaLounge_PaypalCards/js/view/payment/method-renderer', [
    'uiComponent',
    'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
    'use strict';

    if (window.checkoutConfig.payment.paypalExpressCard) {
        rendererList.push(
            {
                type: 'paypal_express_card',
                component: 'MediaLounge_PaypalCards/js/view/payment/method-renderer/paypal-express-card',
                config: window.checkoutConfig.payment.paypalExpressCard.inContextConfig
            },
        );
    }

    /**
     * Add view logic here if needed
     **/
    return Component.extend({});
});

define('MediaLounge_TazaPay/js/view/payment/method-renderer', 
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/renderer-list',
        'MediaLounge_TazaPay/js/view/payment/config-loader'
    ],
    function(
        Component,
        rendererList,
        Config
    ) {
        'use strict';
        for (var method in Config) {
            rendererList.push(
                {
                    type: method,
                    component: 'MediaLounge_TazaPay/js/view/payment/method-renderer/tazapay'
                }
            );
        }
        return Component.extend({});
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/model/agreements-modal', [
    'jquery',
    'Magento_Ui/js/modal/modal',
    'mage/translate'
], function ($, modal, $t) {
    'use strict';

    return {
        modalWindow: null,

        /**
         * Create popUp window for provided element.
         *
         * @param {HTMLElement} element
         */
        createModal: function (element) {
            var options;

            this.modalWindow = element;
            options = {
                'type': 'popup',
                'modalClass': 'agreements-modal',
                'responsive': true,
                'innerScroll': true,
                'trigger': '.show-modal',
                'buttons': [
                    {
                        text: $t('Close'),
                        class: 'action secondary action-hide-popup',

                        /** @inheritdoc */
                        click: function () {
                            this.closeModal();
                        }
                    }
                ]
            };
            modal(options, $(this.modalWindow));
        },

        /** Show login popup window */
        showModal: function () {
            $(this.modalWindow).modal('openModal');
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/view/checkout-agreements', [
    'ko',
    'jquery',
    'uiComponent',
    'Magento_CheckoutAgreements/js/model/agreements-modal'
], function(ko, $, Component, agreementsModal) {
    'use strict';

    var checkoutConfig = window.checkoutConfig,
        agreementManualMode = 1,
        agreementsConfig = checkoutConfig ? checkoutConfig.checkoutAgreements : {};

    return Component.extend({
        defaults: {
            template: 'Magento_CheckoutAgreements/checkout/checkout-agreements'
        },
        isVisible: agreementsConfig.isEnabled,
        agreements: agreementsConfig.agreements,
        modalTitle: ko.observable(null),
        modalContent: ko.observable(null),
        contentHeight: ko.observable(null),
        modalWindow: null,

        /**
         * Checks if agreement required
         *
         * @param {Object} element
         */
        isAgreementRequired: function(element) {
            return element.mode == agreementManualMode; //eslint-disable-line eqeqeq
        },

        htmlDecode: function(input) {
            var e = document.createElement('div');

            e.innerHTML = input;

            return e.childNodes.length === 0 ? '' : e.childNodes[0].nodeValue;
        },

        /**
         * Show agreement content in modal
         *
         * @param {Object} element
         */
        showContent: function(element) {
            this.modalTitle(element.checkboxText);
            this.modalContent(element.content);
            this.contentHeight(element.contentHeight ? element.contentHeight : 'auto');
            agreementsModal.showModal();
        },

        /**
         * build a unique id for the term checkbox
         *
         * @param {Object} context - the ko context
         * @param {Number} agreementId
         */
        getCheckboxId: function(context, agreementId) {
            var paymentMethodName = '',
                paymentMethodRenderer = context.$parents[1];

            // corresponding payment method fetched from parent context
            if (paymentMethodRenderer) {
                // item looks like this: {title: "Check / Money order", method: "checkmo"}
                paymentMethodName = paymentMethodRenderer.item
                    ? paymentMethodRenderer.item.method
                    : '';
            }

            return 'agreement_' + paymentMethodName + '_' + agreementId;
        },

        /**
         * Init modal window for rendered element
         *
         * @param {Object} element
         */
        initModal: function(element) {
            agreementsModal.createModal(element);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/customer-email-validator', [
    'jquery',
    'Magento_Customer/js/model/customer',
    'mage/validation'
], function ($, customer) {
    'use strict';

    let a = false;

    return {
        /**
         * Validate checkout agreements
         *
         * @returns {Boolean}
         */
        validate: function () {
            if (!a) {
                a = true;
                return;
            }
            var emailValidationResult = customer.isLoggedIn(),
                loginFormSelector = 'form[data-role=email-with-possible-login]';

            if (!customer.isLoggedIn()) {
                $(loginFormSelector).validation();
                emailValidationResult = Boolean($(loginFormSelector + ' input[name=username]').valid());
            }

            return emailValidationResult;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Checkout/js/view/payment/email-validator', 
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Checkout/js/model/customer-email-validator'
    ],
    function (Component, additionalValidators, agreementValidator) {
        'use strict';

        additionalValidators.registerValidator(agreementValidator);

        return Component.extend({});
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Captcha/js/model/captchaList', ['jquery'], function ($) {
    'use strict';

    var captchaList = [];

    return {
        /**
         * @param {Object} captcha
         */
        add: function (captcha) {
            captchaList.push(captcha);
        },

        /**
         * @param {String} formId
         * @return {Object}
         */
        getCaptchaByFormId: function (formId) {
            var captcha = null;

            $.each(captchaList, function (key, item) {
                if (formId === item.formId) {
                    captcha = item;

                    return false;
                }
            });

            return captcha;
        },

        /**
         * @return {Array}
         */
        getCaptchaList: function () {
            return captchaList;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_ReCaptchaFrontendUi/js/registry', ['ko'], function (ko) {
    'use strict';

    return {
        ids: ko.observableArray([]),
        captchaList: ko.observableArray([]),
        tokenFields: ko.observableArray([])
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_ReCaptchaFrontendUi/js/ui-messages-mixin', ['Magento_ReCaptchaFrontendUi/js/registry'], function (registry) {
    'use strict';

    return function (originalComponent) {
        return originalComponent.extend({
            /**
             * Initialize reset on messages
             * @returns {initialize}
             */
            initialize: function () {
                this._super();

                this.messageContainer.errorMessages.subscribe(function () {
                    var
                        i,
                        captchaList = registry.captchaList(),
                        tokenFieldsList = registry.tokenFields();

                    for (i = 0; i < captchaList.length; i++) {
                        // eslint-disable-next-line no-undef
                        grecaptcha.reset(captchaList[i]);

                        if (tokenFieldsList[i]) {
                            tokenFieldsList[i].value = '';
                        }
                    }
                }, null, 'arrayChange');

                return this;
            }
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Customer/js/action/check-email-availability', [
    'mage/storage',
    'Magento_Checkout/js/model/url-builder'
], function (storage, urlBuilder) {
    'use strict';

    return function (deferred, email) {
        return storage.post(
            urlBuilder.createUrl('/customers/isEmailAvailable', {}),
            JSON.stringify({
                customerEmail: email
            }),
            false
        ).done(function (isEmailAvailable) {
            if (isEmailAvailable) {
                deferred.resolve();
            } else {
                deferred.reject();
            }
        }).fail(function () {
            deferred.reject();
        });
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/authentication-messages', [
    'ko',
    'Magento_Ui/js/model/messages'
], function (ko, Messages) {
    'use strict';

    return new Messages();
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/model/payment/discount-messages', [
    'Magento_Ui/js/model/messages'
], function (Messages) {
    'use strict';

    return new Messages();
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('MediaLounge_SecurePasswords/js/action/login', [
    'jquery',
    'mage/storage',
    'Magento_Ui/js/model/messageList',
    'Magento_Customer/js/customer-data',
    'mage/translate',
    'mage/cookies'
], function ($, storage, globalMessageList, customerData, $t) {
    'use strict';

    var callbacks = [],

        /**
         * @param {Object} loginData
         * @param {String} redirectUrl
         * @param {*} isGlobal
         * @param {Object} messageContainer
         */
        action = function (loginData, redirectUrl, isGlobal, messageContainer) {
            messageContainer = messageContainer || globalMessageList;

            $.cookie('login_redirect', window.checkoutConfig.checkoutUrl, { path: '/' });

            return storage.post(
                'customer/ajax/login',
                JSON.stringify(loginData),
                isGlobal
            ).done(function (response) {
                if (response.errors) {
                    messageContainer.addErrorMessage(response);
                    callbacks.forEach(function (callback) {
                        callback(loginData);
                    });
                } else {
                    callbacks.forEach(function (callback) {
                        callback(loginData);
                    });
                    customerData.invalidate(['customer']);

                    if (response.redirectUrl) {
                        window.location.href = response.redirectUrl;
                    } else if (redirectUrl) {
                        window.location.href = redirectUrl;
                    } else {
                        location.reload();
                    }
                }
            }).fail(function () {
                messageContainer.addErrorMessage({
                    'message': $t('Could not authenticate. Please try again later')
                });
                callbacks.forEach(function (callback) {
                    callback(loginData);
                });
            });
        };

    /**
     * @param {Function} callback
     */
    action.registerLoginCallback = function (callback) {
        $.cookie('login_redirect', null, { path: '/' });
        callbacks.push(callback);
    };

    return action;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('MediaLounge_Checkout/js/view/form/element/login', [
    'jquery',
    'uiComponent',
    'ko',
    'Magento_Customer/js/model/customer',
    'Magento_Customer/js/action/check-email-availability',
    'Magento_Customer/js/action/login',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/full-screen-loader',
    'mage/validation'
], function ($, Component, ko, customer, checkEmailAvailability, loginAction, quote, checkoutData, fullScreenLoader) {
    'use strict';

    // var validatedEmail;

    // if (!checkoutData.getValidatedEmailValue() &&
    //     window.checkoutConfig.validatedEmailValue
    // ) {
    //     checkoutData.setInputFieldEmailValue(window.checkoutConfig.validatedEmailValue);
    //     checkoutData.setValidatedEmailValue(window.checkoutConfig.validatedEmailValue);
    // }

    // validatedEmail = checkoutData.getValidatedEmailValue();

    // if (validatedEmail && !customer.isLoggedIn()) {
    //     quote.guestEmail = validatedEmail;
    // }

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/form/element/email',
            email: checkoutData.getInputFieldEmailValue(),
            emailFocused: false,
            isLoading: false,
            isPasswordVisible: false,
            listens: {
                email: 'emailHasChanged',
                // emailFocused: 'validateEmail'
            },
            ignoreTmpls: {
                email: true
            }
        },
        checkDelay: 2000,
        checkRequest: null,
        isEmailCheckComplete: null,
        isCustomerLoggedIn: customer.isLoggedIn,
        forgotPasswordUrl: window.checkoutConfig.forgotPasswordUrl,
        emailCheckTimeout: 0,

        /**
         * Initializes regular properties of instance.
         *
         * @returns {Object} Chainable.
         */
        initConfig: function () {
            this._super();

            this.isPasswordVisible = this.resolveInitialPasswordVisibility();

            return this;
        },

        /**
         * Initializes observable properties of instance
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super()
                .observe(['email', 'emailFocused', 'isLoading', 'isPasswordVisible']);

            return this;
        },

        /**
         * Callback on changing email property
         */
        emailHasChanged: function () {
            var self = this;

            clearTimeout(this.emailCheckTimeout);

            // if (self.validateEmail()) {
            //     quote.guestEmail = self.email();
            //     checkoutData.setValidatedEmailValue(self.email());
            // }
            // this.emailCheckTimeout = setTimeout(function () {
            //     if (self.validateEmail()) {
            //         self.checkEmailAvailability();
            //     } else {
            //         self.isPasswordVisible(false);
            //     }
            // }, self.checkDelay);

            checkoutData.setInputFieldEmailValue(self.email());
        },

        /**
         * Check email existing.
         */
        checkEmailAvailability: function () {
            this.validateRequest();
            this.isEmailCheckComplete = $.Deferred();
            this.isLoading(true);
            this.checkRequest = checkEmailAvailability(this.isEmailCheckComplete, this.email());

            $.when(this.isEmailCheckComplete).done(function () {
                this.isPasswordVisible(false);
            }.bind(this)).fail(function () {
                this.isPasswordVisible(true);
                checkoutData.setCheckedEmailValue(this.email());
            }.bind(this)).always(function () {
                this.isLoading(false);
            }.bind(this));
        },

        /**
         * If request has been sent -> abort it.
         * ReadyStates for request aborting:
         * 1 - The request has been set up
         * 2 - The request has been sent
         * 3 - The request is in process
         */
        validateRequest: function () {
            if (this.checkRequest != null && $.inArray(this.checkRequest.readyState, [1, 2, 3])) {
                this.checkRequest.abort();
                this.checkRequest = null;
            }
        },

        /**
         * Local email validation.
         *
         * @param {Boolean} focused - input focus.
         * @returns {Boolean} - validation result.
         */
        validateEmail: function (focused) {
            var loginFormSelector = 'form.form.form-email.form-login',
                usernameSelector = loginFormSelector + ' input[name=username]',
                loginForm = $(loginFormSelector),
                validator,
                valid;

            loginForm.validation();

            if (focused === false && !!this.email()) {
                valid = !!$(usernameSelector).valid();

                if (valid) {
                    $(usernameSelector).removeAttr('aria-invalid aria-describedby');
                }

                return valid;
            }

            validator = loginForm.validate();

            return validator.check(usernameSelector);
        },

        /**
         * Log in form submitting callback.
         *
         * @param {HTMLElement} loginForm - form element.
         */
        login: function (loginForm) {
            var loginData = {},
                formDataArray = $(loginForm).serializeArray();

            formDataArray.forEach(function (entry) {
                loginData[entry.name] = entry.value;
            });

            if ($(loginForm).validation() && $(loginForm).validation('isValid')) {
                fullScreenLoader.startLoader();
                loginAction(loginData).always(function () {
                    fullScreenLoader.stopLoader();
                });
            }
        },

        /**
         * Resolves an initial state of a login form.
         *
         * @returns {Boolean} - initial visibility state.
         */
        resolveInitialPasswordVisibility: function () {
            if (checkoutData.getInputFieldEmailValue() !== '' && checkoutData.getCheckedEmailValue() === '') {
                return true;
            }

            if (checkoutData.getInputFieldEmailValue() !== '') {
                return checkoutData.getInputFieldEmailValue() === checkoutData.getCheckedEmailValue();
            }

            return false;
        }
    });
});

define('MediaLounge_Checkout/js/view/form/element/email-mixin', [
    'jquery',
    'uiComponent',
    'ko',
    'Magento_Customer/js/model/customer',
    'Magento_Customer/js/action/check-email-availability',
    'Magento_Customer/js/action/login',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/full-screen-loader',
    'mage/validation',
    'mage/url'
    ], function($, Component, ko, customer, checkEmailAvailability, loginAction, quote, checkoutData, fullScreenLoader, validation, mageUrl){
    'use strict';

    var mixin = {
        checkDelay: 500,
        defaults: {
            isGuestEmail: false,
            tracks: {
                isGuestEmail: true,
            }
        },

        initialize: function () {
            this._super();

            this.checkEmailAvailability();
        },

        /**
         * Initializes regular properties of instance.
         *
         * @returns {Object} Chainable.
         */
        initConfig: function () {
            this._super();
            this.isPasswordVisible = false;

            return this;
        },

        login: function (loginForm) {
            var loginData = {},
                formDataArray = $(loginForm).serializeArray();

            formDataArray.forEach(function (entry) {
                loginData[entry.name] = entry.value;
            });

            if (this.isPasswordVisible() && $(loginForm).validation() && $(loginForm).validation('isValid')) {
                fullScreenLoader.startLoader();

                loginAction(loginData).always(function (data, status) {
                    fullScreenLoader.stopLoader();

                    if (status === 'success' && data.errors === false) {
                        window.location.reload();
                    }
                });
            }
        },

        loginUrl: function()
        {
            return mageUrl.build('customer/account/login/');
        },

        /**
         * Check email existing.
         */
        checkEmailAvailability: function () {

            if (!this.email()) {
                return;
            }

            this.activeElement = document.activeElement;
            this.validateRequest();
            this.isEmailCheckComplete = $.Deferred();
            this.isLoading(true);
            this.checkRequest = checkEmailAvailability(this.isEmailCheckComplete, this.email());

            $.when(this.isEmailCheckComplete).done(function () {
                this.isPasswordVisible(false);
                this.isGuestEmail = true;
            }.bind(this)).fail(function () {
                this.isPasswordVisible(true);
                this.isGuestEmail = false;
                checkoutData.setCheckedEmailValue(this.email());
            }.bind(this)).always(function () {
                this.isLoading(false);

                if (document.activeElement === document.body) {
                    if (this.activeElement) {
                        this.activeElement.focus();
                    }
                }
            }.bind(this));
        },

        /**
         * Toggle login popup
         */
        loginPopup: function () {
            let email = $('#customer-email').val();
            if (email) {
                $('#checkout-login-email').val(email);
            }

            $('body').toggleClass('__checkout-as-guest');
        },

        /**
         * @returns {string}
         */
        loginPopupText: function () {
            return $.mage.__('You have an existing CDKeys account! Click %1here%2 to login, or continue with your purchase as a guest.').replace('%1', '<strong>').replace('%2', '</strong>');
        }

    };

    return function(target) {
        return target.extend(mixin);
    }
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/form/element/email', [
    'jquery',
    'uiComponent',
    'ko',
    'Magento_Customer/js/model/customer',
    'Magento_Customer/js/action/check-email-availability',
    'Magento_Customer/js/action/login',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/full-screen-loader',
    'mage/validation'
], function ($, Component, ko, customer, checkEmailAvailability, loginAction, quote, checkoutData, fullScreenLoader) {
    'use strict';

    var validatedEmail;

    if (!checkoutData.getValidatedEmailValue() &&
        window.checkoutConfig.validatedEmailValue
    ) {
        checkoutData.setInputFieldEmailValue(window.checkoutConfig.validatedEmailValue);
        checkoutData.setValidatedEmailValue(window.checkoutConfig.validatedEmailValue);
    }

    validatedEmail = checkoutData.getValidatedEmailValue();

    if (validatedEmail && !customer.isLoggedIn()) {
        quote.guestEmail = validatedEmail;
    }

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/form/element/email',
            email: checkoutData.getInputFieldEmailValue(),
            emailFocused: false,
            isLoading: false,
            isPasswordVisible: false,
            listens: {
                email: 'emailHasChanged',
                emailFocused: 'validateEmail'
            },
            ignoreTmpls: {
                email: true
            }
        },
        checkDelay: 2000,
        checkRequest: null,
        isEmailCheckComplete: null,
        isCustomerLoggedIn: customer.isLoggedIn,
        forgotPasswordUrl: window.checkoutConfig.forgotPasswordUrl,
        emailCheckTimeout: 0,

        /**
         * Initializes regular properties of instance.
         *
         * @returns {Object} Chainable.
         */
        initConfig: function () {
            this._super();

            this.isPasswordVisible = this.resolveInitialPasswordVisibility();

            return this;
        },

        /**
         * Initializes observable properties of instance
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super()
                .observe(['email', 'emailFocused', 'isLoading', 'isPasswordVisible']);

            return this;
        },

        /**
         * Callback on changing email property
         */
        emailHasChanged: function () {
            var self = this;

            clearTimeout(this.emailCheckTimeout);

            if (self.validateEmail()) {
                quote.guestEmail = self.email();
                checkoutData.setValidatedEmailValue(self.email());
            }
            this.emailCheckTimeout = setTimeout(function () {
                if (self.validateEmail()) {
                    self.checkEmailAvailability();
                } else {
                    self.isPasswordVisible(false);
                }
            }, self.checkDelay);

            checkoutData.setInputFieldEmailValue(self.email());
        },

        /**
         * Check email existing.
         */
        checkEmailAvailability: function () {
            this.validateRequest();
            this.isEmailCheckComplete = $.Deferred();
            this.isLoading(true);
            this.checkRequest = checkEmailAvailability(this.isEmailCheckComplete, this.email());

            $.when(this.isEmailCheckComplete).done(function () {
                this.isPasswordVisible(false);
                checkoutData.setCheckedEmailValue('');
            }.bind(this)).fail(function () {
                this.isPasswordVisible(true);
                checkoutData.setCheckedEmailValue(this.email());
            }.bind(this)).always(function () {
                this.isLoading(false);
            }.bind(this));
        },

        /**
         * If request has been sent -> abort it.
         * ReadyStates for request aborting:
         * 1 - The request has been set up
         * 2 - The request has been sent
         * 3 - The request is in process
         */
        validateRequest: function () {
            if (this.checkRequest != null && $.inArray(this.checkRequest.readyState, [1, 2, 3])) {
                this.checkRequest.abort();
                this.checkRequest = null;
            }
        },

        /**
         * Local email validation.
         *
         * @param {Boolean} focused - input focus.
         * @returns {Boolean} - validation result.
         */
        validateEmail: function (focused) {
            var loginFormSelector = 'form[data-role=email-with-possible-login]',
                usernameSelector = loginFormSelector + ' input[name=username]',
                loginForm = $(loginFormSelector),
                validator,
                valid;

            loginForm.validation();

            if (focused === false && !!this.email()) {
                valid = !!$(usernameSelector).valid();

                if (valid) {
                    $(usernameSelector).removeAttr('aria-invalid aria-describedby');
                }

                return valid;
            }

            if (loginForm.is(':visible')) {
                validator = loginForm.validate();

                return validator.check(usernameSelector);
            }

            return true;
        },

        /**
         * Log in form submitting callback.
         *
         * @param {HTMLElement} loginForm - form element.
         */
        login: function (loginForm) {
            var loginData = {},
                formDataArray = $(loginForm).serializeArray();

            formDataArray.forEach(function (entry) {
                loginData[entry.name] = entry.value;
            });

            if (this.isPasswordVisible() && $(loginForm).validation() && $(loginForm).validation('isValid')) {
                fullScreenLoader.startLoader();
                loginAction(loginData).always(function () {
                    fullScreenLoader.stopLoader();
                });
            }
        },

        /**
         * Resolves an initial state of a login form.
         *
         * @returns {Boolean} - initial visibility state.
         */
        resolveInitialPasswordVisibility: function () {
            if (checkoutData.getInputFieldEmailValue() !== '' && checkoutData.getCheckedEmailValue() !== '') {
                return true;
            }

            if (checkoutData.getInputFieldEmailValue() !== '') {
                return checkoutData.getInputFieldEmailValue() === checkoutData.getCheckedEmailValue();
            }

            return false;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/form/element/post-code', [
    'underscore',
    './abstract'
], function (_, Abstract) {
    'use strict';

    return Abstract.extend({
        defaults: {
            imports: {
                countryOptions: '${ $.parentName }.country_id:indexedOptions',
                update: '${ $.parentName }.country_id:value'
            }
        },

        /**
         * Initializes observable properties of instance
         *
         * @returns {Abstract} Chainable.
         */
        initObservable: function () {
            this._super();

            /**
             * equalityComparer function
             *
             * @returns boolean.
             */
            this.value.equalityComparer = function (oldValue, newValue) {
                return !oldValue && !newValue || oldValue === newValue;
            };

            return this;
        },

        /**
         * Method called every time country selector's value gets changed.
         * Updates all validations and requirements for certain country.
         * @param {String} value - Selected country ID.
         */
        update: function (value) {
            var isZipCodeOptional,
                option;

            if (!value) {
                return;
            }

            option = _.isObject(this.countryOptions) && this.countryOptions[value];

            if (!option) {
                return;
            }

            isZipCodeOptional = !!option['is_zipcode_optional'];

            if (isZipCodeOptional) {
                this.error(false);
            }

            this.validation['required-entry'] = !isZipCodeOptional;
            this.required(!isZipCodeOptional);
        }
    });
});

/**
 * Copyright 2020 aheadWorks. All rights reserved.\nSee LICENSE.txt for license details.
 */

define('Aheadworks_Giftcard/js/action/apply-giftcard-code', [
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Aheadworks_Giftcard/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'Aheadworks_Giftcard/js/model/payment/giftcard-messages',
    'mage/storage',
    'Magento_Checkout/js/model/totals',
    'mage/translate',
    'Magento_Checkout/js/action/get-payment-information',
    'Aheadworks_Giftcard/js/action/get-customer-giftcards',
    'Magento_Checkout/js/model/full-screen-loader'
], function (
    $,
    quote,
    urlManager,
    errorProcessor,
    messageContainer,
    storage,
    totals,
    $t,
    getPaymentInfoAction,
    getCustomerGiftcardsAction,
    fullScreenLoader
) {
    'use strict';
    return function (giftcardCode) {
        var quoteId = quote.getQuoteId(),
            url = urlManager.getApplyGiftcardUrl(giftcardCode, quoteId),
            message = $t('Your Gift Card code was successfully applied');

        fullScreenLoader.startLoader();
        return storage.put(
            url,
            {},
            false
        ).done(
            function (response) {
                if (response) {
                    var deferred = $.Deferred();

                    getCustomerGiftcardsAction();
                    totals.isLoading(true);
                    getPaymentInfoAction(deferred);
                    $.when(deferred).done(function () {
                        totals.isLoading(false);
                    });
                    messageContainer.addSuccessMessage({
                        'message': message
                    });
                    $(document).trigger('ajax:giftCardSuccess');
                }
            }
        ).fail(
            function (response) {
                totals.isLoading(false);
                $(document).trigger('ajax:giftCardFailure', {
                    message: response.responseText
                });
                errorProcessor.process(response, messageContainer);
            }
        ).always(
            function() {
                fullScreenLoader.stopLoader();
            }
        );
    };
});

define('Aheadworks_Giftcard/js/view/payment/giftcard', [
    'jquery',
    'ko',
    'uiComponent',
    'Aheadworks_Giftcard/js/model/customer/giftcard',
    'Aheadworks_Giftcard/js/action/apply-giftcard-code',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_Customer/js/model/customer',
    'Aheadworks_Giftcard/js/action/get-customer-giftcards'
], function ($, ko, Component, customerGiftcard, applyAction, quote, priceUtils, customer, getCustomerGiftcardsAction) {
    'use strict';

    var giftcardCode = ko.observable(null);

    /**
     * Add Gift Card code to quote
     *
     * @param {String} giftcardCode
     */
    function addGiftcardCode(giftcardCode) {
        applyAction(giftcardCode);
    }

    return Component.extend({
        defaults: {
            template: 'Aheadworks_Giftcard/payment/giftcard'
        },

        /**
         * Gift Card code
         */
        giftcardCode: giftcardCode,

        /**
         * {@inheritdoc}
         */
        initialize: function () {
            this._super();
            getCustomerGiftcardsAction();
        },

        /**
         * Retrieve customer Gift Card codes
         *
         * @return {boolean}
         */
        getCustomerGiftcardCodes: function() {
            return customerGiftcard.giftcardCodes();
        },

        /**
         * Is customer Gift Card codes displayed
         *
         * @return {boolean}
         */
        isCustomerGiftcardCodesDisplayed: function() {
            return customer.isLoggedIn() && this.getCustomerGiftcardCodes().length > 0;
        },

        /**
         * Is loading customer gift card codes block
         *
         * @return {boolean}
         */
        isLoadingCustomerGiftcardsBlock: function() {
            return customerGiftcard.isLoading();
        },

        /**
         * Format Gift Card price
         *
         * @returns {String}
         */
        formatPrice: function(amount) {
            return priceUtils.formatPrice(amount, quote.getPriceFormat());
        },

        /**
         * Apply Gift Card
         */
        apply: function() {
            if (this.validate()) {
                addGiftcardCode(giftcardCode());
            }
        },

        /**
         * Apply Gift Card by code
         *
         * @param {String} giftcardCode
         */
        applyByCode: function(giftcardCode) {
            addGiftcardCode(giftcardCode);
        },

        /**
         * Gift Card form validation
         *
         * @returns {Boolean}
         */
        validate: function() {
            var form = '#aw-giftcard-form';

            return $(form).validation() && $(form).validation('isValid');
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/authentication', [
    'jquery',
    'Magento_Ui/js/form/form',
    'Magento_Customer/js/action/login',
    'Magento_Customer/js/model/customer',
    'mage/validation',
    'Magento_Checkout/js/model/authentication-messages',
    'Magento_Checkout/js/model/full-screen-loader'
], function ($, Component, loginAction, customer, validation, messageContainer, fullScreenLoader) {
    'use strict';

    var checkoutConfig = window.checkoutConfig;

    return Component.extend({
        isGuestCheckoutAllowed: checkoutConfig.isGuestCheckoutAllowed,
        isCustomerLoginRequired: checkoutConfig.isCustomerLoginRequired,
        registerUrl: checkoutConfig.registerUrl,
        forgotPasswordUrl: checkoutConfig.forgotPasswordUrl,
        autocomplete: checkoutConfig.autocomplete,
        defaults: {
            template: 'Magento_Checkout/authentication'
        },

        /**
         * Is login form enabled for current customer.
         *
         * @return {Boolean}
         */
        isActive: function () {
            return !customer.isLoggedIn();
        },

        /**
         * Provide login action.
         *
         * @param {HTMLElement} loginForm
         */
        login: function (loginForm) {
            var loginData = {},
                formDataArray = $(loginForm).serializeArray();

            formDataArray.forEach(function (entry) {
                loginData[entry.name] = entry.value;
            });

            if ($(loginForm).validation() &&
                $(loginForm).validation('isValid')
            ) {
                fullScreenLoader.startLoader();
                loginAction(loginData, checkoutConfig.checkoutUrl, undefined, messageContainer).always(function () {
                    fullScreenLoader.stopLoader();
                });
            }
        }
    });
});

define('Magento_Checkout/js/view/payment-mixin', [
    'jquery',
    'underscore',
    'uiComponent',
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/step-navigator',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/model/payment/method-converter',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'mage/translate'
], function (
    $,
    _,
    Component,
    ko,
    quote,
    stepNavigator,
    paymentService,
    methodConverter,
    getPaymentInformation,
    checkoutDataResolver,
    $t
) {
    'use strict';

    var mixin = {
        isAddressAvailable: ko.computed(function () {
            return quote.billingAddress() != null;
        }),
    };

    return function (target) { // target == Result that Magento_Ui/.../columns returns.
        return target.extend(mixin); // new result that all other modules receive
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/payment', [
    'jquery',
    'underscore',
    'uiComponent',
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/step-navigator',
    'Magento_Checkout/js/model/payment-service',
    'Magento_Checkout/js/model/payment/method-converter',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'mage/translate'
], function (
    $,
    _,
    Component,
    ko,
    quote,
    stepNavigator,
    paymentService,
    methodConverter,
    getPaymentInformation,
    checkoutDataResolver,
    $t
) {
    'use strict';

    /** Set payment methods to collection */
    paymentService.setPaymentMethods(methodConverter(window.checkoutConfig.paymentMethods));

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/payment',
            activeMethod: ''
        },
        isVisible: ko.observable(quote.isVirtual()),
        quoteIsVirtual: quote.isVirtual(),
        isPaymentMethodsAvailable: ko.computed(function () {
            return paymentService.getAvailablePaymentMethods().length > 0;
        }),

        /** @inheritdoc */
        initialize: function () {
            this._super();
            checkoutDataResolver.resolvePaymentMethod();
            stepNavigator.registerStep(
                'payment',
                null,
                $t('Review & Payments'),
                this.isVisible,
                _.bind(this.navigate, this),
                this.sortOrder
            );

            return this;
        },

        /**
         * Navigate method.
         */
        navigate: function () {
            var self = this;

            if (!self.hasShippingMethod()) {
                this.isVisible(false);
                stepNavigator.setHash('shipping');
            } else {
                getPaymentInformation().done(function () {
                    self.isVisible(true);
                });
            }
        },

        /**
         * @return {Boolean}
         */
        hasShippingMethod: function () {
            return window.checkoutConfig.selectedShippingMethod !== null;
        },

        /**
         * @return {*}
         */
        getFormKey: function () {
            return window.checkoutConfig.formKey;
        }
    });
});

define('text!Magento_Checkout/template/onepage.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n\n<div class="checkout-messages">\n    <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n</div>\n\n<!-- ko ifnot: isCustomerLoggedIn() -->\n<div class="checkout-login">\n    <div class="checkout-login-inner">\n        <div class="checkout-login_top-title">\n            <span class="checkout-login_top-title_desktop" data-bind=\'i18n:"Log in"\'></span>\n            <span class="checkout-login_top-title_mobile" data-bind=\'i18n:"Choose Your Log in"\'></span>\n        </div>\n\n        <div class="checkout-login-inner_scroll">\n            <div class="row">\n                <div class="col col-12 col-m-4 order-3 order-m-1">\n                    <!-- ko foreach: getRegion(\'authentication\') -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                    <!--/ko-->\n                </div>\n                <div class="col col-12 col-m-4 order-1 order-m-2">\n                    <!-- Login Form Goes Here -->\n\n                    <!-- ko foreach: getRegion(\'messages\') -->\n                        <!-- ko template: getTemplate() --><!-- /ko -->\n                    <!--/ko-->\n\n                    <!-- ko foreach: getRegion(\'customerLogin\') -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                    <!--/ko-->\n                </div>\n                <div class="col col-12 col-m-4 order-2 order-m-3">\n                    <!-- Register / Continue -->\n                    <div class="checkout-login_title"><span data-bind="i18n: \'Don\\\'t Have an account?\'"></span></div>\n                    <p>\n                        <a class="button green" data-bind=\'i18n: "Create an account", attr: { "href": window.checkoutConfig.registerUrl}\'></a>\n                    </p>\n                    <div class="checkout-login_text"><span class="text-upper" data-bind=\'i18n: "Or..."\'></span></div>\n                    <p>\n                        <button class="button green" type="button" data-bind=\'mageInit: { "guestCheckout": {}, "toggle": { "target": "body", "class": "__checkout-as-guest" } }\'><span data-bind=\'i18n: "Continue as guest"\'></span></button>\n                        <br>\n                        <span class="checkout-login_note" data-bind=\'i18n: "NOTE: You can only earn loyalty points (CDKoins) when you create an account or login"\'></span>\n                    </p>\n                </div>\n            </div> <!-- .row -->\n        </div> <!-- .checkout-login-inner_scroll -->\n    </div>\n</div>\n<!--/ko-->\n\n<div class="checkout-column checkout-column_first">\n    <div class="checkout-column_title">\n        <span data-bind=\'i18n: "Billing Information"\'></span>\n    </div>\n\n    <!-- ko foreach: getRegion(\'customerEmail\') -->\n    <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n\n    <!-- ko foreach: getRegion(\'billingAddress\') -->\n    <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n</div>\n\n<div class="checkout-column checkout-column_second">\n\n    <!-- ko foreach: getRegion(\'steps\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n\n    <!-- ko foreach: getRegion(\'sidebar\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n</div>\n';
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Ui/js/view/messages', [
    'ko',
    'jquery',
    'uiComponent',
    '../model/messageList',
    'jquery-ui-modules/effect-blind'
], function (ko, $, Component, globalMessages) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Ui/messages',
            selector: '[data-role=checkout-messages]',
            isHidden: false,
            hideTimeout: 5000,
            hideSpeed: 500,
            listens: {
                isHidden: 'onHiddenChange'
            }
        },

        /** @inheritdoc */
        initialize: function (config, messageContainer) {
            this._super()
                .initObservable();

            this.messageContainer = messageContainer || config.messageContainer || globalMessages;

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe('isHidden');

            return this;
        },

        /**
         * Checks visibility.
         *
         * @return {Boolean}
         */
        isVisible: function () {
            return this.isHidden(this.messageContainer.hasMessages());
        },

        /**
         * Remove all messages.
         */
        removeAll: function () {
            this.messageContainer.clear();
        },

        /**
         * @param {Boolean} isHidden
         */
        onHiddenChange: function (isHidden) {
            // Hide message block if needed
            if (isHidden) {
                setTimeout(function () {
                    $(this.selector).hide('blind', {}, this.hideSpeed);
                }.bind(this), this.hideTimeout);
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/authentication-messages', [
    'Magento_Ui/js/view/messages',
    'Magento_Checkout/js/model/authentication-messages'
], function (Component, messageContainer) {
    'use strict';

    return Component.extend({
        /** @inheritdoc */
        initialize: function (config) {
            return this._super(config, messageContainer);
        }
    });
});

define('Aheadworks_Giftcard/js/view/payment/giftcard-messages', [
    'Magento_Ui/js/view/messages',
    '../../model/payment/giftcard-messages'
], function (Component, messageContainer) {
    'use strict';
    return Component.extend({
        /**
         * Initialize component
         * 
         * @return {Object}
         */
        initialize: function (config) {
            return this._super(config, messageContainer);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/view/payment/discount-messages', [
    'Magento_Ui/js/view/messages',
    '../../model/payment/discount-messages'
], function (Component, messageContainer) {
    'use strict';

    return Component.extend({
        /** @inheritdoc */
        initialize: function (config) {
            return this._super(config, messageContainer);
        }
    });
});

define('Aheadworks_Giftcard/js/view/payment/total-messages', [
    'Magento_Ui/js/view/messages',
    'Aheadworks_Giftcard/js/model/payment/total-messages'
], function(Component, messageContainer) {
    'use strict';
    return Component.extend({
        defaults: {
            selector: '.opc-block-summary [data-role=checkout-messages]'
        },

        /**
         * Initialize component
         *
         * @return {Object}
         */
        initialize: function(config) {
            return this._super(config, messageContainer);
        },

        /**
         * @param {Boolean} isHidden
         */
        onHiddenChange: function(isHidden) {
            // Hide message block if needed
            if (isHidden) {
                setTimeout(
                    function() {
                        const el = document.querySelector(this.selector);

                        if (el) {
                            el.style.display = 'none';
                        }
                    }.bind(this),
                    this.hideTimeout
                );
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/recollect-shipping-rates', [
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/select-shipping-address',
    'Magento_Checkout/js/model/shipping-rate-registry'
], function (quote, selectShippingAddress, rateRegistry) {
    'use strict';

    return function () {
        var shippingAddress = null;

        if (!quote.isVirtual()) {
            shippingAddress = quote.shippingAddress();

            rateRegistry.set(shippingAddress.getCacheKey(), null);
            selectShippingAddress(shippingAddress);
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Customer store credit(balance) application
 */
define('Magento_SalesRule/js/action/cancel-coupon', [
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'Magento_SalesRule/js/model/payment/discount-messages',
    'mage/storage',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals',
    'mage/translate',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/action/recollect-shipping-rates'
], function ($, quote, urlManager, errorProcessor, messageContainer, storage, getPaymentInformationAction, totals, $t,
  fullScreenLoader, recollectShippingRates
) {
    'use strict';

    var successCallbacks = [],
        action,
        callSuccessCallbacks;

    /**
     * Execute callbacks when a coupon is successfully canceled.
     */
    callSuccessCallbacks = function () {
        successCallbacks.forEach(function (callback) {
            callback();
        });
    };

    /**
     * Cancel applied coupon.
     *
     * @param {Boolean} isApplied
     * @returns {Deferred}
     */
    action =  function (isApplied) {
        var quoteId = quote.getQuoteId(),
            url = urlManager.getCancelCouponUrl(quoteId),
            message = $t('Your coupon was successfully removed.');

        messageContainer.clear();
        fullScreenLoader.startLoader();

        return storage.delete(
            url,
            false
        ).done(function () {
            var deferred = $.Deferred();

            totals.isLoading(true);
            recollectShippingRates();
            getPaymentInformationAction(deferred);
            $.when(deferred).done(function () {
                isApplied(false);
                totals.isLoading(false);
                fullScreenLoader.stopLoader();
                //Allowing to tap into coupon-cancel process.
                callSuccessCallbacks();
            });
            messageContainer.addSuccessMessage({
                'message': message
            });
        }).fail(function (response) {
            totals.isLoading(false);
            fullScreenLoader.stopLoader();
            errorProcessor.process(response, messageContainer);
        });
    };

    /**
     * Callback for when the cancel-coupon process is finished.
     *
     * @param {Function} callback
     */
    action.registerSuccessCallback = function (callback) {
        successCallbacks.push(callback);
    };

    return action;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/**
 * Customer store credit(balance) application
 */
define('Magento_SalesRule/js/action/set-coupon-code', [
    'ko',
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/resource-url-manager',
    'Magento_Checkout/js/model/error-processor',
    'Magento_SalesRule/js/model/payment/discount-messages',
    'mage/storage',
    'mage/translate',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/action/recollect-shipping-rates'
], function (ko, $, quote, urlManager, errorProcessor, messageContainer, storage, $t, getPaymentInformationAction,
             totals, fullScreenLoader, recollectShippingRates
) {
    'use strict';

    var dataModifiers = [],
        successCallbacks = [],
        failCallbacks = [],
        action;

    /**
     * Apply provided coupon.
     *
     * @param {String} couponCode
     * @param {Boolean}isApplied
     * @returns {Deferred}
     */
    action = function (couponCode, isApplied) {
        var quoteId = quote.getQuoteId(),
            url = urlManager.getApplyCouponUrl(couponCode, quoteId),
            message = $t('Your coupon was successfully applied.'),
            data = {},
            headers = {};

        //Allowing to modify coupon-apply request
        dataModifiers.forEach(function (modifier) {
            modifier(headers, data);
        });
        fullScreenLoader.startLoader();

        return storage.put(
            url,
            data,
            false,
            null,
            headers
        ).done(function (response) {
            var deferred;

            if (response) {
                deferred = $.Deferred();

                isApplied(true);
                totals.isLoading(true);
                recollectShippingRates();
                getPaymentInformationAction(deferred);
                $.when(deferred).done(function () {
                    fullScreenLoader.stopLoader();
                    totals.isLoading(false);
                });
                messageContainer.addSuccessMessage({
                    'message': message
                });
                //Allowing to tap into apply-coupon process.
                successCallbacks.forEach(function (callback) {
                    $(document).trigger('ajax:couponSuccess');
                    callback(response);
                });
            }
        }).fail(function (response) {
            fullScreenLoader.stopLoader();
            totals.isLoading(false);
            errorProcessor.process(response, messageContainer);
            //Allowing to tap into apply-coupon process.
            failCallbacks.forEach(function (callback) {
                $(document).trigger('ajax:couponFailure', {
                    message: response.responseText
                });
                callback(response);
            });
        });
    };

    /**
     * Modifying data to be sent.
     *
     * @param {Function} modifier
     */
    action.registerDataModifier = function (modifier) {
        dataModifiers.push(modifier);
    };

    /**
     * When successfully added a coupon.
     *
     * @param {Function} callback
     */
    action.registerSuccessCallback = function (callback) {
        successCallbacks.push(callback);
    };

    /**
     * When failed to add a coupon.
     *
     * @param {Function} callback
     */
    action.registerFailCallback = function (callback) {
        failCallbacks.push(callback);
    };

    return action;
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/view/payment/discount', [
    'jquery',
    'ko',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_SalesRule/js/action/set-coupon-code',
    'Magento_SalesRule/js/action/cancel-coupon',
    'Magento_SalesRule/js/model/coupon'
], function($, ko, Component, quote, setCouponCodeAction, cancelCouponAction, coupon) {
    'use strict';

    var totals = quote.getTotals(),
        couponCode = coupon.getCouponCode(),
        isApplied = coupon.getIsApplied();

    if (totals()) {
        couponCode(totals()['coupon_code']);
    }

    isApplied(couponCode() != null);

    const checkoutConfig = window.checkoutConfig;

    return Component.extend({
        defaults: {
            template: 'Magento_SalesRule/payment/discount'
        },
        couponCode: couponCode,
        isVisible: false,

        /** @inheritdoc */
        initialize: function() {
            this._super();

            let hasGiftCard = false;

            checkoutConfig.quoteItemData.forEach(item => {
                if (item.product_type === 'aw_giftcard') {
                    hasGiftCard = true;
                }
            });

            if (!hasGiftCard) {
                this.isVisible = true;
            } else if (hasGiftCard && isApplied()) {
                couponCode('');
                cancelCouponAction(isApplied);
            }
        },

        /**
         * Applied flag
         */
        isApplied: isApplied,

        /**
         * Coupon code application procedure
         */
        apply: function() {
            if (this.validate()) {
                setCouponCodeAction(couponCode(), isApplied);
            }
        },

        /**
         * Cancel using coupon
         */
        cancel: function() {
            if (this.validate()) {
                couponCode('');
                cancelCouponAction(isApplied);
            }
        },

        /**
         * Coupon form validation
         *
         * @returns {Boolean}
         */
        validate: function() {
            var form = '#discount-form';

            return $(form).validation() && $(form).validation('isValid');
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_PaypalCaptcha/js/model/skipRefreshCaptcha', ['ko'], function (ko) {
    'use strict';

    return {
        skip: ko.observable(false)
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_PaypalCaptcha/js/view/checkout/defaultCaptcha-mixin', [
    'Magento_PaypalCaptcha/js/model/skipRefreshCaptcha'
], function (skipRefreshCaptcha) {
    'use strict';

    var defaultCaptchaMixin = {
        /**
         * @override
         */
        refresh: function () {
            if (!skipRefreshCaptcha.skip()) {
                this._super();
            } else {
                skipRefreshCaptcha.skip(false);
            }
        }
    };

    return function (defaultCaptcha) {
        return defaultCaptcha.extend(defaultCaptchaMixin);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Captcha/js/action/refresh', [
    'jquery', 'mage/url'
], function ($, urlBuilder) {
    'use strict';

    return function (refreshUrl, formId, imageSource) {
        return $.ajax({
            url: urlBuilder.build(refreshUrl),
            type: 'POST',
            data: JSON.stringify({
                'formId': formId
            }),
            global: false,
            contentType: 'application/json'
        }).done(
            function (response) {
                if (response.imgSrc) {
                    imageSource(response.imgSrc);
                }
            }
        );
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Captcha/js/model/captcha', [
    'jquery',
    'ko',
    'Magento_Captcha/js/action/refresh'
], function ($, ko, refreshAction) {
    'use strict';

    return function (captchaData) {
        return {
            formId: captchaData.formId,
            imageSource: ko.observable(captchaData.imageSrc),
            visibility: ko.observable(false),
            captchaValue: ko.observable(null),
            isRequired: ko.observable(captchaData.isRequired),
            isCaseSensitive: captchaData.isCaseSensitive,
            imageHeight: captchaData.imageHeight,
            refreshUrl: captchaData.refreshUrl,
            isLoading: ko.observable(false),
            timestamp: null,

            /**
             * @return {String}
             */
            getFormId: function () {
                return this.formId;
            },

            /**
             * @param {String} formId
             */
            setFormId: function (formId) {
                this.formId = formId;
            },

            /**
             * @return {Boolean}
             */
            getIsVisible: function () {
                return this.visibility();
            },

            /**
             * @param {Boolean} flag
             */
            setIsVisible: function (flag) {
                this.visibility(flag);
            },

            /**
             * @return {Boolean}
             */
            getIsRequired: function () {
                return this.isRequired();
            },

            /**
             * @param {Boolean} flag
             */
            setIsRequired: function (flag) {
                this.isRequired(flag);
            },

            /**
             * @return {Boolean}
             */
            getIsCaseSensitive: function () {
                return this.isCaseSensitive;
            },

            /**
             * @param {Boolean} flag
             */
            setIsCaseSensitive: function (flag) {
                this.isCaseSensitive = flag;
            },

            /**
             * @return {String|Number}
             */
            getImageHeight: function () {
                return this.imageHeight;
            },

            /**
             * @param {String|Number}height
             */
            setImageHeight: function (height) {
                this.imageHeight = height;
            },

            /**
             * @return {String}
             */
            getImageSource: function () {
                return this.imageSource;
            },

            /**
             * @param {String} imageSource
             */
            setImageSource: function (imageSource) {
                this.imageSource(imageSource);
            },

            /**
             * @return {String}
             */
            getRefreshUrl: function () {
                return this.refreshUrl;
            },

            /**
             * @param {String} url
             */
            setRefreshUrl: function (url) {
                this.refreshUrl = url;
            },

            /**
             * @return {*}
             */
            getCaptchaValue: function () {
                return this.captchaValue;
            },

            /**
             * @param {*} value
             */
            setCaptchaValue: function (value) {
                this.captchaValue(value);
            },

            /**
             * Refresh captcha.
             */
            refresh: function () {
                var refresh,
                    self = this;

                this.isLoading(true);

                refresh = refreshAction(this.getRefreshUrl(), this.getFormId(), this.getImageSource());
                $.when(refresh).done(function () {
                    self.isLoading(false);
                });
            }
        };
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Captcha/js/view/checkout/defaultCaptcha', [
    'jquery',
    'uiComponent',
    'Magento_Captcha/js/model/captcha',
    'Magento_Captcha/js/model/captchaList',
    'Magento_Customer/js/customer-data',
    'underscore'
], function ($, Component, Captcha, captchaList, customerData, _) {
    'use strict';

    var captchaConfig;

    return Component.extend({
        defaults: {
            template: 'Magento_Captcha/checkout/captcha'
        },
        dataScope: 'global',
        currentCaptcha: null,
        subscribedFormIds: [],

        /**
         * @return {*}
         */
        captchaValue: function () {
            return this.currentCaptcha.getCaptchaValue();
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            if (window[this.configSource] && window[this.configSource].captcha) {
                captchaConfig = window[this.configSource].captcha;
                $.each(captchaConfig, function (formId, captchaData) {
                    var captcha;

                    captchaData.formId = formId;
                    captcha = Captcha(captchaData);
                    this.checkCustomerData(formId, customerData.get('captcha')(), captcha);
                    this.subscribeCustomerData(formId, captcha);
                    captchaList.add(captcha);
                }.bind(this));
            }
        },

        /**
         * Check customer data for captcha configuration.
         *
         * @param {String} formId
         * @param {Object} captchaData
         * @param {Object} captcha
         */
        checkCustomerData: function (formId, captchaData, captcha) {
            if (!_.isEmpty(captchaData) &&
                !_.isEmpty(captchaData[formId]) &&
                captchaData[formId].timestamp > captcha.timestamp
            ) {
                if (!captcha.isRequired() && captchaData[formId].isRequired) {
                    captcha.refresh();
                }
                captcha.isRequired(captchaData[formId].isRequired);
                captcha.timestamp = captchaData[formId].timestamp;
            }
        },

        /**
         * Subscribe for customer data updates.
         *
         * @param {String} formId
         * @param {Object} captcha
         */
        subscribeCustomerData: function (formId, captcha) {
            if (this.subscribedFormIds.includes(formId) === false) {
                this.subscribedFormIds.push(formId);
                customerData.get('captcha').subscribe(function (captchaData) {
                    this.checkCustomerData(formId, captchaData, captcha);
                }.bind(this));
            }
        },

        /**
         * @return {Boolean}
         */
        getIsLoading: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.isLoading : false;
        },

        /**
         * @return {null|Object}
         */
        getCurrentCaptcha: function () {
            return this.currentCaptcha;
        },

        /**
         * @param {Object} captcha
         */
        setCurrentCaptcha: function (captcha) {
            this.currentCaptcha = captcha;
        },

        /**
         * @return {String|null}
         */
        getFormId: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getFormId() : null;
        },

        /**
         * @return {Boolean}
         */
        getIsVisible: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getIsVisible() : false;
        },

        /**
         * @param {Boolean} flag
         */
        setIsVisible: function (flag) {
            this.currentCaptcha.setIsVisible(flag);
        },

        /**
         * @return {Boolean}
         */
        isRequired: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getIsRequired() : false;
        },

        /**
         * Set isRequired on current captcha model.
         *
         * @param {Boolean} flag
         */
        setIsRequired: function (flag) {
            this.currentCaptcha.setIsRequired(flag);
        },

        /**
         * @return {Boolean}
         */
        isCaseSensitive: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getIsCaseSensitive() : false;
        },

        /**
         * @return {String|Number|null}
         */
        imageHeight: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getImageHeight() : null;
        },

        /**
         * @return {String|null}
         */
        getImageSource: function () {
            return this.currentCaptcha !== null ? this.currentCaptcha.getImageSource() : null;
        },

        /**
         * Refresh captcha.
         */
        refresh: function () {
            this.currentCaptcha.refresh();
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Captcha/js/view/checkout/loginCaptcha', [
    'Magento_Captcha/js/view/checkout/defaultCaptcha',
    'Magento_Captcha/js/model/captchaList',
    'Magento_Customer/js/action/login',
    'underscore'
],
function (defaultCaptcha, captchaList, loginAction, _) {
    'use strict';

    return defaultCaptcha.extend({
        /** @inheritdoc */
        initialize: function () {
            var self = this,
                currentCaptcha;

            this._super();
            currentCaptcha = captchaList.getCaptchaByFormId(this.formId);

            if (currentCaptcha != null) {
                currentCaptcha.setIsVisible(true);
                this.setCurrentCaptcha(currentCaptcha);

                loginAction.registerLoginCallback(function (loginData) {
                    if (loginData['captcha_form_id'] &&
                        loginData['captcha_form_id'] === self.formId &&
                        self.isRequired()
                    ) {
                        _.defer(self.refresh.bind(self));
                    }
                });
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/checkout/placeOrderCaptcha', [
    'Magento_Captcha/js/view/checkout/defaultCaptcha',
    'Magento_Captcha/js/model/captchaList',
    'underscore',
    'Magento_Checkout/js/model/payment/place-order-hooks'
],
function (defaultCaptcha, captchaList, _, placeOrderHooks) {
    'use strict';

    return defaultCaptcha.extend({
        /** @inheritdoc */
        initialize: function () {
            var self = this,
                currentCaptcha;

            this._super();
            currentCaptcha = captchaList.getCaptchaByFormId(this.formId);

            if (currentCaptcha != null) {
                currentCaptcha.setIsVisible(true);
                this.setCurrentCaptcha(currentCaptcha);
                placeOrderHooks.requestModifiers.push(function (headers) {
                    if (self.isRequired()) {
                        headers['X-Captcha'] = self.captchaValue()();
                    }
                });
                placeOrderHooks.afterRequestListeners.push(function () {
                    self.refresh();
                });
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_PaypalCaptcha/js/view/checkout/paymentCaptcha', [
    'jquery',
    'Magento_Captcha/js/view/checkout/defaultCaptcha',
    'Magento_Captcha/js/model/captchaList',
    'Magento_Captcha/js/model/captcha'
],
function ($, defaultCaptcha, captchaList, Captcha) {
    'use strict';

    return defaultCaptcha.extend({

        /** @inheritdoc */
        initialize: function () {
            var captchaConfigPayment,
                currentCaptcha;

            this._super();

            if (window[this.configSource] && window[this.configSource].captchaPayments) {
                captchaConfigPayment = window[this.configSource].captchaPayments;

                $.each(captchaConfigPayment, function (formId, captchaData) {
                    var captcha;

                    captchaData.formId = formId;
                    captcha = Captcha(captchaData);
                    captchaList.add(captcha);
                });
            }

            currentCaptcha = captchaList.getCaptchaByFormId(this.formId);

            if (currentCaptcha != null) {
                currentCaptcha.setIsVisible(true);
                this.setCurrentCaptcha(currentCaptcha);
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_SalesRule/js/view/payment/captcha', [
        'Magento_Captcha/js/view/checkout/defaultCaptcha',
        'Magento_Captcha/js/model/captchaList',
        'Magento_SalesRule/js/action/set-coupon-code',
        'Magento_SalesRule/js/action/cancel-coupon',
        'Magento_Checkout/js/model/quote',
        'ko'
    ],
    function (defaultCaptcha, captchaList, setCouponCodeAction, cancelCouponAction, quote, ko) {
        'use strict';

        var totals = quote.getTotals(),
            couponCode = ko.observable(null),
            isApplied;

        if (totals()) {
            couponCode(totals()['coupon_code']);
        }
        //Captcha can only be required for adding a coupon so we need to know if one was added already.
        isApplied = ko.observable(couponCode() != null);

        return defaultCaptcha.extend({
            /** @inheritdoc */
            initialize: function () {
                var self = this,
                    currentCaptcha;

                this._super();
                //Getting coupon captcha model.
                currentCaptcha = captchaList.getCaptchaByFormId(this.formId);

                if (currentCaptcha != null) {
                    if (!isApplied()) {
                        //Show captcha if we don't have a coupon applied.
                        currentCaptcha.setIsVisible(true);
                    }
                    this.setCurrentCaptcha(currentCaptcha);
                    //Add captcha code to coupon-apply request.
                    setCouponCodeAction.registerDataModifier(function (headers) {
                        if (self.isRequired()) {
                            headers['X-Captcha'] = self.captchaValue()();
                        }
                    });
                    //Refresh captcha after failed request.
                    setCouponCodeAction.registerFailCallback(function () {
                        if (self.isRequired()) {
                            self.refresh();
                        }
                    });
                    //Hide captcha when a coupon has been applied.
                    setCouponCodeAction.registerSuccessCallback(function () {
                        self.setIsVisible(false);
                    });
                    //Show captcha again if it was canceled.
                    cancelCouponAction.registerSuccessCallback(function () {
                        if (self.isRequired()) {
                            self.setIsVisible(true);
                        }
                    });
                }
            }
        });
    });

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/payment/list', [
    'underscore',
    'ko',
    'mageUtils',
    'uiComponent',
    'Magento_Checkout/js/model/payment/method-list',
    'Magento_Checkout/js/model/payment/renderer-list',
    'uiLayout',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'mage/translate',
    'uiRegistry'
], function (_, ko, utils, Component, paymentMethods, rendererList, layout, checkoutDataResolver, $t, registry) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/payment-methods/list',
            visible: paymentMethods().length > 0,
            configDefaultGroup: {
                name: 'methodGroup',
                component: 'Magento_Checkout/js/model/payment/method-group'
            },
            paymentGroupsList: [],
            defaultGroupTitle: $t('Select a new payment method')
        },

        /**
         * Initialize view.
         *
         * @returns {Component} Chainable.
         */
        initialize: function () {
            this._super().initDefaulGroup().initChildren();
            paymentMethods.subscribe(
                function (changes) {
                    checkoutDataResolver.resolvePaymentMethod();
                    //remove renderer for "deleted" payment methods
                    _.each(changes, function (change) {
                        if (change.status === 'deleted') {
                            this.removeRenderer(change.value.method);
                        }
                    }, this);
                    //add renderer for "added" payment methods
                    _.each(changes, function (change) {
                        if (change.status === 'added') {
                            this.createRenderer(change.value);
                        }
                    }, this);
                }, this, 'arrayChange');

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().
                observe(['paymentGroupsList']);

            return this;
        },

        /**
         * Creates default group
         *
         * @returns {Component} Chainable.
         */
        initDefaulGroup: function () {
            layout([
                this.configDefaultGroup
            ]);

            return this;
        },

        /**
         * Create renders for child payment methods.
         *
         * @returns {Component} Chainable.
         */
        initChildren: function () {
            var self = this;

            _.each(paymentMethods(), function (paymentMethodData) {
                self.createRenderer(paymentMethodData);
            });

            return this;
        },

        /**
         * @returns
         */
        createComponent: function (payment) {
            var rendererTemplate,
                rendererComponent,
                templateData;

            templateData = {
                parentName: this.name,
                name: payment.name
            };
            rendererTemplate = {
                parent: '${ $.$data.parentName }',
                name: '${ $.$data.name }',
                displayArea: payment.displayArea,
                component: payment.component
            };
            rendererComponent = utils.template(rendererTemplate, templateData);
            utils.extend(rendererComponent, {
                item: payment.item,
                config: payment.config
            });

            return rendererComponent;
        },

        /**
         * Create renderer.
         *
         * @param {Object} paymentMethodData
         */
        createRenderer: function (paymentMethodData) {
            var isRendererForMethod = false,
                currentGroup;

            registry.get(this.configDefaultGroup.name, function (defaultGroup) {
                _.each(rendererList(), function (renderer) {

                    if (renderer.hasOwnProperty('typeComparatorCallback') &&
                        typeof renderer.typeComparatorCallback == 'function'
                    ) {
                        isRendererForMethod = renderer.typeComparatorCallback(renderer.type, paymentMethodData.method);
                    } else {
                        isRendererForMethod = renderer.type === paymentMethodData.method;
                    }

                    if (isRendererForMethod) {
                        currentGroup = renderer.group ? renderer.group : defaultGroup;

                        this.collectPaymentGroups(currentGroup);

                        layout([
                            this.createComponent(
                                {
                                    config: renderer.config,
                                    component: renderer.component,
                                    name: renderer.type,
                                    method: paymentMethodData.method,
                                    item: paymentMethodData,
                                    displayArea: currentGroup.displayArea
                                }
                            )]);
                    }
                }.bind(this));
            }.bind(this));
        },

        /**
         * Collects unique groups of available payment methods
         *
         * @param {Object} group
         */
        collectPaymentGroups: function (group) {
            var groupsList = this.paymentGroupsList(),
                isGroupExists = _.some(groupsList, function (existsGroup) {
                    return existsGroup.alias === group.alias;
                });

            if (!isGroupExists) {
                groupsList.push(group);
                groupsList = _.sortBy(groupsList, function (existsGroup) {
                    return existsGroup.sortOrder;
                });
                this.paymentGroupsList(groupsList);
            }
        },

        /**
         * Returns payment group title
         *
         * @param {Object} group
         * @returns {String}
         */
        getGroupTitle: function (group) {
            var title = group().title;

            if (group().isDefault() && this.paymentGroupsList().length > 1) {
                title = this.defaultGroupTitle;
            }

            return title;
        },

        /**
         * Checks if at least one payment method available
         *
         * @returns {String}
         */
        isPaymentMethodsAvailable: function () {
            return _.some(this.paymentGroupsList(), function (group) {
                return this.regionHasElements(group.displayArea);
            }, this);
        },

        /**
         * Remove view renderer.
         *
         * @param {String} paymentMethodCode
         */
        removeRenderer: function (paymentMethodCode) {
            var items;

            _.each(this.paymentGroupsList(), function (group) {
                items = this.getRegion(group.displayArea);

                _.find(items(), function (value) {
                    if (value.item.method.indexOf(paymentMethodCode) === 0) {
                        value.disposeSubscriptions();
                        value.destroy();
                    }
                });
            }, this);
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_PaypalCaptcha/js/view/payment/list-mixin', [
    'jquery',
    'Magento_Captcha/js/model/captchaList'
], function ($, captchaList) {
    'use strict';

    var mixin = {

        formId: 'co-payment-form',

        /**
         * Sets custom template for Payflow Pro
         *
         * @param {Object} payment
         * @returns {Object}
         */
        createComponent: function (payment) {

            var component = this._super(payment);

            if (component.component === 'Magento_Paypal/js/view/payment/method-renderer/payflowpro-method') {
                component.template = 'Magento_PaypalCaptcha/payment/payflowpro-form';
                $(window).off('clearTimeout')
                    .on('clearTimeout', this.clearTimeout.bind(this));
            }

            return component;
        },

        /**
         * Overrides default window.clearTimeout() to catch errors from iframe and reload Captcha.
         *
         * @param {Number} timeoutID
         */
        clearTimeout: function (timeoutID) {
            var captcha = captchaList.getCaptchaByFormId(this.formId);

            if (captcha !== null) {
                captcha.refresh();
            }
            clearTimeout(timeoutID);
        }
    };

    /**
     * Overrides `Magento_Checkout/js/view/payment/list::createComponent`
     */
    return function (target) {
        return target.extend(mixin);
    };
});

define('Magento_Checkout/js/view/billing-address-mixin', [
        'ko',
        'underscore',
        'Magento_Ui/js/form/form',
        'Magento_Customer/js/model/customer',
        'Magento_Customer/js/model/address-list',
        'Magento_Checkout/js/model/quote'
    ],
    function (
        ko,
        _,
        Component,
        customer,
        addressList,
        quote
    ) {
        'use strict';

    var addressUpadated = false;

    var mixin = {
        /**
         * Cancel address edit action
         */
        cancelAddressEdit: function () {
            addressUpadated = true;
            this.restoreBillingAddress();

            if (!quote.isVirtual() && quote.billingAddress()) {
                // restore 'Same As Shipping' checkbox state
                this.isAddressSameAsShipping(
                    quote.billingAddress() != null &&
                    quote.billingAddress().getCacheKey() == quote.shippingAddress().getCacheKey() && //eslint-disable-line
                    !quote.isVirtual()
                );
                this.isAddressDetailsVisible(true);
            }
        },
    };

    return function (target) {
        return target.extend(mixin);
    };
});

define('text!Magento_Checkout/template/authentication.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="authentication-wrapper" data-block="authentication" data-bind="visible: isActive(), css: { __authshow: isActive() }">\n    <button\n        type="button"\n        class="action action-auth-toggle"\n        data-trigger="authentication">\n        <span data-bind="i18n: \'Sign In\'"></span>\n    </button>\n    <div class="block-authentication">\n        <!-- ko foreach: getRegion(\'before\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!-- /ko -->\n        <div class="block block-customer-login">\n            <div id="block-customer-login-heading"\n                role="heading"\n                aria-level="2"\n                class="checkout-login_title"\n                data-bind="i18n: \'Sign in using the platforms below\'"></div>\n\n            <!-- ko foreach: getRegion(\'messages\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n\n            <div class="block-content" aria-labelledby="block-customer-login-heading">\n                <form data-role="login"\n                      data-bind="submit:login"\n                      method="post">\n                    <div class="fieldset"\n                              data-bind="attr: {\'data-hasrequired\': $t(\'* Required Fields\')}">\n                        <div class="field field-email required">\n                            <label class="label" for="login-email"><span data-bind="i18n: \'Email Address\'"></span></label>\n                            <div class="control">\n                                <input type="email"\n                                       class="input-text"\n                                       id="login-email"\n                                       name="username"\n                                       data-bind="attr: {autocomplete: autocomplete}"\n                                       data-validate="{required:true, \'validate-email\':true}" />\n                            </div>\n                        </div>\n                        <div class="field field-password required">\n                            <label for="login-password" class="label"><span data-bind="i18n: \'Password\'"></span></label>\n                            <div class="control">\n                                <input type="password"\n                                       class="input-text"\n                                       id="login-password"\n                                       name="password"\n                                       data-bind="attr: {autocomplete: autocomplete}"\n                                       data-validate="{required:true}"\n                                       autocomplete="off"/>\n                            </div>\n                        </div>\n                        <!-- ko foreach: getRegion(\'additional-login-form-fields\') -->\n                        <!-- ko template: getTemplate() --><!-- /ko -->\n                        <!-- /ko -->\n                    </div>\n                    <div class="actions-toolbar">\n                        <input name="context" type="hidden" value="checkout" />\n                        <div class="primary">\n                            <button type="submit" class="action action-login secondary"><span data-bind="i18n: \'Sign In\'"></span></button>\n                        </div>\n                        <div class="secondary">\n                            <a class="action action-remind" data-bind="attr: { href: forgotPasswordUrl }">\n                                <span data-bind="i18n: \'Forgot Your Password?\'"></span>\n                            </a>\n                        </div>\n                    </div>\n                </form>\n            </div>\n        </div>\n    </div>\n</div>\n';
});
define('text!MediaLounge_FraudAccounts/template/device-registration.html', function() {
    return '<!-- ko ifnot: isDeviceRegistered() -->\n   <div class="form">\n        <div class="checkout-login_title">\n           <span data-bind="i18n: \'Verification Code\'"></span>\n        </div>\n        <form class="form form-login form-verify"\n              action="/customer/account/deviceAjax"\n              method="post"\n              id="login-form"\n              data-bind=\'mageInit: {"validation":{}, "fraudAccounts":{ "ajax": true }}\'>\n            <div class="field verification-code">\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="0" data-validate="{required:true}" />\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="1" data-validate="{required:true}" />\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="2" data-validate="{required:true}" />\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="3" data-validate="{required:true}" />\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="4" data-validate="{required:true}" />\n                <input name="verify_code[]" type="number" min="0" max="9" minlength="1" maxlength="1" placeholder="5" data-validate="{required:true}" />\n            </div>\n            <div id="custom-error-message-container" class="errors"></div>\n            <div class="actions-toolbar">\n                <div class="primary">\n                    <button type="submit" class="button green" name="send" id="send">\n                        <span data-bind="i18n: \'Verify Device\'"></span>\n                    </button>\n                </div>\n\n                <div class="secondary">\n                    <button class="button purple outline s" data-bind="click: cancelDeviceRegistration">\n                        <span data-bind="i18n: \'Cancel\'"></span>\n                    </button>\n                </div>\n            </div>\n        </form>\n   </div>\n<!--/ko-->\n';
});
define('text!Magento_Checkout/template/form/element/login.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<form class="form form-email form-login"\n      data-bind="\n        submit: login,\n        mageInit: { \'labels\': {} }\n    "\n      method="post">\n    <div class="checkout-login_title"><span data-bind=\'i18n: "Sign in to your account"\'></span></div>\n    <div id="customer-email-fieldset" class="fieldset" data-bind="blockLoader: isLoading">\n        <div class="legend"><span data-bind="i18n: \'Enter your email\'"></span></div>\n        <div class="field required">\n            <label class="label" for="customer-email">\n                <span data-bind="i18n: \'Email Address\'"></span>\n            </label>\n            <div class="control">\n                <input\n                    class="input-text"\n                    type="email"\n                    data-bind="\n                        hasFocus: emailFocused,\n                        mageInit: {\'mage/trim-input\':{}}"\n                    name="username"\n                    data-validate="{ required: true, \'validate-email\': true }"\n                    id="checkout-login-email" />\n            </div>\n        </div>\n\n        <div class="fieldset">\n            <div class="field">\n                <label class="label" for="customer-password">\n                    <span data-bind="i18n: \'Password\'"></span>\n                </label>\n                <div class="control">\n                    <input class="input-text"\n                           type="password"\n                           name="password"\n                           id="checkout-login-password"\n                           data-validate="{required:true}"\n                           autocomplete="off"\n                           data-bind="mageInit: { \'passwordPlain\': {} }"/>\n                    <span class="note" data-bind="i18n: \'You already have an account with us. Sign in or continue as guest.\'"></span>\n                </div>\n\n            </div>\n\n            <div class="field">\n                <a class="action remind" data-bind="attr: { href: forgotPasswordUrl }">\n                    <span data-bind="i18n: \'Forgot Your Password?\'"></span>\n                </a>\n            </div>\n\n            <div class="actions-toolbar">\n                <input name="context" type="hidden" value="checkout" />\n                <div class="primary">\n                    <button type="submit" class="action login button green" data-action="checkout-method-login"><span data-bind="i18n: \'Login\'"></span></button>\n                </div>\n            </div>\n        </div>\n    </div>\n</form>\n\n<div class="form-email-toggle">\n    <button class="button green block s" data-bind=\'mageInit: { "toggle": { "target": "body", "class": "__show-login-form" } }\'>\n        <span data-bind=\'i18n: "Log In"\'></span>\n    </button>\n</div>\n';
});
define('text!MediaLounge_RegionalRestrictions/template/restrict.html', function() {
    return '<!-- ko if: isRestricted() -->\n    <!-- ko if: getRestrictMessages().length === 1 -->\n    <div class="regional-warning_container" data-bind="foreach: getRestrictMessages()">\n        <div class="regional-warning">\n            <span data-bind="text: message"></span>\n        </div>\n    </div>\n    <!-- /ko -->\n    <!-- ko if: getRestrictMessages().length > 1 -->\n    <div class="regional-warning_container">\n        <div class="regional-warning">\n            <span data-bind="text: multiple"></span>\n        </div>\n    </div>\n    <!-- /ko -->\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/form/element/email.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko ifnot: isCustomerLoggedIn() -->\n\n<!-- ko foreach: getRegion(\'before-login-form\') -->\n<!-- ko template: getTemplate() --><!-- /ko -->\n<!-- /ko -->\n<form class="form form-email" data-role="email-with-possible-login"\n      data-bind="\n        submit: login,\n        mageInit: { \'labels\': {} }\n    "\n      method="post">\n    <div class="checkout-step-title"><span data-bind="i18n: \'Delivery Information\'"></span></div>\n\n    <div id="customer-email-fieldset" class="fieldset" data-bind="blockLoader: isLoading">\n        <div class="legend"><span data-bind="i18n: \'Enter your email\'"></span></div>\n        <div class="field required">\n            <label class="label" for="customer-email">\n                <span data-bind="i18n: \'Email Address\'"></span>\n            </label>\n            <div class="control _with-tooltip">\n                <input class="input-text"\n                       type="email"\n                       data-bind="\n                            textInput: email,\n                            hasFocus: emailFocused,\n                            mageInit: {\'mage/trim-input\':{}}"\n                       name="username"\n                       data-validate="{required:true, \'validate-email\':true}"\n                       id="customer-email" />\n                <!-- ko template: \'ui/form/element/helper/tooltip\' --><!-- /ko -->\n                <span class="note" data-bind="fadeVisible: isGuestEmail"><!-- ko i18n: \'You can create an account after checkout.\'--><!-- /ko --></span>\n            </div>\n        </div>\n\n        <div class="field required" data-bind="fadeVisible: isGuestEmail">\n            <label class="label" for="customer-email-confirm">\n                <span data-bind="i18n: \'Confirm Email Address\'"></span>\n            </label>\n            <div class="control _with-tooltip">\n                <input class="input-text"\n                       type="text"\n                       data-bind="\n                            textInput: isPasswordVisible() == true ? email : \'\',\n                            mageInit: {\'mage/trim-input\':{}, \'inputPaste\':{}}"\n                       name="username"\n                       data-validate="{required:true, equalToEmail:\'#customer-email\'}"\n                       id="customer-email-confirm" />\n            </div>\n        </div>\n\n        <!--Hidden fields -->\n        <div class="fieldset hidden-fields" data-bind="fadeVisible: isPasswordVisible">\n            <div class="field">\n                <a class="action remind" href="#" data-bind="click: loginPopup">\n                    <span data-bind="html: loginPopupText()"></span>\n                </a>\n            </div>\n        </div>\n        <!--Hidden fields -->\n    </div>\n\n    <div class="form-email_message">\n        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 27 27"><g filter="url(#a)"><path stroke="#BBDEF1" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13.5 10v3.3m0 3.4h0m8.5-3.4a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0Z"></path></g><defs><filter id="a" width="26.5" height="26.5" x=".3" y=".1" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset></feOffset><feGaussianBlur stdDeviation="2"></feGaussianBlur><feColorMatrix values="0 0 0 0 0.733333 0 0 0 0 0.870588 0 0 0 0 0.945098 0 0 0 0.5 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_835_19335"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_835_19335" result="shape"></feBlend></filter></defs></svg>\n        <span data-bind="i18n: \'We will email you the details of your purchase once you place your order. This information is secure and will not be shared.\'"></span>\n    </div>\n</form>\n<!-- /ko -->\n';
});
define('text!Magento_Ui/template/messages.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div data-role="checkout-messages" class="messages" data-bind="visible: isVisible(), click: removeAll">\n    <!-- ko foreach: messageContainer.getErrorMessages() -->\n    <div aria-atomic="true" role="alert" class="message message-error error">\n        <div data-ui-id="checkout-cart-validationmessages-message-error" data-bind="text: $parent.parseMessage($data)"></div>\n    </div>\n    <!--/ko-->\n    <!-- ko foreach: messageContainer.getSuccessMessages() -->\n    <div aria-atomic="true" role="alert" class="message message-success success">\n        <div data-ui-id="checkout-cart-validationmessages-message-success" data-bind="text: $parent.parseMessage($data)"></div>\n    </div>\n    <!--/ko-->\n</div>\n';
});
define('text!MediaLounge_RegionalRestrictions/template/checkout.html', function() {
    return '<!-- ko if: isCheckoutRestricted() -->\n    <!-- ko if: getCheckoutRestrictMessages().length === 1 -->\n    <div class="regional-warning_container regional-checkout_container" data-bind="foreach: getCheckoutRestrictMessages()">\n        <div class="regional-warning">\n            <span data-bind="text: message"></span>\n        </div>\n    </div>\n    <!-- /ko -->\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/payment.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div id="payment" role="presentation" class="checkout-payment-method" data-bind="fadeVisible: isVisible">\n    <div id="checkout-step-payment"\n         class="step-content"\n         data-role="content"\n         role="tabpanel"\n         aria-hidden="false">\n        <!-- ko if: (quoteIsVirtual) -->\n            <!-- ko foreach: getRegion(\'customer-email\') -->\n                <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        <!--/ko-->\n        <form id="co-payment-form" class="form payments" novalidate="novalidate">\n            <input data-bind=\'attr: {value: getFormKey()}\' type="hidden" name="form_key"/>\n            <div class="fieldset">\n                <legend class="legend">\n                    <span data-bind="i18n: \'Payment Information\'"></span>\n                </legend><br />\n                <!-- ko foreach: getRegion(\'beforeMethods\') -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                <!-- /ko -->\n                <!--,-->\n                <div id="checkout-payment-method-load" class="opc-payment"\n                     data-bind="{ css: { \'disabled\': !isAddressAvailable() }, visible: isPaymentMethodsAvailable }">\n                    <!-- ko foreach: getRegion(\'payment-methods-list\') -->\n                        <!-- ko template: getTemplate() --><!-- /ko -->\n                    <!-- /ko -->\n                </div>\n                <div class="no-quotes-block" data-bind="visible: isPaymentMethodsAvailable() == false">\n                    <!-- ko i18n: \'No Payment method available.\'--><!-- /ko -->\n                </div>\n                <!-- ko foreach: getRegion(\'afterMethods\') -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                <!-- /ko -->\n            </div>\n        </form>\n    </div>\n</div>\n';
});
define('Magento_Checkout/js/guest-checkout', ['jquery'], $ => {
    'use strict';

    return (config, element) => {
        element.addEventListener('click', function(event) {
            setTimeout(() => {
                $('html,body').animate({ scrollTop: 0 }, 300);
            }, 0);
            $('#customer-email').focus();
            const ev = new Event('checkout:guest');

            document.body.dispatchEvent(ev);
        });
    };
});

'use strict';
/* eslint-disable */

define('Magento_Review/js/labels.babel', ['jquery', 'domReady!'], function ($) {
  'use strict';

  function getParent(el, filter) {
    el = el.parentNode;

    while (el.parentNode) {
      if (el.matches(filter)) {
        return el;
      }

      el = el.parentNode;
    }

    return null;
  }

  return function (config, element) {
    var strElements = 'input, select, textarea';
    $(element).on('focus', strElements, function () {
      var elParent = getParent(this, '.field');

      if (elParent) {
        elParent.classList.add('focussed');
        elParent = getParent(elParent, '.field');

        if (elParent) {
          elParent.classList.add('focussed');
        }
      }
    }).on('blur', strElements, function () {
      var elParent = getParent(this, '.field');

      if (elParent) {
        elParent.classList.remove('focussed');
        elParent = getParent(elParent, '.field');

        if (elParent) {
          elParent.classList.remove('focussed');
        }
      }
    }).on('change', strElements, function () {
      var elParent = getParent(this, '.field'); //

      if (elParent) {
        if (this.value) {
          elParent.classList.add('filled');
        } else {
          elParent.classList.remove('filled');
        }

        elParent = getParent(elParent, '.field');

        if (elParent) {
          if (this.value) {
            elParent.classList.add('filled');
          } else {
            elParent.classList.remove('filled');
          }
        }
      }

      $(this).trigger('postChange');

      if (!this.classList.contains('__filled-setup')) {
        this.classList.add('__filled-setup');
        const el = document.createElement('div');
        el.classList.add('filled-input-icon');
        this.insertAdjacentElement('afterend', el);
      }
    }).on('postChange', 'select', function () {
      if (!this.value) {
        return;
      }

      var elOption = this.querySelector('[value="'.concat(this.value, '"]'));

      if (elOption && elOption.textContent.trim()) {
        var elParent = getParent(this, '.field'); //

        if (elParent) {
          elParent.classList.add('filled');
        }
      }
    });
    var ivlsetup = setInterval(function () {
      if (element.querySelectorAll(strElements).length) {
        clearInterval(ivlsetup);
        $(element).find(strElements).trigger('change');
        $(element).find('select').each(function (index, el) {
          var elOpt, elParent;
          elOpt = el.querySelector('[value="'.concat(element.value, '"]'));

          if (elOpt && elOpt.textContent) {
            elParent = getParent(elOpt, '.field');
          }

          if (elParent) {
            elParent.classList.add('filled');
          }
        });
      }
    }, 500);
  };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/set-billing-address', 
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage',
        'Magento_Checkout/js/model/error-processor',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/action/get-payment-information'
    ],
    function ($,
              quote,
              urlBuilder,
              storage,
              errorProcessor,
              customer,
              fullScreenLoader,
              getPaymentInformationAction
    ) {
        'use strict';

        return function (messageContainer) {
            var serviceUrl,
                payload;

            /**
             * Checkout for guest and registered customer.
             */
            if (!customer.isLoggedIn()) {
                serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/billing-address', {
                    cartId: quote.getQuoteId()
                });
                payload = {
                    cartId: quote.getQuoteId(),
                    address: quote.billingAddress()
                };
            } else {
                serviceUrl = urlBuilder.createUrl('/carts/mine/billing-address', {});
                payload = {
                    cartId: quote.getQuoteId(),
                    address: quote.billingAddress()
                };
            }

            fullScreenLoader.startLoader();

            return storage.post(
                serviceUrl, JSON.stringify(payload)
            ).done(
                function () {
                    var deferred = $.Deferred();

                    getPaymentInformationAction(deferred);
                    $.when(deferred).done(function () {
                        fullScreenLoader.stopLoader();
                    });
                }
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageContainer);
                    fullScreenLoader.stopLoader();
                }
            );
        };
    }
);

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/billing-address-postcode-validator', [
           'jquery',
           'Magento_Checkout/js/model/postcode-validator',
           'mage/translate',
           'uiRegistry'
       ], function (
    $,
    postcodeValidator,
    $t,
    uiRegistry
) {
    'use strict';

    var postcodeElementName = 'postcode';

    return {
        validateZipCodeTimeout: 0,
        validateDelay: 2000,

        /**
         * Perform postponed binding for fieldset elements
         *
         * @param {String} formPath
         */
        initFields: function (formPath) {
            var self = this;

            uiRegistry.async(formPath + '.' + postcodeElementName)(self.bindHandler.bind(self));
        },

        /**
         * @param {Object} element
         * @param {Number} delay
         */
        bindHandler: function (element, delay) {
            var self = this;

            delay = typeof delay === 'undefined' ? self.validateDelay : delay;

            element.on('value', function () {
                clearTimeout(self.validateZipCodeTimeout);
                self.validateZipCodeTimeout = setTimeout(function () {
                    self.postcodeValidation(element);
                }, delay);
            });
        },

        /**
         * @param {Object} postcodeElement
         * @return {*}
         */
        postcodeValidation: function (postcodeElement) {
            var countryId = $('select[name="country_id"]:visible').val(),
                validationResult,
                warnMessage;

            if (postcodeElement == null || postcodeElement.value() == null) {
                return true;
            }

            postcodeElement.warn(null);
            validationResult = postcodeValidator.validate(postcodeElement.value(), countryId);

            if (!validationResult) {
                warnMessage = $t('Provided Zip/Postal Code seems to be invalid.');

                if (postcodeValidator.validatedPostCodeExample.length) {
                    warnMessage += $t(' Example: ') + postcodeValidator.validatedPostCodeExample.join('; ') + '. ';
                }
                warnMessage += $t('If you believe it is the right one you can ignore this notice.');
                postcodeElement.warn(warnMessage);
            }

            return validationResult;
        }
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/view/billing-address', [
    'ko',
    'underscore',
    'Magento_Ui/js/form/form',
    'Magento_Customer/js/model/customer',
    'Magento_Customer/js/model/address-list',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/create-billing-address',
    'Magento_Checkout/js/action/select-billing-address',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'Magento_Customer/js/customer-data',
    'Magento_Checkout/js/action/set-billing-address',
    'Magento_Ui/js/model/messageList',
    'mage/translate',
    'Magento_Checkout/js/model/billing-address-postcode-validator',
    'Magento_Checkout/js/model/address-converter'
],
function (
    ko,
    _,
    Component,
    customer,
    addressList,
    quote,
    createBillingAddress,
    selectBillingAddress,
    checkoutData,
    checkoutDataResolver,
    customerData,
    setBillingAddressAction,
    globalMessageList,
    $t,
    billingAddressPostcodeValidator,
    addressConverter
) {
    'use strict';

    var lastSelectedBillingAddress = null,
        addressUpadated = false,
        addressEdited = false,
        countryData = customerData.get('directory-data'),
        addressOptions = addressList().filter(function (address) {
            return address.getType() === 'customer-address';
        });

    return Component.extend({
        defaults: {
            template: 'Magento_Checkout/billing-address',
            actionsTemplate: 'Magento_Checkout/billing-address/actions',
            formTemplate: 'Magento_Checkout/billing-address/form',
            detailsTemplate: 'Magento_Checkout/billing-address/details',
            links: {
                isAddressFormVisible: '${$.billingAddressListProvider}:isNewAddressSelected'
            }
        },
        currentBillingAddress: quote.billingAddress,
        customerHasAddresses: addressOptions.length > 0,

        /**
         * Init component
         */
        initialize: function () {
            this._super();
            quote.paymentMethod.subscribe(function () {
                checkoutDataResolver.resolveBillingAddress();
            }, this);
            billingAddressPostcodeValidator.initFields(this.get('name') + '.form-fields');
        },

        /**
         * @return {exports.initObservable}
         */
        initObservable: function () {
            this._super()
                .observe({
                    selectedAddress: null,
                    isAddressDetailsVisible: quote.billingAddress() != null,
                    isAddressFormVisible: !customer.isLoggedIn() || !addressOptions.length,
                    isAddressSameAsShipping: false,
                    saveInAddressBook: 1
                });

            quote.billingAddress.subscribe(function (newAddress) {
                if (quote.isVirtual()) {
                    this.isAddressSameAsShipping(false);
                } else {
                    this.isAddressSameAsShipping(
                        newAddress != null &&
                        newAddress.getCacheKey() == quote.shippingAddress().getCacheKey() //eslint-disable-line eqeqeq
                    );
                }

                if (newAddress != null && newAddress.saveInAddressBook !== undefined) {
                    this.saveInAddressBook(newAddress.saveInAddressBook);
                } else {
                    this.saveInAddressBook(1);
                }
                this.isAddressDetailsVisible(true);
            }, this);

            return this;
        },

        canUseShippingAddress: ko.computed(function () {
            return !quote.isVirtual() && quote.shippingAddress() && quote.shippingAddress().canUseForBilling();
        }),

        /**
         * @param {Object} address
         * @return {*}
         */
        addressOptionsText: function (address) {
            return address.getAddressInline();
        },

        /**
         * @return {Boolean}
         */
        useShippingAddress: function () {
            if (this.isAddressSameAsShipping()) {
                selectBillingAddress(quote.shippingAddress());

                this.updateAddresses();
                this.isAddressDetailsVisible(true);
            } else {
                lastSelectedBillingAddress = quote.billingAddress();
                quote.billingAddress(null);
                this.isAddressDetailsVisible(false);
            }
            checkoutData.setSelectedBillingAddress(null);

            return true;
        },

        /**
         * Update address action
         */
        updateAddress: function () {
            var addressData, newBillingAddress;

            addressUpadated = true;

            if (this.selectedAddress() && !this.isAddressFormVisible()) {
                selectBillingAddress(this.selectedAddress());
                checkoutData.setSelectedBillingAddress(this.selectedAddress().getKey());
            } else {
                this.source.set('params.invalid', false);
                this.source.trigger(this.dataScopePrefix + '.data.validate');

                if (this.source.get(this.dataScopePrefix + '.custom_attributes')) {
                    this.source.trigger(this.dataScopePrefix + '.custom_attributes.data.validate');
                }

                if (!this.source.get('params.invalid')) {
                    addressData = this.source.get(this.dataScopePrefix);

                    if (customer.isLoggedIn() && !this.customerHasAddresses) { //eslint-disable-line max-depth
                        this.saveInAddressBook(1);
                    }
                    addressData['save_in_address_book'] = this.saveInAddressBook() ? 1 : 0;
                    newBillingAddress = createBillingAddress(addressData);
                    // New address must be selected as a billing address
                    selectBillingAddress(newBillingAddress);
                    checkoutData.setSelectedBillingAddress(newBillingAddress.getKey());
                    checkoutData.setNewCustomerBillingAddress(addressData);
                }
            }
            setBillingAddressAction(globalMessageList);
            this.updateAddresses();
        },

        /**
         * Edit address action
         */
        editAddress: function () {
            addressUpadated = false;
            addressEdited = true;
            lastSelectedBillingAddress = quote.billingAddress();
            quote.billingAddress(null);
            this.isAddressDetailsVisible(false);
        },

        /**
         * Cancel address edit action
         */
        cancelAddressEdit: function () {
            addressUpadated = true;
            this.restoreBillingAddress();

            if (quote.billingAddress()) {
                // restore 'Same As Shipping' checkbox state
                this.isAddressSameAsShipping(
                    quote.billingAddress() != null &&
                        quote.billingAddress().getCacheKey() == quote.shippingAddress().getCacheKey() && //eslint-disable-line
                        !quote.isVirtual()
                );
                this.isAddressDetailsVisible(true);
            }
        },

        /**
         * Manage cancel button visibility
         */
        canUseCancelBillingAddress: ko.computed(function () {
            return quote.billingAddress() || lastSelectedBillingAddress;
        }),

        /**
         * Check if Billing Address Changes should be canceled
         */
        needCancelBillingAddressChanges: function () {
            if (addressEdited && !addressUpadated) {
                this.cancelAddressEdit();
            }
        },

        /**
         * Restore billing address
         */
        restoreBillingAddress: function () {
            var lastBillingAddress;

            if (lastSelectedBillingAddress != null) {
                selectBillingAddress(lastSelectedBillingAddress);
                lastBillingAddress = addressConverter.quoteAddressToFormAddressData(lastSelectedBillingAddress);

                checkoutData.setNewCustomerBillingAddress(lastBillingAddress);
            }
        },

        /**
         * @param {Number} countryId
         * @return {*}
         */
        getCountryName: function (countryId) {
            return countryData()[countryId] != undefined ? countryData()[countryId].name : ''; //eslint-disable-line
        },

        /**
         * Trigger action to update shipping and billing addresses
         */
        updateAddresses: function () {
            if (window.checkoutConfig.reloadOnBillingAddress ||
                !window.checkoutConfig.displayBillingOnPaymentMethod
            ) {
                setBillingAddressAction(globalMessageList);
            }
        },

        /**
         * Get code
         * @param {Object} parent
         * @returns {String}
         */
        getCode: function (parent) {
            return _.isFunction(parent.getCode) ? parent.getCode() : 'shared';
        },

        /**
         * Get customer attribute label
         *
         * @param {*} attribute
         * @returns {*}
         */
        getCustomAttributeLabel: function (attribute) {
            var label;

            if (typeof attribute === 'string') {
                return attribute;
            }

            if (attribute.label) {
                return attribute.label;
            }

            if (_.isArray(attribute.value)) {
                label = _.map(attribute.value, function (value) {
                    return this.getCustomAttributeOptionLabel(attribute['attribute_code'], value) || value;
                }, this).join(', ');
            } else if (typeof attribute.value === 'object') {
                label = _.map(Object.values(attribute.value)).join(', ');
            } else {
                label = this.getCustomAttributeOptionLabel(attribute['attribute_code'], attribute.value);
            }

            return label || attribute.value;
        },

        /**
         * Get option label for given attribute code and option ID
         *
         * @param {String} attributeCode
         * @param {String} value
         * @returns {String|null}
         */
        getCustomAttributeOptionLabel: function (attributeCode, value) {
            var option,
                label,
                options = this.source.get('customAttributes') || {};

            if (options[attributeCode]) {
                option = _.findWhere(options[attributeCode], {
                    value: value
                });

                if (option) {
                    label = option.label;
                }
            } else if (value.file !== null) {
                label = value.file;
            }

            return label;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Checkout/js/model/payment/method-group', [
        'uiElement',
        'mage/translate'
], function (Element, $t) {
    'use strict';

    var DEFAULT_GROUP_ALIAS = 'default';

    return Element.extend({
        defaults: {
            alias: DEFAULT_GROUP_ALIAS,
            title: $t('Payment Method'),
            sortOrder: 100,
            displayArea: 'payment-methods-items-${ $.alias }'
        },

        /**
         * Checks if group instance is default
         *
         * @returns {Boolean}
         */
        isDefault: function () {
            return this.alias === DEFAULT_GROUP_ALIAS;
        }
    });
});

define('text!Magento_Captcha/template/checkout/captcha.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<input name="captcha_form_id" type="hidden" data-bind="value: formId,  attr: {\'data-scope\': dataScope}" />\n<!-- ko if: (isRequired() && getIsVisible())-->\n<div class="field captcha required" data-bind="blockLoader: getIsLoading()">\n    <label data-bind="attr: {for: \'captcha_\' + formId}" class="label"><span data-bind="i18n: \'Please type the letters and numbers below\'"></span></label>\n    <div class="control captcha">\n        <input name="captcha_string" type="text" class="input-text required-entry" data-bind="value: captchaValue(), attr: {id: \'captcha_\' + formId, \'data-scope\': dataScope}" autocomplete="off"/>\n        <div class="nested">\n            <div class="field captcha no-label">\n                <div class="control captcha-image">\n                    <img data-bind="attr: {\n                                        alt: $t(\'Please type the letters and numbers below\'),\n                                        title: $t(\'Please type the letters and numbers below\'),\n                                        height: imageHeight(),\n                                        src: getImageSource(),\n                                        }"\n                         class="captcha-img"/>\n                    <button type="button" class="action reload captcha-reload" data-bind="attr: {title: $t(\'Reload captcha\')}, click: refresh">\n                        <span data-bind="i18n: \'Reload captcha\'"></span>\n                    </button>\n                </div>\n            </div>\n            <!-- ko if: isCaseSensitive()-->\n            <div class="captcha-note note" data-bind="i18n: \'Attention: Captcha is case sensitive.\'"></div>\n            <!-- /ko -->\n        </div>\n    </div>\n</div>\n<!-- /ko -->\n';
});
define('text!Lof_SocialLogin/template/social-buttons.html', function() {
    return '<!-- ko if: isActive() -->\n<div class="lof-social-login-widget lof-social-customer lof-social-login lof-social-login-color"> \n\t<div class="social-login-authentication-channel row" data-bind="foreach: socials()">\n\t\t<div class="actions-toolbar social-btn col col-6 col-m-12" data-bind="css: label + \'-login\'">\n\t\t\t<div class="primary" data-bind = "socialButton: $parent.isActive, url: login_url, label: label">\n\t\t\t\t<button class="action button" type="button" data-test="yup">  \n\t\t\t\t\t<span>\n\t\t\t\t\t\t<span>\n\t\t\t\t\t\t\t<i class="fa icon-social"  data-bind="css: \'fa-\' + label +\' \'+label + \'-icon\'" aria-hidden="true"></i>\n\t\t\t\t\t\t\t<!--ko text: title--><!--/ko-->\n\t\t\t\t\t\t\t<!--ko i18n: "Sign In"--><!--/ko-->\n\t\t\t\t\t\t</span>   \n\t\t\t\t\t</span>\n\t\t\t\t</button>\n\t\t\t</div> \n\t\t</div>\n\t</div>  \n</div>  \n<!-- /ko --> ';
});
"use strict";

define('js/togglePasswordField.babel', ['jquery'], $ => {
  'use strict';

  return (config, element) => {
    $(window).trigger('renderPasswordField', element);
  };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('mage/trim-input', [
    'jquery'
], function ($) {
    'use strict';

    $.widget('mage.trimInput', {
        options: {
            cache: {}
        },

        /**
         * Widget initialization
         * @private
         */
        _create: function () {
            this.options.cache.input = $(this.element);
            this._bind();
        },

        /**
         * Event binding, will monitor change, keyup and paste events.
         * @private
         */
        _bind: function () {
            if (this.options.cache.input.length) {
                this._on(this.options.cache.input, {
                    'change': this._trimInput,
                    'keyup': this._trimInput,
                    'paste': this._trimInput
                });
            }
        },

        /**
         * Trim value
         * @private
         */
        _trimInput: function () {
            // Safari caret position workaround: storing carter position
            var caretStart, caretEnd, input;

            caretStart = this.options.cache.input.get(0).selectionStart;
            caretEnd = this.options.cache.input.get(0).selectionEnd;

            input = this._getInputValue().trim();

            this.options.cache.input.val(input);

            // Safari caret position workaround: setting caret position to previously stored values
            if (caretStart !== null && caretEnd !== null) {
                this.options.cache.input.get(0).setSelectionRange(caretStart, caretEnd);
            }
        },

        /**
         * Get input value
         * @returns {*}
         * @private
         */
        _getInputValue: function () {
            return this.options.cache.input.val();
        }
    });

    return $.mage.trimInput;
});

define('text!ui/template/form/element/helper/tooltip.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n <div class="field-tooltip toggle">\n\n    <!-- ko if: (tooltip.link)-->\n    <a class="field-tooltip-action action-help"\n       target="_blank"\n       data-toggle="dropdown"\n       data-bind="attr: {href: tooltip.link}, mageInit: {\'dropdown\':{\'activeClass\': \'_active\'}}"></a>\n     <!-- /ko -->\n\n     <span class="label" data-bind="attr: { id: $data.tooltipId ? $data.tooltipId : \'tooltip-label\' }"><!-- ko i18n: \'Tooltip\' --><!-- /ko --></span>\n     <!-- ko if: (!tooltip.link)-->\n         <span\n             class="field-tooltip-action action-help"\n             tabindex="0"\n             data-toggle="dropdown"\n             data-bind="\n                mageInit: {\'dropdown\':{\'activeClass\': \'_active\', \'parent\': \'.field-tooltip.toggle\'}},\n                attr: { \'aria-labelledby\': $data.tooltipId ? $data.tooltipId : \'tooltip-label\' }\n            "\n         >\n         </span>\n     <!-- /ko -->\n\n     <div class="field-tooltip-content"\n         data-target="dropdown" translate="tooltip.description">\n    </div>\n</div>\n';
});
define('text!MediaLounge_RoktTag/template/rokt-above.html', function() {
    return '<div id="rokt-above-payment"></div>';
});
define('text!Magento_Checkout/template/payment-methods/list.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n -->\n<div if="isPaymentMethodsAvailable()"\n     class="items payment-methods">\n    <div repeat="foreach: paymentGroupsList, item: \'$group\'"\n         class="payment-group">\n        <div if="getRegion($group().displayArea)().length"\n             class="step-title"\n             data-role="title">\n             <span translate="getGroupTitle($group)"></span>\n        </div>\n        <each args="data: getRegion($group().displayArea), as: \'method\'" render=""></each>\n    </div>\n</div>\n<div ifnot="isPaymentMethodsAvailable()"\n     class="no-payments-block"\n     translate="\'No Payment Methods\'">\n</div>\n';
});
define('text!MediaLounge_CheckoutMessage/template/promotion.html', function() {
    return '<!-- ko if: message -->\n<div class="checkout-message-wrapper paypal-promotion">\n    <div data-bind="html: message"></div>\n</div>\n<!-- /ko -->\n';
});
define('Magento_Checkout/js/input-paste', ['jquery'], $ => {
    'use strict';

    return (config, element) => {
        element.onpaste = e => {
            e.preventDefault();
            return false;
        };

        // Force validation re-assessment //
        $(element).on('input', () => {
            if (element.form.getAttribute('novalidate') === 'novalidate') {
                // Skip if validation has not yet been initialized
                $(element).valid();
            }
        });
    };
});

define('text!MediaLounge_PayPalPayLater/template/promotion.html', function() {
    return '<!-- ko if: isPromotionEnabled() -->\n<div class="paypal-promotion">\n    <div data-bind="html: message"></div>\n</div>\n<!-- /ko -->\n';
});
define('text!MediaLounge_RoktTag/template/rokt.html', function() {
    return '<div id="rokt-placeholder"></div>';
});
define('text!MediaLounge_RoktTag/template/rokt-below.html', function() {
    return '<div id="rokt-below-payment"></div>';
});
define('text!Magento_SalesRule/template/payment/discount.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isVisible -->\n<div class="payment-option _collapsible opc-payment-additional discount-code"\n     data-bind="mageInit: {\'collapsible\':{\'openedState\': \'_active\'}}">\n    <div class="payment-option-title field choice" data-role="title">\n        <span class="action action-toggle" id="block-discount-heading" role="heading" aria-level="2">\n            <!-- ko i18n: \'Discount Code\'--><!-- /ko -->\n        </span>\n    </div>\n    <div class="payment-option-content" data-role="content">\n        <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n        <form class="form form-discount" id="discount-form">\n            <div class="payment-option-inner">\n                <div class="field">\n                    <label class="label" for="discount-code">\n                        <span data-bind="i18n: \'Enter discount code\'"></span>\n                    </label>\n                    <div class="control">\n                        <input class="input-text"\n                               type="text"\n                               id="discount-code"\n                               name="discount_code"\n                               data-validate="{\'required-entry\':true}"\n                               data-bind="value: couponCode, attr:{disabled:isApplied() , placeholder: $t(\'Enter discount code\')} ">\n                    </div>\n                </div>\n            </div>\n            <div class="actions-toolbar">\n                <div class="primary">\n                    <!-- ko ifnot: isApplied() -->\n                        <button class="action action-apply button blue s" type="submit" data-bind="\'value\': $t(\'Apply Discount\'), click: apply">\n                            <span><!-- ko i18n: \'Apply Discount\'--><!-- /ko --></span>\n                        </button>\n                    <!-- /ko -->\n                    <!-- ko if: isApplied() -->\n                        <button class="action action-cancel button red s" type="submit" data-bind="\'value\': $t(\'Cancel\'), click: cancel">\n                            <span><!-- ko i18n: \'Cancel coupon\'--><!-- /ko --></span>\n                        </button>\n                    <!-- /ko -->\n                </div>\n            </div>\n            <!-- ko foreach: getRegion(\'captcha\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!-- /ko -->\n        </form>\n    </div>\n</div>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/summary.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="opc-block-summary" data-bind="blockLoader: isLoading">\n    <div class="title">\n        <span data-bind="i18n: \'Order Summary\'"></span>\n    </div>\n    \n    <!-- ko foreach: elems() -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!-- /ko -->\n</div>\n';
});
define('text!Magento_Checkout/template/billing-address.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="checkout-billing-address">\n    <div class="checkout-step-title"><span data-bind="i18n: \'Billing Information\'"></span></div>\n\n    <div class="billing-address-same-as-shipping-block field choice" data-bind="visible: canUseShippingAddress()">\n        <input type="checkbox" name="billing-address-same-as-shipping"\n               data-bind="checked: isAddressSameAsShipping, click: useShippingAddress, attr: {id: \'billing-address-same-as-shipping-\' + getCode($parent)}"/>\n\n        <label data-bind="attr: {for: \'billing-address-same-as-shipping-\' + getCode($parent)}"><span\n                data-bind="i18n: \'My billing and shipping address are the same\'"></span></label>\n    </div>\n\n    <render args="detailsTemplate"></render>\n\n    <fieldset class="fieldset" data-bind="visible: !isAddressDetailsVisible()">\n        <each args="getRegion(\'billing-address-list\')" render=""></each>\n\n        <div class="billing-address-form-wrapper" data-bind="fadeVisible: isAddressFormVisible">\n            <render args="formTemplate"></render>\n        </div>\n\n        <render args="actionsTemplate"></render>\n    </fieldset>\n</div>\n';
});
define('text!Aheadworks_Giftcard/template/payment/giftcard.html', function() {
    return '<div class="payment-option _collapsible opc-payment-additional aw-giftcard-code"\n     data-bind="mageInit: {\'collapsible\':{\'openedState\': \'_active\'}}">\n    <div class="payment-option-title field choice" data-role="title">\n        <span class="action action-toggle" id="block-aw-giftcard-heading" role="heading" aria-level="2">\n            <span data-bind="i18n: \'Gift Card\'"></span>\n        </span>\n    </div>\n    <div class="payment-option-content" data-role="content">\n        <each args="getRegion(\'messages\')" render=""></each>\n        <if args="isCustomerGiftcardCodesDisplayed()">\n            <div class="block aw-giftcard-codes-block" data-bind="blockLoader: isLoadingCustomerGiftcardsBlock()">\n                <div class="block-title">\n                    <span data-bind="i18n: \'Your Gift Card codes\'"></span>\n                </div>\n                <div class="block-content">\n                    <div class="box">\n                        <div class="box-content">\n                            <table>\n                                <tbody>\n                                    <tr repeat="foreach: getCustomerGiftcardCodes(), item: \'$giftcard\'"\n                                        data-bind="attr: {\'data-aw-giftcard-code\': $giftcard().code }">\n                                        <td class="code">\n                                            <text args="$giftcard().code"></text>\n                                        </td>\n                                        <td class="balance">\n                                            <text args="formatPrice($giftcard().balance)"></text>\n                                        </td>\n                                        <td class="action-apply">\n                                            <a href="#" data-bind="attr: {\'title\': $t(\'Apply\')},\n                                                                   click: applyByCode.bind($data, $giftcard().code),\n                                                                   i18n: \'Apply\'"></a>\n                                        </td>\n                                    </tr>\n                                <tbody>\n                            </table>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </if>\n        <form class="form form-aw-giftcard" id="aw-giftcard-form">\n            <div class="payment-option-inner">\n                <div class="field">\n                    <div class="control">\n                        <input class="input-text"\n                               type="text"\n                               id="giftcard_code"\n                               name="giftcard_code"\n                               data-validate="{\'required-entry\':true}"\n                               data-bind="value: giftcardCode, attr:{placeholder: $t(\'Enter Gift Card code\')} " />\n                    </div>\n                </div>\n            </div>\n            <div class="actions-toolbar">\n                <div class="primary">\n                    <button class="action action-apply button blue s" type="submit" data-bind="\'value\': $t(\'Apply\'), click: apply">\n                        <span data-bind="i18n: \'Apply\'"></span>\n                    </button>\n                </div>\n            </div>\n        </form>\n    </div>\n</div>\n';
});
/**
 * Mixin paypal express checkout
 */
define('Amasty_InvisibleCaptcha/js/view/paypal/in-context/checkout-express-mixin', [
    'jquery',
    'underscore',
    'Amasty_InvisibleCaptcha/js/model/am-recaptcha',
    'Magento_Checkout/js/model/payment/additional-validators'
], function ($, _, amReCaptchaModel, additionalValidators) {
    'use strict';

    var mixin = {
        defaults: {
            reCaptchaButton: false
        },
        isCaptchaValid: false,

        /** @inheritDoc */
        initListeners: function (context) {
            this._super(context);

            if (amReCaptchaModel.isEnabledOnPayments) {
                $.async('button[data-payment-name="' + this.index + '"]', function (element) {
                    this.reCaptchaButton = $(element);
                    this.validate();
                }.bind(this));

                amReCaptchaModel.isValidationPassed.subscribe(function (data) {
                    this.isCaptchaValid = data;
                }.bind(this));
            }

            return this;
        },

        /** @inheritDoc */
        validate: function (actions) {
            this.actions = actions || this.actions;

            if (this.actions) {
                if (amReCaptchaModel.isEnabledOnPayments && !this.isCaptchaValid) {
                    this.actions.disable();
                } else {
                    additionalValidators.validate(true)
                        ? this.actions.enable()
                        : this.actions.disable();

                }
            }
        },

        /**
         * Adding logic to be triggered onClick action for smart buttons component
         * @returns {void}
         */
        onClick: function () {
            var savedCallback = this._super;

            if (!this.isCaptchaValid && amReCaptchaModel.isEnabledOnPayments) {
                // eslint-disable-next-line one-var
                var subscribe = amReCaptchaModel.isValidationPassed.subscribe(function (data) {
                    if (this.actions) {
                        if (data) {
                            this.actions.enable();

                            savedCallback.apply(this);
                        } else {
                            this.actions.disable();
                        }
                    }

                    subscribe.dispose();
                }.bind(this));

                this.validateCaptcha();
            } else {
                savedCallback.apply(this);
            }
        },

        /**
         * Trigger captcha's invisible button
         * @returns {void}
         */
        validateCaptcha: function () {
            if (this.reCaptchaButton.length) {
                this.reCaptchaButton.trigger('click');
            }
        }
    };

    return function (ExpressCheckout) {
        return ExpressCheckout.extend(mixin);
    };
});

define('MediaLounge_DoublePoints/js/view/payment/checkoutcom_card_payment-mixin', [
    'jquery',
    'ko',
    'Magento_Customer/js/customer-data',
    'Magento_Checkout/js/model/quote',
    'mage/url'
], function($, ko, customerData, quote, urlBuilder){
    'use strict';

    let mixin = {
        defaults: {
            template: 'MediaLounge_DoublePoints/payment/checkoutcom_card_payment.html',
            paymentMethod: 'checkoutcom_card_payment',
            activeMethod: null,
            doublePoints: false,
            isDoublePoints: false,
            imports: {
                activeMethod: 'checkout.steps.billing-step.payment.double-points:activeMethod',
                doublePoints: 'checkout.steps.billing-step.payment.double-points:doublePoints',
            },
            listens: {
                activeMethod: 'displayPoints',
                doublePoints: 'displayPoints'
            },
            tracks: {
                activeMethod: true,
                doublePoints: true,
                isDoublePoints: true
            }
        },


        displayPoints: function() {
            if (this.doublePoints) {
                this.checkPoints();
                this.clearPoints();
            }
        },

        clearPoints: function() {
            let self = this;
            setTimeout((e) => {
                self.isDoublePoints = false;
            }, 3000);
        },

        checkPoints: function () {
            let self = this;
            this.doublePoints.forEach(el => {
                if (el.paymentMethod === self.paymentMethod &&
                    self.paymentMethod === self.activeMethod) {
                    self.isDoublePoints = el.doublePoints;
                }
            });
        },
    };

    return function (target) {
        return target.extend(mixin);
    };
});

define('CheckoutCom_Magento2/js/view/payment/method-renderer/checkoutcom_card_payment-mixin', [], () => {
    'use strict';

    const mixin = {
        /**
         * Removes the payment form
         *
         * @return {void}
         */
        removeCkoPaymentForm: function () {
            // Remove the events
            Frames.removeAllEventHandlers(Frames.Events.CARD_VALIDATION_CHANGED);
            Frames.removeAllEventHandlers(Frames.Events.CARD_TOKENIZED);
            Frames.removeAllEventHandlers(Frames.Events.FRAME_VALIDATION_CHANGED);
            Frames.removeAllEventHandlers(Frames.Events.PAYMENT_METHOD_CHANGED);

            // Remove the HTML
            if ( $('#' + this.formId) && $('#' + this.formId).html().length > 0 ) {
                this.formClone = $('#' + this.formId).html();
            }
        }
    };

    return target => target.extend(mixin);
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* @api */
define('Magento_OfflinePayments/js/view/payment/method-renderer/checkmo-method', [
    'Magento_Checkout/js/view/payment/default'
], function (Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_OfflinePayments/payment/checkmo'
        },

        /**
         * Returns send check to info.
         *
         * @return {*}
         */
        getMailingAddress: function () {
            return window.checkoutConfig.payment.checkmo.mailingAddress;
        },

        /**
         * Returns payable to info.
         *
         * @return {*}
         */
        getPayableTo: function () {
            return window.checkoutConfig.payment.checkmo.payableTo;
        }
    });
});

define('MediaLounge_Credorax/js/view/payment/method-renderer/credorax', [
    'Magento_Checkout/js/view/payment/default',
    'Magento_Checkout/js/action/redirect-on-success'
], function (Component, redirectOnSuccessAction) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'MediaLounge_Credorax/payment/form',
            paymentReady: false
        },
        redirectAfterPlaceOrder: true,

        placeOrder: function () {
            redirectOnSuccessAction.redirectUrl = 'credorax';

            return this._super();
        },

        getIconSrc: function () {
            return window.checkoutConfig.payment[this.getCode()].iconSrc;
        },
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('mage/dropdowns', [
    'jquery'
], function ($) {
    'use strict';

    /**
     * @param {Object} options
     */
    $.fn.dropdown = function (options) {
        var defaults = {
                parent: null,
                autoclose: true,
                btnArrow: '.arrow',
                menu: '[data-target="dropdown"]',
                activeClass: 'active'
            },
            actionElem = $(this),
            self = this;

        options = $.extend(defaults, options);
        actionElem = $(this);
        self = this;

        /**
         * @param {HTMLElement} elem
         */
        this.openDropdown = function (elem) {
            elem
                .addClass(options.activeClass)
                .attr('aria-expanded', true)
                .parent()
                    .addClass(options.activeClass);

            elem.parent()
                .find(options.menu)
                .attr('aria-hidden', false);

            $(options.btnArrow, elem).text('-');
        };

        /**
         * @param {HTMLElement} elem
         */
        this.closeDropdown = function (elem) {
            elem.removeClass(options.activeClass)
                .attr('aria-expanded', false)
                .parent()
                    .removeClass(options.activeClass);

            elem.parent()
                .find(options.menu)
                .attr('aria-hidden', true);

            $(options.btnArrow, elem).text('+');
        };

        /**
         * Reset all dropdowns.
         *
         * @param {Object} param
         */
        this.reset = function (param) {
            var params = param || {},
                dropdowns = params.elems || actionElem;

            dropdowns.each(function (index, elem) {
                self.closeDropdown($(elem));
            });
        };

        /* document Event bindings */
        if (options.autoclose === true) {
            $(document).on('click.hideDropdown', this.reset);
            $(document).on('keyup.hideDropdown', function (e) {
                var ESC_CODE = '27';

                if (e.keyCode == ESC_CODE) { //eslint-disable-line eqeqeq
                    self.reset();
                }
            });
        }

        if (options.events) {
            $.each(options.events, function (index, event) {
                $(document).on(event.name, event.selector, event.action);
            });
        }

        return this.each(function () {
            var elem = $(this),
                parent = $(options.parent).length > 0 ? $(options.parent) : elem.parent(),
                menu = $(options.menu, parent) || $('.dropdown-menu', parent);

            // ARIA (adding aria attributes)
            if (menu.length) {
                elem.attr('aria-haspopup', true);
            }

            if (!elem.hasClass(options.activeClass)) {
                elem.attr('aria-expanded', false);
                menu.attr('aria-hidden', true);
            } else {
                elem.attr('aria-expanded', true);
                menu.attr('aria-hidden', false);
            }

            if (!elem.is('a, button')) {
                elem.attr('role', 'button');
                elem.attr('tabindex', 0);
            }

            if (elem.attr('data-trigger-keypress-button')) {
                elem.on('keypress', function (e) {
                    var keyCode = e.keyCode || e.which,
                        ENTER_CODE = 13;

                    if (keyCode === ENTER_CODE) {
                        e.preventDefault();
                        elem.trigger('click.toggleDropdown');
                    }
                });
            }

            elem.on('click.toggleDropdown', function () {
                var el = actionElem;

                if (options.autoclose === true) {
                    actionElem = $();
                    $(document).trigger('click.hideDropdown');
                    actionElem = el;
                }

                self[el.hasClass(options.activeClass) ? 'closeDropdown' : 'openDropdown'](elem);

                return false;
            });
        });
    };

    return function (data, el) {
        $(el).dropdown(data);
    };
});

define('text!Magento_Checkout/template/summary/totals.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isDisplayed() -->\n<table class="data table table-totals">\n    <caption class="table-caption" data-bind="i18n: \'Order Summary\'"></caption>\n    <tbody>\n    <!-- ko foreach: elems() -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!-- /ko -->\n    </tbody>\n</table>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/summary/cart-items.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="block items-in-cart" data-bind="mageInit: {\'collapsible\':{\'openedState\': \'active\', \'active\': isItemsBlockExpanded()}}">\n    <div class="title" data-role="title">\n        <strong role="heading" aria-level="1">\n            <translate args="maxCartItemsToDisplay" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>\n            <translate args="\'of\'" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>\n            <span data-bind="text: getCartSummaryItemsCount().toLocaleString(window.LOCALE)"></span>\n            <translate args="\'Item in Cart\'" if="getCartSummaryItemsCount() === 1"></translate>\n            <translate args="\'Items in Cart\'" if="getCartSummaryItemsCount() > 1"></translate>\n        </strong>\n    </div>\n    <div class="content minicart-items" data-role="content">\n        <div class="minicart-items-wrapper">\n            <ol class="minicart-items">\n                <each args="items()">\n                    <li class="product-item">\n                        <div class="product">\n                            <each args="$parent.elems()" render=""></each>\n                        </div>\n                    </li>\n                </each>\n            </ol>\n        </div>\n    </div>\n    <div class="actions-toolbar" if="maxCartItemsToDisplay < getCartLineItemsCount()">\n        <div class="secondary">\n            <a class="action viewcart" data-bind="attr: {href: cartUrl}">\n                <span data-bind="i18n: \'View and Edit Cart\'"></span>\n            </a>\n        </div>\n    </div>\n</div>\n';
});
define('text!Magento_Checkout/template/billing-address/details.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div if="isAddressDetailsVisible() && currentBillingAddress()" class="billing-address-details">\n    <div class="title">\n        <span data-bind="i18n: \'Billing Address\'"></span>\n    </div>\n\n    <div class="address-option address-option__selected">\n        <div class="address-option_content">\n            <div class="address-option_label"><span data-bind=\'i18n: "Name"\'></span></div>\n            <div class="address-option_value">\n                <text args="currentBillingAddress().prefix"></text> <text args="currentBillingAddress().firstname"></text>\n                <text args="currentBillingAddress().middlename"></text>\n                <text args="currentBillingAddress().lastname"></text> <text args="currentBillingAddress().suffix"></text>\n            </div>\n\n            <div class="address-option_label"><span data-bind=\'i18n: "Address"\'></span></div>\n            <div class="address-option_value">\n                <text args="currentBillingAddress().street.join(\', \')"></text>,\n                <text args="currentBillingAddress().city "></text>,\n                <span text="currentBillingAddress().region"></span>\n                <text args="currentBillingAddress().postcode"></text>\n            </div>\n            <div class="address-option_label"><span data-bind=\'i18n: "Tel"\'></span></div>\n            <div class="address-option_value"><text args="currentBillingAddress().telephone"></text></div>\n        </div>\n    </div>\n\n    <each args="data: currentBillingAddress().customAttributes, as: \'element\'">\n        <text args="$parent.getCustomAttributeLabel(element)"></text>\n        <br/>\n    </each>\n\n    <button visible="!isAddressSameAsShipping()"\n            type="button"\n            class="action action-edit-address button blue"\n            click="editAddress">\n        <span translate="\'Change Address\'"></span>\n    </button>\n</div>\n\n';
});
define('text!Magento_Checkout/template/billing-address/list.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="field field-select-billing">\n    <label class="label"><span data-bind="i18n: \'Billing Address\'"></span></label>\n    <div class="control" data-bind="if: (addressOptions.length > 1)">\n        <select class="select" name="billing_address_id" data-bind="\n        options: addressOptions,\n        optionsText: addressOptionsText,\n        value: selectedAddress,\n        event: {change: onAddressChange(selectedAddress())};\n    "></select>\n    </div>\n</div>\n\n<!-- ko if: (addressOptions.length > 1) -->\n<div class="address-options" data-bind="foreach: addressOptions">\n    <!-- ko ifnot: customerAddressId == null -->\n    <div class="address-option">\n        <label class="address-option_radio"><input type="radio" data-bind="value: $data, checked: $parent.selectedAddress, event: {change: $parent.onAddressChange($parent.selectedAddress())}"><span></span></label>\n    \n        <div class="address-option_content">\n            <div class="address-option_label"><span data-bind=\'i18n: "Name"\'></span></div>\n            <div class="address-option_value"><span data-bind=\'text: firstname\'></span> <span data-bind=\'text: lastname\'></span></div>\n        \n            <div class="address-option_label"><span data-bind=\'i18n: "Address"\'></span></div>\n            <div class="address-option_value">\n                <span data-bind=\'foreach: street\'><!-- ko text: $data --><!-- /ko --></span>\n                <!-- ko text: city --><!-- /ko -->\n                <!-- ko text: region --><!-- /ko -->\n                <!-- ko text: postcode --><!-- /ko -->\n            </div>\n        \n            <div class="address-option_label"><span data-bind=\'i18n: "Tel"\'></span></div>\n            <div class="address-option_value"><!-- ko text: telephone --><!-- /ko --></div>\n        </div>\n    </div>\n    <!--/ko-->\n\n    <!-- ko if: customerAddressId == null -->\n    <div class="address-new" data-bind="css: { \'__hide\': $parent.isNewAddressSelected() }">\n        <label class="button blue">\n            <span data-bind=\'i18n: "Add another address +"\'></span>\n            <input type="radio" data-bind="value: $data, checked: $parent.selectedAddress, event: {change: $parent.onAddressChange($parent.selectedAddress())}">\n        </label>\n    </div>\n    <!--/ko-->\n</div>\n<!--/ko-->';
});
define('text!Magento_Checkout/template/billing-address/form.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="billing-address-form">\n    <!-- ko foreach: getRegion(\'before-fields\') -->\n    <!-- ko template: getTemplate() --><!-- /ko -->\n    <!--/ko-->\n    <form\n        data-bind="attr: {\'data-hasrequired\': $t(\'* Required Fields\')},\n        mageInit: { \'labels\': {} }"\n    >\n        <div class="fieldset address" data-form="billing-new-address">\n            <!-- ko foreach: getRegion(\'additional-fieldsets\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n            <!-- ko if: (isCustomerLoggedIn && customerHasAddresses) -->\n            <div class="choice field">\n                <input type="checkbox" class="checkbox"  data-bind="checked: saveInAddressBook, attr: {id: \'billing-save-in-address-book-\' + getCode($parent)}" />\n                <label class="label" data-bind="attr: {for: \'billing-save-in-address-book-\' + getCode($parent)}" >\n                    <span data-bind="i18n: \'Save in address book\'"></span>\n                </label>\n            </div>\n            <!-- /ko -->\n        </div>\n    </form>\n</div>\n';
});
define('text!Magento_Checkout/template/billing-address/actions.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="actions-toolbar">\n    <div class="primary">\n        <button class="action action-update button green"\n                type="button"\n                click="updateAddress">\n            <span translate="\'Confirm Address\'"></span>\n        </button>\n        <button class="action action-cancel button red"\n                type="button"\n                click="cancelAddressEdit"\n                visible="canUseCancelBillingAddress()">\n            <span translate="\'Cancel\'"></span>\n        </button>\n    </div>\n</div>\n';
});
/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/frames/multi', 
    [
        'jquery',
        'mage/translate'
    ],
    function ($, __) {
        'use strict';

        return {
            load: function (framesInstance, formId) {
                // Assign properties
                this.F = framesInstance;
                this.formId = formId;

                // Validation changed event
                this.F.addEventHandler(
                    this.F.Events.FRAME_VALIDATION_CHANGED,
                    this.onValidationChanged.bind(this)
                );

                // Payment method changed event
                this.F.addEventHandler(
                    this.F.Events.PAYMENT_METHOD_CHANGED,
                    this.paymentMethodChanged.bind(this)
                );

                return this.F;
            },

            getLogos: function () {
                var logos = {};

                logos['card-number'] = {
                    src: 'card',
                    alt: __('Card number logo')
                };

                logos['expiry-date'] = {
                    src: 'exp-date',
                    alt: __('Expiry date logo')
                };

                logos['cvv'] = {
                    src: 'cvv',
                    alt: __('CVV logo')
                };

                return logos;
            },

            getErrors: function () {
                var errors = {
                    'card-number': __('Please enter a valid card number'),
                    'expiry-date': __('Please enter a valid expiry date'),
                    'cvv': __('Please enter a valid CVV code')
                };

                return errors;
            },

            onValidationChanged: function (event) {
                var e = event.element;
                var pm = event.paymentMethod;
                var targetSelector = '#' + this.formId + ' .icon-container.payment-method';
                let container = document.querySelector(targetSelector);

                if (event.isValid || event.isEmpty) {
                    if (e == 'card-number' && !event.isEmpty) {
                        this.showPaymentMethodIcon(container, pm);
                    }
                    this.setDefaultIcon(e);
                    this.clearErrorIcon(e);
                    this.clearErrorMessage(e);
                } else {
                    if (e == 'card-number') {
                        this.clearPaymentMethodIcon();
                    }
                    this.setDefaultErrorIcon(e);
                    this.setErrorIcon(e);
                    this.setErrorMessage(e);
                }
            },

            clearErrorMessage: function (el) {
                var targetSelector = '#' + this.formId + ' .error-message__' + el;
                var message = document.querySelector(targetSelector);
                message.textContent = '';
            },

            clearErrorIcon: function (el) {
                var logo = document.getElementById('icon-' + el + '-error');
                logo.style.removeProperty('display');
            },

            showPaymentMethodIcon: function (parent, pm) {
                if (parent) {
                    parent.classList.add('show');
                }
                var logo = document.getElementById('logo-payment-method');
                if (pm) {
                    var name = pm.toLowerCase();
                    logo.setAttribute('src', this.getImagesPath() + name + '.svg');
                    logo.setAttribute('alt', pm || __('Payment method'));
                }
                logo.style.removeProperty('display');
            },

            getImagesPath: function () {
                return window.checkoutConfig.payment.checkoutcom_magento2.checkoutcom_data.images_path
                + '/frames/multi/';
            },

            clearPaymentMethodIcon: function (parent) {
                if (parent) {
                    parent.classList.remove('show');
                }
                var logo = document.getElementById('logo-payment-method');
                logo.style.setProperty('display', 'none');
            },

            setErrorMessage: function (el) {
                var targetSelector = '#' + this.formId + ' .error-message__' + el;
                var message = document.querySelector(targetSelector);
                message.textContent = this.getErrors()[el];
            },

            setDefaultIcon: function (el) {
                var selector = 'icon-' + el;
                var logos = this.getLogos();
                var logo = document.getElementById(selector);
                logo.setAttribute('src', this.getImagesPath() + logos[el].src + '.svg');
                logo.setAttribute('alt', logos[el].alt);
            },

            setDefaultErrorIcon: function (el) {
                var selector = 'icon-' + el;
                var logos = this.getLogos();
                var logo = document.getElementById(selector);
                logo.setAttribute('src', this.getImagesPath() + logos[el].src + '-error.svg');
                logo.setAttribute('alt', logos[el].alt);
            },

            setErrorIcon: function (el) {
                var logo = document.getElementById('icon-' + el + '-error');
                logo.style.setProperty('display', 'block');
            },

            paymentMethodChanged: function (event) {
                var pm = event.paymentMethod;
                var targetSelector = '#' + this.formId + ' .icon-container.payment-method';
                let container = document.querySelector(targetSelector);
                if (!pm) {
                    this.clearPaymentMethodIcon(container);
                } else {
                    this.clearErrorIcon('card-number');
                    this.showPaymentMethodIcon(container, pm);
                }
            }
        };
    }
);

define('text!Magento_OfflinePayments/template/payment/checkmo.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="payment-method" data-bind="css: {\'_active\': (getCode() == isChecked())}">\n    <div class="payment-method-title field choice">\n        <input type="radio"\n               name="payment[method]"\n               class="radio"\n               data-bind="attr: {\'id\': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>\n        <label data-bind="attr: {\'for\': getCode()}" class="label"><span data-bind="text: getTitle()"></span></label>\n    </div>\n    <div class="payment-method-content">\n        <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n        <div class="payment-method-billing-address">\n            <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <!-- ko if: getMailingAddress() || getPayableTo() -->\n        <dl class="items check payable">\n            <!-- ko if: getPayableTo() -->\n            <dt class="title"><!-- ko i18n: \'Make Check payable to:\' --><!-- /ko --></dt>\n            <dd class="content"><!-- ko text: getPayableTo() --><!-- /ko --></dd>\n            <!-- /ko -->\n            <!-- ko if: getMailingAddress() -->\n            <dt class="title"><!-- ko i18n: \'Send Check to:\' --><!-- /ko --></dt>\n            <dd class="content">\n                <address class="checkmo mailing address" data-bind="html: getMailingAddress()"></address>\n            </dd>\n            <!-- /ko -->\n        </dl>\n        <!-- /ko -->\n        <div class="checkout-agreements-block">\n            <!-- ko foreach: $parent.getRegion(\'before-place-order\') -->\n                <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <div class="actions-toolbar">\n            <div class="primary">\n                <button class="action primary checkout"\n                        type="submit"\n                        data-bind="\n                        click: placeOrder,\n                        attr: {title: $t(\'Place Order\')},\n                        css: {disabled: !isPlaceOrderActionAllowed()},\n                        enable: (getCode() == isChecked())\n                        "\n                        disabled>\n                    <span data-bind="i18n: \'Place Order\'"></span>\n                </button>\n            </div>\n        </div>\n    </div>\n</div>\n        \n';
});
define('text!MediaLounge_Credorax/template/payment/form.html', function() {
    return '<div class="payment-method" data-bind="css: {\'_active\': (getCode() == isChecked())}">\n    <div class="payment-method-title field choice">\n        <input type="radio"\n               name="payment[method]"\n               class="radio"\n               data-bind="attr: {\'id\': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()">\n        <label class="label" data-bind="attr: {\'for\': getCode()}">\n            <img data-bind="attr: {src: getIconSrc(), alt: getTitle()}" class="payment-icon" style="height:44px;">\n            <span data-bind="text: getTitle()"></span>\n        </label>\n    </div>\n\n    <div class="payment-method-content">\n        <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n        <div class="payment-method-billing-address">\n            <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <div class="checkout-agreements-block">\n            <!-- ko foreach: $parent.getRegion(\'before-place-order\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <div class="actions-toolbar">\n            <div class="primary">\n                <button class="action primary checkout"\n                        type="submit"\n                        data-bind="\n                        click: placeOrder,\n                        attr: {title: $t(\'Place Order Securely\')}\n                        ">\n                    <span data-bind="i18n: \'Place Order Securely\'"></span>\n                </button>\n            </div>\n        </div>\n    </div>\n</div>\n';
});
/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/frames/single', 
    [
        'jquery',
        'mage/translate'
    ],
    function ($, __) {
        'use strict';

        return {
            load: function (framesInstance, formId) {
                // Assign properties
                this.F = framesInstance;
                this.formId = formId;

                // Validation changed event
                this.F.addEventHandler(
                    this.F.Events.FRAME_VALIDATION_CHANGED,
                    this.onValidationChanged.bind(this)
                );

                return this.F;
            },

            getErrors: function () {
                var errors = {
                    'card-number': __('Please enter a valid card number'),
                    'expiry-date': __('Please enter a valid expiry date'),
                    'cvv': __('Please enter a valid CVV code')
                };

                return errors;
            },

            getErrorMessage: function (event) {
                if (event.isValid || event.isEmpty) {
                    return '';
                }

                return this.getErrors()[event.element];
            },

            onValidationChanged: function (event) {
                var targetSelector = '.error-message';
                var errorMessage = document.querySelector(targetSelector);
                errorMessage.textContent = this.getErrorMessage(event);
            }
        };
    }
);

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-present Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('CheckoutCom_Magento2/js/view/payment/method-renderer/checkoutcom_card_payment', 
    [
        'jquery',
        'ko',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'CheckoutCom_Magento2/js/frames/multi',
        'CheckoutCom_Magento2/js/frames/single',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'framesjs'
    ],
    function ($, ko, Component, Utilities, FramesMulti, FramesSingle, AdditionalValidators, Customer, Quote) {
        'use strict';
        window.checkoutConfig.reloadOnBillingAddress = true;
        const METHOD_ID = 'checkoutcom_card_payment';
        let cardholderName = '';


        return Component.extend(
            {
                defaults: {
                    template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
                    buttonId: METHOD_ID + '_btn',
                    formId: METHOD_ID + '_frm',
                    formClone: null,
                    cardToken: null,
                    cardBin: null,
                    saveCard: false,
                    preferredScheme: false,
                    supportedCards: null,
                    redirectAfterPlaceOrder: false,
                    allowPlaceOrder: ko.observable(false)
                },

                /**
                 * @return {exports}
                 */
                initialize: function () {
                    this._super();
                    Utilities.loadCss(this.getFormLayout(), 'frames');
                    Utilities.setEmail();

                    return this;
                },

                /**
                 * @return {string}
                 */
                getCode: function () {
                    return METHOD_ID;
                },

                /**
                 * @return {string}
                 */
                getValue: function (field) {
                    return Utilities.getValue(METHOD_ID, field);
                },

                /**
                 * @return {string}
                 */
                isVaultEnabled: function () {
                    return parseInt(Utilities.getValue('checkoutcom_vault', 'active', true));
                },

                /**
                 * @return {string}
                 */
                isSaveCardEnabled: function () {
                    return parseInt(this.getValue('save_card_option'));
                },

                /**
                 * @return {bool}
                 */
                shouldDisplayCardIcons: function () {
                    return this.getValue('display_card_icons') == true;
                },

                /**
                 * @return {array}
                 */
                getCardIcons: function () {
                    return Utilities.getSupportedCards();
                },

                /**
                 * @return {bool}
                 */
                isLoggedIn: function () {
                    return Customer.isLoggedIn();
                },

                /**
                 * @return {void}
                 */
                initEvents: function () {
                    var self = this;

                    // Save card event
                    $('input[name="saveCard"]').on(
                        'click',
                        function () {
                            self.saveCard = this.checked;
                        }
                    );

                    self.getCkoPaymentForm();

                    // Option click event
                    $('.payment-method input[type="radio"]').on('click', function () {
                        self.allowPlaceOrder(false);

                        if ($(this).attr('id') == METHOD_ID) {
                            self.getCkoPaymentForm();
                        } else {
                            self.removeCkoPaymentForm();
                        }
                    });

                    // Clear frames after update billing event
                    $(document).on('click', '.action-update', function () {
                        if ($('#checkoutcom_card_payment').is(':checked')) {
                            Frames.init()
                        }
                    })
                },

                /**
                 * @return {void}
                 */
                handleFormState: function () {
                    if (Utilities.methodIsSelected(METHOD_ID)) {
                        this.getCkoPaymentForm();
                    }
                },

                /**
                 * Gets the payment form styles
                 *
                 * @return {void}
                 */
                getFormStyles: function () {
                    var formStyles = this.getValue('payment_form_styles');

                    // Reject empty, null or undefined values
                    if (formStyles === undefined || formStyles == null || formStyles.length <= 0) {
                        return false;
                    }

                    // Check if the styles are valid
                    try {
                        var stylesObj = JSON.parse(formStyles);
                    } catch (e) {
                        return null;
                    }

                    return stylesObj;
                },

                /**
                 * Gets the payment form layout
                 *
                 * @return {void}
                 */
                getFormLayout: function () {
                    return this.getValue('payment_form_layout');
                },

                /**
                 * Gets the module images path
                 *
                 * @return {void}
                 */
                getImagesPath: function () {
                    return window.checkoutConfig.payment.checkoutcom_magento2.checkoutcom_data.images_path;
                },

                /**
                 * Gets the payment form
                 *
                 * @return {void}
                 */
                getCkoPaymentForm: function () {
                    // Prepare the needed variables
                    var self = this;
                    var formStyles = self.getFormStyles();

                    // Restore any existing HTML
                    if (this.formClone) {
                        // Restore the clone HTML
                        $('#' + this.formId).html(this.formClone);

                        // Empty the clone cache
                        this.formClone = null;
                    }

                    // Initialize the payment form
                    Frames.init(
                        {
                            publicKey: self.getValue('public_key'),
                            debug: Boolean(self.getValue('debug') && self.getValue('console_logging')),
                            schemeChoice: {
                                frameSelector: ".scheme-choice-frame"
                            },
                            localization: Utilities.getShopLanguage(),
                            style: (formStyles) ? formStyles : {}
                        }
                    );

                    // Load the Frames instance component
                    Frames = this.addFramesComponent(Frames);

                    // Add the Frames events
                    this.addFramesEvents();
                },

                /**
                 * Loads a Frames component.
                 * @return {void}
                 */
                addFramesComponent: function (framesInstance) {
                    if (this.getFormLayout() == 'multi') {
                        Frames = FramesMulti.load(framesInstance, this.formId);
                    } else {
                        Frames = FramesSingle.load(framesInstance, this.formId);
                    }

                    return Frames;
                },

                /**
                 * Removes the payment form
                 *
                 * @return {void}
                 */
                removeCkoPaymentForm: function () {
                    // Remove the events
                    Frames.removeAllEventHandlers(Frames.Events.CARD_VALIDATION_CHANGED);
                    Frames.removeAllEventHandlers(Frames.Events.CARD_TOKENIZED);
                    Frames.removeAllEventHandlers(Frames.Events.FRAME_VALIDATION_CHANGED);
                    Frames.removeAllEventHandlers(Frames.Events.PAYMENT_METHOD_CHANGED);

                    // Remove the HTML
                    var container = $('#' + this.formId);
                    if ( $('#' + this.formId).html().length > 0 ) {
                        this.formClone = $('#' + this.formId).html();
                    }
                    container.empty();
                },

                /**
                 * Add events to Frames.
                 * @return {void}
                 */
                addFramesEvents: function () {
                    var self = this;

                    // Frames ready event
                    Frames.addEventHandler(
                        Frames.Events.READY,
                        function() {
                            var valid = Utilities.getBillingAddress() != null;

                            if(valid) {
                                cardholderName = Utilities.getCustomerName();
                            }
                        }
                    )

                    // Card validation changed event
                    Frames.addEventHandler(
                        Frames.Events.CARD_VALIDATION_CHANGED,
                        function (event) {
                            var valid = Frames.isCardValid()
                            if (valid) {
                                if(cardholderName.length === 0) {
                                    if(Utilities.getBillingAddress()) {
                                        cardholderName = Utilities.getCustomerName();
                                    }
                                }

                                if (cardholderName.length > 0) {
                                    Frames.cardholder = {
                                        name: cardholderName
                                    };
                                }

                                // Submit the payment form
                                Frames.submitCard();
                            }

                            self.allowPlaceOrder(false);
                        }
                    );

                    // Card tokenized event
                    Frames.addEventHandler(
                        Frames.Events.CARD_TOKENIZED,
                        function (event) {
                            // Store the card token and the card bin
                            self.cardToken = event.token;
                            self.cardBin =  event.bin;
                            self.preferredScheme = event.preferred_scheme;

                            // Enable the submit form
                            Frames.enableSubmitForm();

                            // Set allowPlaceOrder to true only when tokenized.
                            self.allowPlaceOrder(true);
                        }
                    );

                    // Card bin event
                    Frames.addEventHandler(
                        Frames.Events.CARD_BIN_CHANGED,
                        function (event) {
                            self.preferredScheme = event.scheme;
                        }
                    );
                },

                /**
                 * @return {void}
                 */
                placeOrder: function () {
                    if (Utilities.methodIsSelected(METHOD_ID)) {
                        // Validate the order placement
                        if (AdditionalValidators.validate() && Frames.isCardValid()) {
                            // Prepare the payload
                            var payload = {
                                methodId: METHOD_ID,
                                cardToken: this.cardToken,
                                cardBin: this.cardBin,
                                saveCard: this.saveCard,
                                preferredScheme: this.preferredScheme,
                                source: METHOD_ID
                            };

                            // Place the order
                            Utilities.placeOrder(payload, METHOD_ID);
                            Utilities.cleanCustomerShippingAddress();
                        }
                    }
                }
            }
        );
    }
);

/**
 * Checkout.com
 * Authorized and regulated as an electronic money institution
 * by the UK Financial Conduct Authority (FCA) under number 900816.
 *
 * PHP version 7
 *
 * @category  Magento2
 * @package   Checkout.com
 * @author    Platforms Development Team <platforms@checkout.com>
 * @copyright 2010-2019 Checkout.com
 * @license   https://opensource.org/licenses/mit-license.html MIT License
 * @link      https://docs.checkout.com/
 */

define('MediaLounge_Checkout/js/view/payment/method-renderer/checkoutcom_card_payment-mixin', 
    [
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'CheckoutCom_Magento2/js/frames/multi',
        'CheckoutCom_Magento2/js/frames/single',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Checkout/js/model/customer-email-validator',
        'Magento_CheckoutAgreements/js/model/agreement-validator',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'mage/translate',
        'framesjs'
    ],
    function ($, Component, Utilities, FramesMulti, FramesSingle, AdditionalValidators, EmailValidator, AgreementValidator, Customer, Quote, $t) {
        'use strict';

        const METHOD_ID = 'checkoutcom_card_payment';
        let cardholderName = '';

        var mixin = {
            /**
             * @return {integer}
             */
            isSaveCardEnabled: function () {
                return parseInt(this.getValue('save_card_option'), 10);
            },

            isAmex: false,

            classLoader: '__cko-loading',
            tmrLoader: null,
            tmrValidate: null,
            showLoader: function() {
                document.body.classList.add(this.classLoader);

                if (this.tmrLoader) {
                    clearTimeout(this.tmrLoader);
                }

                this.tmrLoader = setTimeout(() => {
                    document.body.classList.remove(this.classLoader);
                }, 5000);
            },
            hideLoader: function() {
                document.body.classList.remove(this.classLoader);

                if (this.tmrLoader) {
                    clearTimeout(this.tmrLoader);
                }
            },

            /**
             * Add events to Frames.
             * @return {void}
             */
            addFramesEvents: function () {
                var self = this;

                // Card validation changed event
                Frames.addEventHandler(
                    Frames.Events.CARD_VALIDATION_CHANGED,
                    function (event) {
                        self.showLoader();

                        // Move this code to a timeout to avoid blocking the page
                        if (self.tmrValidate) {
                            clearTimeout(self.tmrValidate);
                        }
                        self.tmrValidate = setTimeout(() => {
                            var valid = Frames.isCardValid() && Utilities.getBillingAddress() != null;

                            if (self.isAmex) {
                                return;
                            }

                            if (valid) {
                                Utilities.clearMessages(METHOD_ID);

                                // Add the card holder name
                                Frames.cardholder = {
                                    name: Utilities.getCustomerName()
                                };

                                // Submit the payment form
                                Frames.submitCard();
                            } else {
                                this.showErrorMessage();
                                self.hideLoader();
                            }

                            Utilities.allowPlaceOrder(self.buttonId, false);
                            self.tmrValidate = null;
                        }, 0);
                    }
                );

                // Card tokenized event
                Frames.addEventHandler(
                    Frames.Events.CARD_TOKENIZED,
                    function (event) {
                        // Store the card token and the card bin
                        self.cardToken = event.token;
                        self.cardBin =  event.bin;
                        self.hideLoader();

                        // Enable the submit form
                        Frames.enableSubmitForm();

                        // Enable place order button only when tokenized.
                        Utilities.allowPlaceOrder(self.buttonId, true);
                    }
                );

                // Show error message when entering an AMEX card
                Frames.addEventHandler(
                    Frames.Events.PAYMENT_METHOD_CHANGED,
                    function (event) {
                        Utilities.clearMessages(METHOD_ID);

                        if (event.paymentMethod && event.paymentMethod === "American Express") {
                            self.isAmex = true;
                            Utilities.showMessage('error', $t('Sorry, we do not accept American Express cards'), METHOD_ID)
                            Utilities.allowPlaceOrder(self.buttonId, false);
                        } else {
                            self.isAmex = false;
                        }
                    }
                );
            },

            /**
             * @return {void}
             */
            placeOrder: function () {
                if (typeof grecaptcha !== 'undefined') {
                    window.placeOrder = this.placeOrderSim.bind(this);
                    grecaptcha.reset(window.checkoutRecaptchaWidget);
                    grecaptcha.execute(window.checkoutRecaptchaWidget);
                    return false;
                }

                if (Utilities.methodIsSelected(METHOD_ID)) {
                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: this.cardToken,
                            cardBin: this.cardBin,
                            saveCard: this.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);
                    } else {
                        this.showErrorMessage();
                    }
                }
            },

            placeOrderSim: function () {
                if (Utilities.methodIsSelected(METHOD_ID)) {
                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: this.cardToken,
                            cardBin: this.cardBin,
                            saveCard: this.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);
                        window.placeOrder = null;
                    } else {
                        this.showErrorMessage();
                    }
                }
            },

            showErrorMessage: function() {
                let errorMessage = false;

                if (!Frames.isCardValid()) {
                    errorMessage = $t('Please complete your card details');
                }

                if (!errorMessage) {
                    AdditionalValidators.getValidators().forEach(v => {
                        if (!v.validate() && !errorMessage) {
                            if (v === EmailValidator) {
                                errorMessage = $t('Please confirm your email address');
                                this.goToErrorField('customer-email');
                            }

                            if (v === AgreementValidator) {
                                errorMessage = $t('Please accept our terms & conditions');
                                this.goToErrorField('agreement_checkoutcom_card_payment_1');
                            }
                        }
                    });
                }


                if (errorMessage) {
                    Utilities.showMessage('error', errorMessage, METHOD_ID);
                }
            },

            goToErrorField: function(elementId) {
                const elErrorField = document.getElementById(elementId);

                if (elErrorField) {
                    elErrorField.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
                    setTimeout(() => {
                        elErrorField.focus({
                            focusVisible: true
                        });
                    }, 450)

                }
            }
        };

        return function(target) {
            return target.extend(mixin);
        }
    });

define('MediaLounge_Coinify/js/view/payment/method-renderer/coinify', 
    [
        'Magento_Checkout/js/view/payment/default',
        'Magento_Checkout/js/action/redirect-on-success',
        'mage/url',
        'Magento_Checkout/js/model/totals',
        'Magento_Checkout/js/model/payment/additional-validators',
        'underscore'
    ],
    function (
        Component,
        redirectOnSuccessAction,
        url,
        totals,
        additionalValidators,
        _
    ) {
        'use strict';

        return Component.extend({
            defaults: {
                template: 'MediaLounge_Coinify/payment/form',
                transactionResult: '',
                isBelowMinimum: false,
                totals: totals.totals,
                tracks: {
                    isBelowMinimum: true
                }
            },
            redirectAfterPlaceOrder: true,

            initObservable: function () {
                this._super().observe(['transactionResult']);
                return this;
            },

            placeOrder: function () {
                var self = this;

                redirectOnSuccessAction.redirectUrl = 'coinify/result/pay';

                if (this.validate() &&
                    additionalValidators.validate() &&
                    this.isPlaceOrderActionAllowed() === true
                ) {
                    this.getPlaceOrderDeferredObject()
                        .done(
                            function () {
                                self.afterPlaceOrder();

                                if (self.redirectAfterPlaceOrder) {
                                    redirectOnSuccessAction.execute();
                                }
                            }
                        ).always(
                            function () {
                                self.isPlaceOrderActionAllowed(true);
                            }
                        );
                }

                return false;
            },

            getCode: function () {
                return 'coinify';
            },

            getData: function () {
                return {
                    'method': this.item.method,
                    'additional_data': {
                        'transaction_result': this.transactionResult()
                    }
                };
            },

            getTransactionResults: function () {
                return _.map(window.checkoutConfig.payment.coinify.transactionResults, function (value, key) {
                    return {
                        'value': key,
                        'transaction_result': value
                    }
                });
            },

            getCartUrl: function() {
                return url.build('checkout/cart');
            },

            getTermsUrl: function() {
                return url.build('crypto-tcs');
            },

            getIconSrc: function() {
                return window.checkoutConfig.payment.coinify.iconSrc;
            }
        });
    }
);

define('text!Magento_Checkout/template/summary/discountwrapper.html', function() {
    return '<!-- ko if: isDisplayed() -->\n<tr class="totals discounts-wrapper">\n    <td colspan="2">\n        <div class="discounts-wrapper_frame">\n            <span class="discounts-wrapper_title" data-bind="i18n: \'Discounts\'"></span>\n\n            <table class="discounts-wrapper_table">\n                <!-- ko foreach: elems() -->\n                    <!-- ko template: getTemplate() --><!-- /ko -->\n                <!-- /ko -->\n            </table>\n        </div>\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/summary/grand-total.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isDisplayed() -->\n<tr class="grand totals">\n    <td class="mark" scope="row">\n        <strong data-bind="i18n: title"></strong>\n    </td>\n    <td class="amount" data-bind="attr: {\'data-th\': $t(title)}">\n        <strong><span class="price" data-bind="text: getValue()"></span></strong>\n        <!-- ko foreach: elems() -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n        <!-- /ko -->\n    </td>\n</tr>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/summary/shipping.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: quoteIsVirtual == 0 -->\n    <tr class="totals shipping excl">\n        <th class="mark" scope="row">\n            <span class="label" data-bind="i18n: title"></span>\n            <span class="value" data-bind="text: getShippingMethodTitle()"></span>\n        </th>\n        <td class="amount">\n            <!-- ko if: isCalculated() -->\n            <span class="price"\n                  data-bind="text: getValue(), attr: {\'data-th\': title}"></span>\n            <!-- /ko -->\n            <!-- ko ifnot: isCalculated() -->\n            <span class="not-calculated"\n                  data-bind="text: getValue(), attr: {\'data-th\': title}"></span>\n            <!-- /ko -->\n        </td>\n    </tr>\n<!-- /ko -->\n';
});
define('text!Magento_Checkout/template/summary/subtotal.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n\n<tr class="totals">\n    <th class="mark" scope="row" data-bind="text: title"></th>\n    <td class="amount">\n        <span class="price" data-bind ="text: getValue(), attr:{\'data-label\': title}"></span>\n        <!-- ko foreach: elems() -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n        <!-- /ko -->\n    </td>\n</tr>\n';
});
define('text!Magento_Checkout/template/summary/item/details.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="product-image">\n<!-- ko foreach: getRegion(\'before_details\') -->\n    <!-- ko template: getTemplate() --><!-- /ko -->\n<!-- /ko -->\n</div>\n\n<div class="product-item-details">\n\n    <div class="product-item-inner">\n        <div class="product-item-name-block">\n            <strong class="product-item-name" data-bind="html: $parent.name"></strong>\n            <div class="details-qty">\n                <span class="label"><!-- ko i18n: \'Quantity\' --><!-- /ko -->:</span>\n                <span class="value" data-bind="text: $parent.qty"></span>\n            </div>\n        </div>\n        <!-- ko foreach: getRegion(\'after_details\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n        <!-- /ko -->\n    </div>\n\n    <!-- ko if: $parent.qty > 1 -->\n    <div class="product-item-warning __qty">\n        <span data-bind="i18n: \'Note: Multiple items in your cart for this product\'"></span>\n    </div>\n    <!-- /ko -->\n\n    <!-- ko foreach: getRegion(\'item_message\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n    <!-- /ko -->\n</div>\n';
});
define('text!ui/template/group/group.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<fieldset class="field" data-bind="css: additionalClasses">\n    <legend class="label">\n        <span translate="element.label"></span>\n    </legend>\n    <div class="control">\n        <!-- ko foreach: { data: elems, as: \'element\' } -->\n\n            <!-- ko if: element.visible() -->\n\n                <!-- ko ifnot: (element.input_type == \'checkbox\' || element.input_type == \'radio\') -->\n                    <!-- ko template: $parent.fieldTemplate --><!-- /ko -->\n                <!-- /ko -->\n\n                <!-- ko if: (element.input_type == \'checkbox\' || element.input_type == \'radio\') -->\n                    <!-- ko template: element.elementTmpl --><!-- /ko -->\n                <!-- /ko -->\n\n            <!-- /ko -->\n\n        <!-- /ko -->\n\n        <!-- ko if: validateWholeGroup -->\n        <!-- ko  foreach: { data: elems, as: \'element\' } -->\n            <!-- ko if: element.error() && element.visible() -->\n                <label class="error" data-bind="attr: { for: uid }, text: element.error"></label>\n            <!-- /ko -->\n        <!-- /ko -->\n        <!-- /ko -->\n    </div>\n</fieldset>\n';
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_CheckoutAgreements/js/model/set-payment-information-mixin', [
    'jquery',
    'mage/utils/wrapper',
    'Magento_CheckoutAgreements/js/model/agreements-assigner'
], function ($, wrapper, agreementsAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override place-order-mixin for set-payment-information action as they differs only by method signature */
        return wrapper.wrap(placeOrderAction, function (originalAction, messageContainer, paymentData) {
            agreementsAssigner(paymentData);

            return originalAction(messageContainer, paymentData);
        });
    };
});

define('text!Magento_Checkout/template/payment/before-place-order.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko foreach: { data: elems, as: \'element\' } -->\n<!-- ko if: hasTemplate() -->\n<!-- ko template: getTemplate() --><!-- /ko -->\n<!-- /ko -->\n<!-- /ko -->\n';
});
define('text!MediaLounge_Coinify/template/payment/form.html', function() {
    return '<div class="payment-method" data-bind="css: {\'_active\': (getCode() == isChecked())}">\n    <div class="payment-method-title field choice">\n        <input class="radio"\n               data-bind="attr: {\'id\': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"\n               name="payment[method]"\n               type="radio">\n        <label class="label" data-bind="attr: {\'for\': getCode()}">\n            <img data-bind="attr: {src: getIconSrc(), alt: getTitle()}" class="payment-icon" style="height:44px;">\n            <span data-bind="text: getTitle()"></span>\n        </label>\n    </div>\n\n    <div class="payment-method-content">\n        <div class="payment-method-content-error">\n            <span data-bind="i18n: \'*Please note there are strict limits on Cryptocurrency payment amounts and refunds, and we cannot be held responsible for underpayments and/or lost payments. Using this payment method is at your own risk.\'"></span>\n            <a target="_blank" data-bind="attr: {href: getTermsUrl()}"><span data-bind="i18n: \'Terms & Conditions\'"></span></a>\n        </div>\n        <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n        <div class="payment-method-billing-address">\n            <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <div class="checkout-agreements-block">\n            <!-- ko foreach: $parent.getRegion(\'before-place-order\') -->\n            <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n        <div class="actions-toolbar">\n            <div class="primary">\n                <button class="action primary checkout"\n                        data-bind="\n                        click: placeOrder,\n                        attr: {title: $t(\'Place Order Securely\')}\n                        "\n                        type="submit">\n                    <span data-bind="i18n: \'Place Order Securely\'"></span>\n                </button>\n            </div>\n        </div>\n    </div>\n</div>\n';
});
define('text!MediaLounge_DoublePoints/template/payment/checkoutcom_card_payment.html', function() {
    return '<!--\n/**\n * Checkout.com Magento 2 Magento2 Payment.\n *\n * PHP version 7\n *\n * @category  Checkout.com\n * @package   Magento2\n * @author    Checkout.com Development Team <integration@checkout.com>\n * @copyright 2019 Checkout.com all rights reserved\n * @license   https://opensource.org/licenses/mit-license.html MIT License\n * @link      https://www.checkout.com\n */\n-->\n\n<div class="payment-method" data-bind="css: {\'_active\': (getCode() == isChecked())}, attr: {\'id\': getCode() + \'_container\', afterRender: initEvents()}">\n    <!-- ko if: isDoublePoints -->\n    <div class="double-points-tooltip">\n        <div class="icon">\n            <svg width="35" height="34" viewBox="0 0 35 34" fill="none" xmlns="http://www.w3.org/2000/svg">\n                <path d="M13.4351 22.944C11.9433 23.3068 10.7142 23.7601 9.83645 24.3037C9.13376 24.6665 8.78359 25.1198 8.78359 25.4814C8.78359 26.207 9.83645 26.9315 11.592 27.5655C13.6102 28.2912 16.4186 28.6528 19.4908 28.6528C22.563 28.6528 25.3714 28.29 27.3896 27.5655C29.1452 26.9315 30.198 26.2058 30.198 25.4814C30.198 24.9378 29.3203 24.3037 28.0036 23.6685C26.4243 23.0344 24.2299 22.5812 21.6841 22.3992L21.509 22.8524C20.8063 24.1217 18.8757 24.3929 16.4186 23.8493C15.4533 23.6685 14.488 23.3972 13.4351 22.944ZM29.6716 10.1643L29.1452 8.08014C28.2674 8.53337 27.3021 8.8962 26.2492 9.34943L26.7757 11.4336C27.8285 10.9803 28.7938 10.6175 29.6716 10.1643ZM30.4607 7.26408L30.9871 9.34823L31.2509 9.16742C32.7427 8.17055 33.6204 7.17367 33.4453 6.44802L33.094 5.17873C32.6551 5.72236 31.9536 6.35641 31.1634 6.90125C30.8996 6.99286 30.7245 7.17367 30.4607 7.26408ZM25.3714 11.9772L24.845 9.80146C24.3186 9.98227 23.8797 10.1643 23.3533 10.2547C22.8268 10.4355 22.3879 10.5271 21.8615 10.6175L22.3879 12.7933C22.9144 12.6125 23.3533 12.5209 23.8797 12.34C24.405 12.2496 24.9326 12.0676 25.3714 11.9772ZM12.3822 10.8899L12.7336 12.1592C12.9087 12.8849 14.1378 13.2465 15.9809 13.4285H16.2447L15.7182 11.3444C15.4544 11.3444 15.1918 11.3444 15.0156 11.3444C13.9615 11.2528 13.1713 11.1612 12.3822 10.8899ZM17.8228 13.4273C18.7881 13.3369 19.841 13.2465 20.895 13.0645L20.3686 10.9803C19.3157 11.1612 18.2617 11.2528 17.2964 11.3432L17.8228 13.4273ZM33.9718 2.46053L34.9371 6.0864C35.2884 7.4461 34.1469 9.07701 32.0411 10.5271C30.198 11.7964 27.3896 13.0645 24.3174 13.8806C23.4396 14.153 22.5619 14.3338 21.6841 14.5146C22.2981 15.2403 22.8245 15.9647 23.0883 16.5987C23.7023 17.7764 23.791 18.7745 23.2634 19.5894L22.5607 20.9491C24.9302 21.1299 26.9484 21.5831 28.5289 22.2184C30.5471 23.0344 31.6886 24.2121 31.6886 25.4814V29.2881C31.6886 30.7382 30.2844 32.0075 27.8273 32.8223C25.7205 33.548 22.7369 34 19.4896 34C16.2423 34 13.2588 33.5468 11.1519 32.8223C8.69604 32.0075 7.29184 30.7382 7.29184 29.2881V25.4814C7.29184 24.4845 7.90581 23.5781 9.04739 22.944C9.66136 22.5812 10.3641 22.2184 11.1543 21.9471C10.2765 21.5843 9.48628 21.1311 8.60967 20.5874C5.80125 18.9565 3.43173 17.0532 1.93998 15.2403C0.270802 13.3369 -0.431886 11.4336 0.270801 10.1643L2.1139 6.90125C2.64033 5.90438 3.95699 5.54155 5.71254 5.63196C7.11675 5.72236 8.78476 6.266 10.7154 6.99166C11.1543 6.1756 12.0321 5.26913 13.1725 4.54468C15.1031 3.18498 17.824 2.0073 20.9837 1.10084C24.1435 0.284775 27.127 -0.0768471 29.3214 0.0135584C31.8649 0.195575 33.6204 1.01043 33.9718 2.46053ZM19.8422 14.787C18.438 14.9678 17.0337 15.0594 15.8933 14.9678C13.4363 14.787 11.6807 13.971 11.2418 12.6113L10.3641 8.9854C10.2765 8.80459 10.2765 8.62257 10.2765 8.53217C8.52096 7.80651 6.85412 7.35449 5.625 7.26287C4.48459 7.17247 3.69436 7.26287 3.43056 7.71611C3.07922 8.35015 3.69436 9.52904 4.92231 10.9791C6.23897 12.6101 8.43341 14.3326 11.0656 15.9635H11.1531C13.874 17.5944 16.5061 18.6829 18.5255 19.1361C20.3686 19.499 21.5977 19.4086 21.9479 18.7733C22.123 18.5009 22.0354 17.9572 21.7728 17.3232C21.4215 16.6 20.7199 15.6935 19.8422 14.787ZM30.2856 5.54276C31.8649 4.54589 32.6551 3.54902 32.48 2.82336C32.3049 2.18932 31.0758 1.73608 29.2327 1.64568C27.1258 1.46487 24.3174 1.82649 21.3339 2.64255C18.3504 3.45861 15.8046 4.63629 14.0491 5.81518C12.4698 6.90246 11.6795 7.89933 11.8546 8.53458C12.0297 9.26023 13.2588 9.62186 15.1019 9.80387C17.2088 9.89428 20.0172 9.62306 23.0007 8.71659C25.9854 7.89933 28.53 6.81085 30.2856 5.54276ZM3.2543 14.4242L4.21962 12.6113C4.04454 12.3388 3.86828 12.158 3.78074 11.9772C3.07805 11.2516 2.55162 10.5271 2.28898 9.80146L1.5863 10.9791C1.23495 11.6132 1.8501 12.7921 3.07805 14.2422L3.2543 14.4242ZM5.3612 13.6997L4.39588 15.5127C5.09857 16.2383 5.88763 16.8724 6.76541 17.5064L7.81827 15.6935C6.94049 14.9678 6.15026 14.3338 5.3612 13.6997ZM9.13493 16.5083L8.08207 18.4117C8.43341 18.6841 8.8723 18.9553 9.31119 19.2277H9.39873C9.83762 19.5002 10.2765 19.7714 10.7154 20.0438L11.7683 18.1405C11.3294 17.9597 10.978 17.6872 10.6279 17.5064L10.4528 17.3256C9.924 17.0532 9.48628 16.7808 9.13493 16.5083ZM13.0838 18.7745L12.0309 20.6778C13.0838 21.2215 14.0491 21.5843 14.9268 21.8555L15.9797 20.0426C15.1031 19.681 14.1378 19.3181 13.0838 18.7745ZM17.4726 20.497L16.5073 22.31H16.6824C18.5255 22.7632 19.8422 22.6728 20.1935 22.0375L20.8075 20.8599C20.1048 20.9503 19.2282 20.8599 18.2629 20.6791C17.9991 20.5874 17.7353 20.497 17.4726 20.497ZM11.8558 31.3722V29.2881C11.592 29.1977 11.3294 29.1073 11.1531 29.0156C10.1878 28.7432 9.39756 28.3816 8.78359 27.9284V29.2881C8.78359 30.0137 9.83645 30.7382 11.592 31.2818L11.8558 31.3722ZM13.3476 29.6509V31.8267C14.3129 32.0075 15.3657 32.1895 16.4198 32.2799V30.1041C15.3657 30.0125 14.3129 29.8317 13.3476 29.6509ZM17.9991 30.1945V32.3703C18.438 32.4607 18.9644 32.4607 19.4908 32.4607C20.0172 32.4607 20.5437 32.4607 20.9826 32.3703V30.1945C20.5437 30.2849 20.0172 30.2849 19.4908 30.2849C18.9644 30.2849 18.438 30.2849 17.9991 30.1945ZM22.563 30.1041V32.2799C23.6159 32.1895 24.6699 32.0075 25.6352 31.8267V29.6509C24.6688 29.8317 23.6159 30.0137 22.563 30.1041ZM27.1258 29.2881V31.3722L27.3896 31.2818C29.1452 30.7382 30.198 30.0125 30.198 29.2881V27.9284C29.5841 28.3816 28.7938 28.7444 27.8285 29.0156C27.6523 29.1073 27.3896 29.1977 27.1258 29.2881Z" fill="#FFF597"/>\n            </svg>\n        </div>\n        <div class="text">\n            <strong data-bind="i18n: \'Earn double cdkoins\'"></strong>\n            <span data-bind="i18n: \'When selecting this payment method\'"></span>\n        </div>\n\n    </div>\n    <!-- /ko -->\n    <div class="payment-method-title field choice">\n        <input type="radio"\n               name="payment[method]"\n               class="radio"\n               data-bind="attr: {\'id\': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()">\n        <label data-bind="attr: {\'for\': getCode()}" class="label">\n            <span data-bind="text: getTitle()"></span>\n        </label>\n\n        <!-- Card Icons -->\n        <!-- ko if: shouldDisplayCardIcons()-->\n            <!-- ko foreach: {data: getCardIcons(), as: \'card\'} -->\n            <img data-bind="attr: {\'src\': card.url, \'alt\': card.name}" style="display:inline-block; vertical-align:-50%; line-height: 14px; margin-left: 4px">\n            <!--/ko-->\n        <!--/ko-->\n    </div>\n    <div class="payment-method-content">\n        <!-- Messages -->\n        <!-- ko foreach: getRegion(\'messages\') -->\n        <!-- ko template: getTemplate() --><!-- /ko -->\n        <!--/ko-->\n\n        <div class="payment-method-messages checkout-messages">\n            <div class="message message-cko" data-bind="attr: {\'id\': (getCode()+\'_message\')}"></div>\n            <div class="message message-response-code" data-bind="attr: {\'id\': (getCode()+\'_message\')}"></div>\n            <div class="message debug-message" data-bind="attr: {\'id\': (getCode()+\'_message\')}"></div>\n        </div>\n\n        <!-- Card form -->\n        <div class="frames-container">\n            <form method="POST" data-bind="attr: {\'id\': formId}">\n                <!-- ko if: (getFormLayout() == \'single\') -->\n                    <div class="one-liner">\n                        <div class="card-frame" data-bind="afterRender: handleFormState()">\n                            <!-- Form will be added here -->\n                        </div>\n                    </div>\n                    <p class="error-message"></p>\n                <!-- /ko -->\n                <!-- ko if: (getFormLayout() == \'multi\') -->\n                    <div data-bind="afterRender: handleFormState()">\n                        <!-- Card number field-->\n                        <label for="card-number">\n                            <!-- ko i18n: \'Card number\'--><!-- /ko -->\n                        </label>\n                        <div class="input-container card-number">\n                            <div class="icon-container">\n                                <img id="icon-card-number" data-bind="attr: {alt: $t(\'PAN\'), src: getImagesPath() + \'/frames/multi/card.svg\'}">\n                            </div>\n                            <div class="card-number-frame"></div>\n                            <div class="icon-container payment-method">\n                                <img id="logo-payment-method">\n                            </div>\n                            <div class="icon-container">\n                                <img id="icon-card-number-error" data-bind="attr: {src: getImagesPath() + \'/frames/multi/error.svg\'}">\n                            </div>\n                        </div>\n\n                        <!-- Date and code fields -->\n                        <div class="date-and-code">\n                            <!-- Date field -->\n                            <div>\n                                <label for="expiry-date">\n                                    <!-- ko i18n: \'Expiry date\'--><!-- /ko -->\n                                </label>\n                                <div class="input-container expiry-date">\n                                    <div class="icon-container">\n                                        <img id="icon-expiry-date" data-bind="attr: {alt: $t(\'Expiry date\'), src: getImagesPath() + \'/frames/multi/exp-date.svg\'}">\n                                    </div>\n                                    <div class="expiry-date-frame"></div>\n                                    <div class="icon-container">\n                                        <img id="icon-expiry-date-error" data-bind="attr: {src: getImagesPath() + \'/frames/multi/error.svg\'}">\n                                    </div>\n                                </div>\n                            </div>\n\n                            <!-- Code field -->\n                            <div>\n                                <label for="cvv">\n                                    <!-- ko i18n: \'Security code\'--><!-- /ko -->\n                                </label>\n                                <div class="input-container cvv">\n                                    <div class="icon-container">\n                                        <img id="icon-cvv" data-bind="attr: {alt: $t(\'CVV\'), src: getImagesPath() + \'/frames/multi/cvv.svg\'}">\n                                    </div>\n                                    <div class="cvv-frame"></div>\n                                    <div class="icon-container">\n                                        <img id="icon-cvv-error" data-bind="attr: {src: getImagesPath() + \'/frames/multi/error.svg\'}">\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                    <div>\n                        <span class="error-message error-message__card-number"></span>\n                        <span class="error-message error-message__expiry-date"></span>\n                        <span class="error-message error-message__cvv"></span>\n                    </div>\n                <!-- /ko -->\n            </form>\n        </div>\n\n        <!-- Billing form -->\n        <div class="payment-method-billing-address">\n            <!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->\n                <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n\n        <!-- ko if: (isVaultEnabled() && isSaveCardEnabled() && isLoggedIn()) -->\n            <div class="field choice save-card-option">\n                <input type="checkbox" name="saveCard" id="saveCard" class="checkbox">\n                <label class="label" for="saveCard">\n                    <span><!-- ko i18n: \'Save this card for later use.\'--><!-- /ko --></span>\n                </label>\n            </div>\n        <!-- /ko -->\n\n        <!-- Agreements form -->\n        <div class="checkout-agreements-block">\n            <!-- ko foreach: $parent.getRegion(\'before-place-order\') -->\n                <!-- ko template: getTemplate() --><!-- /ko -->\n            <!--/ko-->\n        </div>\n\n        <!-- Actions -->\n        <div class="actions-toolbar">\n            <div class="primary">\n                <button class="action primary checkout"\n                        type="submit"\n                        data-bind="\n                        click: placeOrder,\n                        attr: {title: $t(\'Place Order\'), \'id\': buttonId}\n                        ">\n                    <span data-bind="i18n: \'Place Order\'"></span>\n                </button>\n            </div>\n        </div>\n    </div>\n</div>\n';
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/set-payment-information-extended', [
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/action/get-totals',
    'Magento_Checkout/js/model/full-screen-loader',
    'underscore',
    'Magento_Checkout/js/model/payment/place-order-hooks'
], function (quote, urlBuilder, storage, errorProcessor, customer, getTotalsAction, fullScreenLoader, _, hooks) {
    'use strict';

    /**
     * Filter template data.
     *
     * @param {Object|Array} data
     */
    var filterTemplateData = function (data) {
        return _.each(data, function (value, key, list) {
            if (_.isArray(value) || _.isObject(value)) {
                list[key] = filterTemplateData(value);
            }

            if (key === '__disableTmpl' || key === 'title') {
                delete list[key];
            }
        });
    };

    return function (messageContainer, paymentData, skipBilling) {
        var serviceUrl,
            payload,
            headers = {};

        paymentData = filterTemplateData(paymentData);
        skipBilling = skipBilling || false;
        payload = {
            cartId: quote.getQuoteId(),
            paymentMethod: paymentData
        };

        /**
         * Checkout for guest and registered customer.
         */
        if (!customer.isLoggedIn()) {
            serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/set-payment-information', {
                cartId: quote.getQuoteId()
            });
            payload.email = quote.guestEmail;
        } else {
            serviceUrl = urlBuilder.createUrl('/carts/mine/set-payment-information', {});
        }

        if (skipBilling === false) {
            payload.billingAddress = quote.billingAddress();
        }

        fullScreenLoader.startLoader();

        _.each(hooks.requestModifiers, function (modifier) {
            modifier(headers, payload);
        });

        return storage.post(
            serviceUrl, JSON.stringify(payload), true, 'application/json', headers
        ).fail(
            function (response) {
                errorProcessor.process(response, messageContainer);
            }
        ).always(
            function () {
                fullScreenLoader.stopLoader();
                _.each(hooks.afterRequestListeners, function (listener) {
                    listener();
                });
            }
        );
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define('Magento_Checkout/js/action/set-payment-information', [
    'Magento_Checkout/js/action/set-payment-information-extended'

], function (setPaymentInformationExtended) {
    'use strict';

    return function (messageContainer, paymentData) {

        return setPaymentInformationExtended(messageContainer, paymentData, false);
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Paypal/js/action/set-payment-method', [
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/action/set-payment-information'
], function (quote, setPaymentInformation) {
    'use strict';

    return function (messageContainer) {
        return setPaymentInformation(messageContainer, quote.paymentMethod());
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract', [
    'jquery',
    'Magento_Checkout/js/view/payment/default',
    'Magento_Paypal/js/action/set-payment-method',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Checkout/js/model/quote',
    'Magento_Customer/js/customer-data'
], function ($, Component, setPaymentMethodAction, additionalValidators, quote, customerData) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Paypal/payment/payflow-express-bml',
            billingAgreement: ''
        },

        /** Init observable variables */
        initObservable: function () {
            this._super()
                .observe('billingAgreement');

            return this;
        },

        /** Open window with  */
        showAcceptanceWindow: function (data, event) {
            window.open(
                $(event.currentTarget).attr('href'),
                'olcwhatispaypal',
                'toolbar=no, location=no,' +
                ' directories=no, status=no,' +
                ' menubar=no, scrollbars=yes,' +
                ' resizable=yes, ,left=0,' +
                ' top=0, width=400, height=350'
            );

            return false;
        },

        /** Returns payment acceptance mark link path */
        getPaymentAcceptanceMarkHref: function () {
            return window.checkoutConfig.payment.paypalExpress.paymentAcceptanceMarkHref;
        },

        /** Returns payment acceptance mark image path */
        getPaymentAcceptanceMarkSrc: function () {
            return window.checkoutConfig.payment.paypalExpress.paymentAcceptanceMarkSrc;
        },

        /** Returns billing agreement data */
        getBillingAgreementCode: function () {
            return window.checkoutConfig.payment.paypalExpress.billingAgreementCode[this.item.method];
        },

        /** Returns payment information data */
        getData: function () {
            var parent = this._super(),
                additionalData = null;

            if (this.getBillingAgreementCode()) {
                additionalData = {};
                additionalData[this.getBillingAgreementCode()] = this.billingAgreement();
            }

            return $.extend(true, parent, {
                'additional_data': additionalData
            });
        },

        /** Redirect to paypal */
        continueToPayPal: function () {
            if (additionalValidators.validate()) {
                //update payment method information if additional data was changed
                setPaymentMethodAction(this.messageContainer).done(
                    function () {
                        customerData.invalidate(['cart']);
                        $.mage.redirect(
                            window.checkoutConfig.payment.paypalExpress.redirectUrl[quote.paymentMethod().method]
                        );
                    }
                );

                return false;
            }
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('MediaLounge_PaypalCards/js/view/payment/method-renderer/paypal-express-card', [
    'jquery',
    'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract',
    'Magento_Paypal/js/in-context/express-checkout-wrapper',
    'Magento_Paypal/js/action/set-payment-method',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Ui/js/model/messageList',
    'Magento_Ui/js/lib/view/utils/async'
], function ($, Component, Wrapper, setPaymentMethod, additionalValidators, messageList) {
    'use strict';

    return Component.extend(Wrapper).extend({
        defaults: {
            template: 'MediaLounge_PaypalCards/payment/paypal-express-card',
            validationElements: 'input'
        },

        getPaymentAcceptanceMarkSrc: function () {
            return window.checkoutConfig.payment.paypalExpressCard.paymentAcceptanceMarkSrc;
        },

        /**
         * Listens element on change and validate it.
         *
         * @param {HTMLElement} context
         */
        initListeners: function (context) {
            $.async(this.validationElements, context, function (element) {
                $(element).on('change', function () {
                    this.validate();
                }.bind(this));
            }.bind(this));
        },

        /**
         *  Validates Smart Buttons
         */
        validate: function () {
            this._super();

            if (this.actions) {
                additionalValidators.validate(true) ? this.actions.enable() : this.actions.disable();
            }
        },

        /** @inheritdoc */
        beforePayment: function (resolve, reject) {
            var promise = $.Deferred();

            setPaymentMethod(this.messageContainer).done(function () {
                return promise.resolve();
            }).fail(function (response) {
                var error;

                try {
                    error = JSON.parse(response.responseText);
                } catch (exception) {
                    error = this.paymentActionError;
                }

                this.addError(error);

                return reject(new Error(error));
            }.bind(this));

            return promise;
        },

        /**
         * Populate client config with all required data
         *
         * @return {Object}
         */
        prepareClientConfig: function () {
            this._super();
            this.clientConfig.quoteId = window.checkoutConfig.quoteData['entity_id'];
            this.clientConfig.customerId = window.customerData.id;
            this.clientConfig.button = 0;

            return this.clientConfig;
        },

        /**
         * Adding logic to be triggered onClick action for smart buttons component
         */
        onClick: function () {
            additionalValidators.validate();
        },

        /**
         * Adds error message
         *
         * @param {String} message
         */
        addError: function (message) {
            messageList.addErrorMessage({
                message: message
            });
        },

        /**
         * After payment execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         *
         * @return {*}
         */
        afterPayment: function (res, resolve, reject) {
            if (res.success) {
                return resolve(res.token);
            }

            this.addError(res['error_message']);

            return reject(new Error(res['error_message']));
        },

        /**
         * After onAuthorize execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         * @param {Object} actions
         *
         * @return {*}
         */
        afterOnAuthorize: function (res, resolve, reject, actions) {
            $('body').trigger('processStop');

            if (res.success) {
                resolve();

                return actions.redirect(res.redirectUrl);
            }

            this.addError(res['error_message']);
            return reject(new Error(res['error_message']));
        },

        getBillingAgreementCode: function () {
            return false;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_Paypal/js/view/payment/method-renderer/in-context/checkout-express', [
    'jquery',
    'Magento_Paypal/js/view/payment/method-renderer/paypal-express-abstract',
    'Magento_Paypal/js/in-context/express-checkout-wrapper',
    'Magento_Paypal/js/action/set-payment-method',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Ui/js/model/messageList',
    'Magento_Ui/js/lib/view/utils/async'
], function ($, Component, Wrapper, setPaymentMethod, additionalValidators, messageList) {
    'use strict';

    return Component.extend(Wrapper).extend({
        defaults: {
            template: 'Magento_Paypal/payment/paypal-express-in-context',
            validationElements: 'input'
        },

        /**
         * Listens element on change and validate it.
         *
         * @param {HTMLElement} context
         */
        initListeners: function (context) {
            $.async(this.validationElements, context, function (element) {
                $(element).on('change', function () {
                    this.validate();
                }.bind(this));
            }.bind(this));
        },

        /**
         *  Validates Smart Buttons
         */
        validate: function () {
            this._super();

            if (this.actions) {
                additionalValidators.validate(true) ? this.actions.enable() : this.actions.disable();
            }
        },

        /** @inheritdoc */
        beforePayment: function (resolve, reject) {
            var promise = $.Deferred();

            setPaymentMethod(this.messageContainer).done(function () {
                return promise.resolve();
            }).fail(function (response) {
                var error;

                try {
                    error = JSON.parse(response.responseText);
                } catch (exception) {
                    error = this.paymentActionError;
                }

                this.addError(error);

                return reject(new Error(error));
            }.bind(this));

            return promise;
        },

        /**
         * Populate client config with all required data
         *
         * @return {Object}
         */
        prepareClientConfig: function () {
            this._super();
            this.clientConfig.quoteId = window.checkoutConfig.quoteData['entity_id'];
            this.clientConfig.customerId = window.customerData.id;
            this.clientConfig.button = 0;

            return this.clientConfig;
        },

        /**
         * Adding logic to be triggered onClick action for smart buttons component
         */
        onClick: function () {
            additionalValidators.validate();
        },

        /**
         * Adds error message
         *
         * @param {String} message
         */
        addError: function (message) {
            messageList.addErrorMessage({
                message: message
            });
        },

        /**
         * After payment execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         *
         * @return {*}
         */
        afterPayment: function (res, resolve, reject) {
            if (res.success) {
                return resolve(res.token);
            }

            this.addError(res['error_message']);

            return reject(new Error(res['error_message']));
        },

        /**
         * After onAuthorize execute
         *
         * @param {Object} res
         * @param {Function} resolve
         * @param {Function} reject
         * @param {Object} actions
         *
         * @return {*}
         */
        afterOnAuthorize: function (res, resolve, reject, actions) {
            if (res.success) {
                resolve();

                return actions.redirect(res.redirectUrl);
            }

            this.addError(res['error_message']);

            return reject(new Error(res['error_message']));
        }
    });
});

define('text!Magento_Checkout/template/summary/item/details/subtotal.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<span class="subtotal" data-bind="text: getValue($parents[1])"></span>\n';
});
define('text!Magento_Checkout/template/summary/item/details/thumbnail.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<span class="product-image-container"\n      data-bind="attr: {\'style\': \'height: \' + getHeight($parents[1])/2 + \'px; width: \' + getWidth($parents[1])/2 + \'px;\' }">\n    <span class="product-image-wrapper">\n        <img\n            data-bind="attr: {\'src\': getSrc($parents[1]), \'width\': getWidth($parents[1]), \'height\': getHeight($parents[1]), \'alt\': getAlt($parents[1]), \'title\': getAlt($parents[1]) }"/>\n    </span>\n</span>\n';
});
define('text!Magento_Checkout/template/summary/item/details/message.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="cart item message notice" if="getMessage($parents[1])">\n    <div data-bind="text: getMessage($parents[1])"></div>\n</div>\n';
});
define('text!Magento_CheckoutAgreements/template/checkout/checkout-agreements.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div data-role="checkout-agreements">\n    <div class="checkout-agreements fieldset" data-bind="visible: isVisible">\n        <!-- ko foreach: agreements -->\n            <!-- ko if: ($parent.isAgreementRequired($data)) -->\n            <div class="checkout-agreement field choice required">\n                <input type="checkbox" class="required-entry"\n                       data-bind="attr: {\n                                    \'id\': $parent.getCheckboxId($parentContext, agreementId),\n                                    \'name\': \'agreement[\' + agreementId + \']\',\n                                    \'value\': agreementId,\n                                    \'checked\': true\n                                    }"/>\n                <label class="label" data-bind="attr: {\'for\': $parent.getCheckboxId($parentContext, agreementId)}">\n                    <!-- <button type="button"\n                            class="action action-show"\n                            data-bind="click: function(data, event) { return $parent.showContent(data, event) }"\n                            >\n                        <span data-bind="html: checkboxText"></span>\n                    </button> -->\n\n                    <span data-bind="html: $parent.htmlDecode(checkboxText)"></span>\n                </label>\n            </div>\n            <!-- /ko -->\n            <!-- ko ifnot: ($parent.isAgreementRequired($data)) -->\n            <div class="checkout-agreement">\n                <!-- <button type="button" class="action action-show"\n                        data-bind="click: function(data, event) { return $parent.showContent(data, event) }">\n                    <span data-bind="html: checkboxText"></span>\n                </button> -->\n\n                <span data-bind="html: $parent.htmlDecode(checkboxText)"></span>\n            </div>\n            <!-- /ko -->\n        <!-- /ko -->\n        <div id="checkout-agreements-modal" data-bind="afterRender: initModal" style="display: none">\n            <div class="checkout-agreements-item-content" data-bind="html: modalContent, style: {height: contentHeight, overflow:\'auto\' }"></div>\n        </div>\n    </div>\n</div>\n';
});
define('text!Magento_Paypal/template/payment/paypal-express-in-context.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="payment-method" css="_active: getCode() == isChecked()" afterRender="initListeners">\n    <div class="payment-method-title field choice">\n        <input type="radio"\n               name="payment[method]"\n               class="radio"\n               attr="id: getCode()"\n               ko-value="getCode()"\n               ko-checked="isChecked"\n               click="selectPaymentMethod"\n               visible="isRadioButtonVisible()"/>\n        <label attr="for: getCode()" class="label">\n            <!-- PayPal Logo -->\n            <img attr="src: getPaymentAcceptanceMarkSrc(), alt: $t(\'Acceptance Mark\')" class="payment-icon"/>\n            <!-- PayPal Logo -->\n            <span text="getTitle()"/>\n        </label>\n    </div>\n    <div class="payment-method-content">\n        <!-- ko template: \'Magento_Paypal/payment/express/billing-agreement\' --><!-- /ko -->\n        <each args="getRegion(\'messages\')" render=""></each>\n        <div class="checkout-agreements-block">\n            <each args="$parent.getRegion(\'before-place-order\')" render=""></each>\n        </div>\n        <div class="actions-toolbar" attr="id: getButtonId()" afterRender="renderPayPalButtons"></div>\n        <div class="payment-method-extra-content">\n            <each args="$parent.getRegion(\'paypal-method-extra-content\')" render=""></each>\n        </div>\n    </div>\n</div>\n';
});
define('text!MediaLounge_PaypalCards/template/payment/paypal-express-card.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<div class="payment-method" css="_active: getCode() == isChecked()" afterRender="initListeners">\n    <div class="payment-method-title field choice">\n        <input type="radio"\n               name="payment[method]"\n               class="radio"\n               attr="id: getCode()"\n               ko-value="getCode()"\n               ko-checked="isChecked"\n               click="selectPaymentMethod"\n               visible="isRadioButtonVisible()"/>\n        <label attr="for: getCode()" class="label">\n            <!-- PayPal Logo -->\n            <img attr="src: getPaymentAcceptanceMarkSrc(), alt: $t(\'Acceptance Mark\')" class="payment-icon" style="height:44px;"/>\n            <!-- PayPal Logo -->\n            <span text="getTitle()"></span>\n        </label>\n    </div>\n    <div class="payment-method-content">\n        <each args="getRegion(\'messages\')" render=""></each>\n        <div class="checkout-agreements-block">\n            <each args="$parent.getRegion(\'before-place-order\')" render=""></each>\n        </div>\n        <div class="actions-toolbar --card" attr="id: getButtonId()" afterRender="renderPayPalButtons"></div>\n        <div class="payment-method-extra-content">\n            <each args="$parent.getRegion(\'paypal-method-extra-content\')" render=""></each>\n        </div>\n    </div>\n</div>\n';
});
define('text!Magento_Paypal/template/payment/express/billing-agreement.html', function() {
    return '<!--\n/**\n * Copyright \xA9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: getBillingAgreementCode() -->\n<div class="paypal-agreement-input">\n    <input type="checkbox"\n        data-bind=\'\n            attr: {id: getBillingAgreementCode(), name: "payment[" + getBillingAgreementCode() + "]"},\n            checked: billingAgreement\n            enable: isActive($parent) && getBillingAgreementCode(),\n            click: selectPaymentMethod\'\n        value="1" class="checkbox">\n    <label\n        data-bind=\'\n            attr: {for: getBillingAgreementCode()}\'\n        class="label">\n        <span><!-- ko i18n: \'Save your PayPal details for your next purchase\' --><!-- /ko --></span>\n    </label>\n</div>\n<!-- /ko -->\n';
});
