/**
 * 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_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.
 */

/**
 * 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.
 */
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_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-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.
 */

/**
 * @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_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.
 */

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

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

/**
 * 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_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;
        }
    };
});

/**
 * 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.
 */

/**
 * @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/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;

            if (response.status == 401) { //eslint-disable-line eqeqeq
                this.redirectTo(url.build('customer/account/login/'));
            } else {
                try {
                    error = JSON.parse(response.responseText);
                } catch (exception) {
                    error = {
                        message: $t('Something went wrong with your request. Please try again later.')
                    };
                }
                messageContainer.addErrorMessage(error);
            }
        },

        /**
         * Method to redirect by requested URL.
         */
        redirectTo: function (redirectUrl) {
            window.location.replace(redirectUrl);
        }
    };
});

/**
 * 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;
        }
    };
});

/**
 * 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(
    'Born_Midtrans/js/action/select-payment-method',[
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/full-screen-loader',
        'jquery',
        'Magento_Checkout/js/action/get-totals',
        'mage/translate',
    ],
    function (quote, fullScreenLoader, jQuery, getTotalsAction, $t) {
        'use strict';
        return function (paymentMethod) {
            if (paymentMethod && paymentMethod.method !== "mapclub") {
                quote.paymentMethod(paymentMethod);
                fullScreenLoader.startLoader();
                jQuery.ajax('/binpromotion/checkout/validatebinpromotion', {
                    data: {cc_number: '', payment_method: paymentMethod.method},
                    complete: function () {
                            getTotalsAction([]);
                            fullScreenLoader.stopLoader();
                    }
                });
            }else if (paymentMethod && paymentMethod.method == "mapclub") {
                quote.paymentMethod(paymentMethod);
                getTotalsAction([]);
            }
            if (paymentMethod && paymentMethod.method !== "midtranscci") {
                jQuery('.midtrans-bank-installment .card-installment').html($t('Choose Bank & Installment'));
                jQuery('#midtransccibank_installment').prop('checked', false);
                jQuery('#midtranscci_cc_bank_name').val('');
                jQuery('#midtranscci_cc_installment').val('');
                window.localStorage.removeItem('cardBankName');
                window.localStorage.removeItem('creditCardInstallment');
                window.localStorage.removeItem('installmentText');
                window.localStorage.removeItem('creditCardHandlingFee');
            }
        }
    }
);

/**
 * 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;

            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);
                }
            }

            /**
             * 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;
                }
            });

            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);
        }
    };
});

/**
 * 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.
 */

/**
 * @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.
 */

/**
 * 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.
 */

/**
 * @api
 */
define('Magento_Catalog/js/price-utils',[
    'jquery',
    'underscore'
], function ($, _) {
    'use strict';

    var globalPriceFormat = {
        requiredPrecision: 2,
        integerRequired: 1,
        decimalSymbol: ',',
        groupSymbol: ',',
        groupLength: ','
    };

    /**
     * Repeats {string} {times} times
     * @param  {String} string
     * @param  {Number} times
     * @return {String}
     */
    function stringPad(string, times) {
        return new Array(times + 1).join(string);
    }

    /**
     * Format the price with the compliance to the specified locale
     *
     * @param {Number} amount
     * @param {Object} format
     * @param  {Boolean} isShowSign
     */
    function formatPriceLocale(amount, format, isShowSign)
    {
        var s = '',
            precision, pattern, locale, r;

        format = _.extend(globalPriceFormat, format);
        precision = isNaN(format.requiredPrecision = Math.abs(format.requiredPrecision)) ? 2 : format.requiredPrecision;
        pattern = format.pattern || '%s';
        locale = window.LOCALE || 'en-US';
        if (isShowSign === undefined || isShowSign === true) {
            s = amount < 0 ? '-' : isShowSign ? '+' : '';
        } else if (isShowSign === false) {
            s = '';
        }
        pattern = pattern.indexOf('{sign}') < 0 ? s + pattern : pattern.replace('{sign}', s);
        amount = Number(Math.round(Math.abs(+amount || 0) + 'e+' + precision) + ('e-' + precision));
        r = amount.toLocaleString(locale, {minimumFractionDigits: precision});

        return pattern.replace('%s', r).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    /**
     * Formatter for price amount
     * @param  {Number}  amount
     * @param  {Object}  format
     * @param  {Boolean} isShowSign
     * @return {String}              Formatted value
     * @deprecated
     */
    function formatPrice(amount, format, isShowSign) {
        var s = '',
            precision, integerRequired, decimalSymbol, groupSymbol, groupLength, pattern, i, pad, j, re, r, am;

        format = _.extend(globalPriceFormat, format);

        // copied from price-option.js | Could be refactored with varien/js.js

        precision = isNaN(format.requiredPrecision = Math.abs(format.requiredPrecision)) ? 2 : format.requiredPrecision;
        integerRequired = isNaN(format.integerRequired = Math.abs(format.integerRequired)) ? 1 : format.integerRequired;
        decimalSymbol = format.decimalSymbol === undefined ? ',' : format.decimalSymbol;
        groupSymbol = format.groupSymbol === undefined ? '.' : format.groupSymbol;
        groupLength = format.groupLength === undefined ? 3 : format.groupLength;
        pattern = format.pattern || '%s';

        if (isShowSign === undefined || isShowSign === true) {
            s = amount < 0 ? '-' : isShowSign ? '+' : '';
        } else if (isShowSign === false) {
            s = '';
        }
        pattern = pattern.indexOf('{sign}') < 0 ? s + pattern : pattern.replace('{sign}', s);

        // we're avoiding the usage of to fixed, and using round instead with the e representation to address
        // numbers like 1.005 = 1.01. Using ToFixed to only provide trailing zeroes in case we have a whole number
        i = parseInt(
                amount = Number(Math.round(Math.abs(+amount || 0) + 'e+' + precision) + ('e-' + precision)),
                10
            ) + '';
        pad = i.length < integerRequired ? integerRequired - i.length : 0;

        i = stringPad('0', pad) + i;

        j = i.length > groupLength ? i.length % groupLength : 0;
        re = new RegExp('(\\d{' + groupLength + '})(?=\\d)', 'g');

        // replace(/-/, 0) is only for fixing Safari bug which appears
        // when Math.abs(0).toFixed() executed on '0' number.
        // Result is '0.-0' :(

        am = Number(Math.round(Math.abs(amount - i) + 'e+' + precision) + ('e-' + precision));
        r = (j ? i.substr(0, j) + groupSymbol : '') +
            i.substr(j).replace(re, '$1' + groupSymbol) +
            (precision ? decimalSymbol + am.toFixed(precision).replace(/-/, 0).slice(2) : '');

        return pattern.replace('%s', r).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    /**
     * Deep clone of Object. Doesn't support functions
     * @param {Object} obj
     * @return {Object}
     */
    function objectDeepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    /**
     * Helper to find ID in name attribute
     * @param   {jQuery} element
     * @returns {undefined|String}
     */
    function findOptionId(element) {
        var re, id, name;

        if (!element) {
            return id;
        }
        name = $(element).attr('name');

        if (name.indexOf('[') !== -1) {
            re = /\[([^\]]+)?\]/;
        } else {
            re = /_([^\]]+)?_/; // just to support file-type-option
        }
        id = re.exec(name) && re.exec(name)[1];

        if (id) {
            return id;
        }
    }

    return {
        formatPriceLocale: formatPriceLocale,
        formatPrice: formatPrice,
        deepClone: objectDeepClone,
        strPad: stringPad,
        findOptionId: findOptionId
    };
});

/**
 * 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');
        }
    });
});

/**
 * 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('Amasty_Conditions/js/model/resource-url-manager',[
    'Magento_Checkout/js/model/resource-url-manager'
], function (resourceUrlManager) {
    'use strict';

    return {
        /**
         * Making url for total estimation request.
         *
         * @param {Object} quote - Quote model.
         * @returns {String} Result url.
         */
        getUrlForTotalsEstimationForNewAddress: function (quote) {
            if (window.checkoutConfig.isNegotiableQuote) {
                var params = {
                        quoteId: quote.getQuoteId()
                    },
                    urls = {
                        'negotiable': '/negotiable-carts/:quoteId/totals-information/?isNegotiableQuote=true'
                    };

                return resourceUrlManager.getUrl(urls, params);
            }

            return resourceUrlManager.getUrlForTotalsEstimationForNewAddress(quote);
        },
    };
});

/**
 * 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.
 */

/**
 * @api
 */
define('Magento_GiftWrapping/js/model/gift-wrapping',[
    'uiElement',
    'underscore',
    'Magento_Checkout/js/model/cart/cache'
], function (uiElement, _, cartCache) {
    'use strict';

    var giftWrappingConfig = window.giftOptionsConfig ?
            window.giftOptionsConfig.giftWrapping :
            window.checkoutConfig.giftWrapping,
        provider = uiElement();

    return function (itemId) {
        var model =  {
            itemId: itemId,
            observables: {},

            /**
             * @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} node
             * @param {String} key
             * @return {*}
             */
            getObservable: function (node, key) {
                this.initObservable(node, key);

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

            /**
             * @param {String} node
             * @param {*} id
             * @return {Boolean}
             */
            unsetObservable: function (node, id) {
                var self = this;

                if (!(node || this.observables.hasOwnProperty(node))) {
                    return false;
                }

                if (id) {
                    provider[this.getUniqueKey(node, id)](false);

                    return true;
                }
                _.each(this.observables[node], function (key) {
                    provider[self.getUniqueKey(node, key)](false);
                });
            },

            /**
             * @param {*} id
             * @param {String} key
             * @return {*}
             */
            isHighlight: function (id, key) {
                return this.getObservable('isHighlight-' + id, key);
            },

            /**
             * @param {String} id
             */
            setActiveItem: function (id) {
                this.unsetObservable('isHighlight-' + this.itemId);
                this.getObservable('isHighlight-' + this.itemId, id)(true);
                this.getObservable('activeWrapping', this.itemId)(id);
            },

            /**
             * Uncheck wrapping.
             */
            uncheckWrapping: function () {
                var activeWrappingId = this.getObservable('activeWrapping', this.itemId)();

                this.getObservable('isHighlight-' + this.itemId, activeWrappingId)(false);
                this.getObservable('activeWrapping', this.itemId)(null);
            },

            /**
             * Retrieve gift wrapping items related to current scope
             *
             * @returns {Array}
             */
            getWrappingItems: function () {
                var cartItemId = this.itemId;

                return _.map(giftWrappingConfig.designsInfo, function (item, id) {
                    var cartItemsConfig = giftWrappingConfig.itemsInfo || {},
                        price = 0,
                        priceExclTax = 0,
                        priceInclTax = 0,
                        cartItemConfig = null;

                    if (cartItemId !== 'orderLevel' &&
                        cartItemsConfig[cartItemId] &&
                        (cartItemsConfig[cartItemId].hasOwnProperty('price') ||
                            cartItemsConfig[cartItemId].hasOwnProperty('price_excl_tax') ||
                            cartItemsConfig[cartItemId].hasOwnProperty('price_incl_tax'))
                    ) {
                        // use product level configuration if it is available
                        cartItemConfig = cartItemsConfig[cartItemId];
                        price = cartItemConfig.price;
                        priceExclTax = cartItemConfig.hasOwnProperty('price_excl_tax') ?
                            cartItemConfig['price_excl_tax'] :
                            null;
                        priceInclTax = cartItemConfig.hasOwnProperty('price_incl_tax') ?
                            cartItemConfig['price_incl_tax'] :
                            null;
                    } else {
                        price = item.price;
                        priceExclTax = item.hasOwnProperty('price_excl_tax') ? item['price_excl_tax'] : null;
                        priceInclTax = item.hasOwnProperty('price_incl_tax') ? item['price_incl_tax'] : null;
                    }

                    return {
                        'id': id,
                        'label': item.label,
                        'path': item.path,
                        'price': price,
                        'priceExclTax': priceExclTax,
                        'priceInclTax': priceInclTax
                    };
                });
            },

            /**
             * @return {*|Boolean}
             */
            isWrappingAvailable: function () {
                // itemId represent gift wrapping level: 'orderLevel' constant or cart item ID
                var isWrappingEnabled;

                if (this.itemId == 'orderLevel') { //eslint-disable-line eqeqeq
                    return this.getConfigValue('allowForOrder') &&
                        (
                            this.getWrappingItems().length > 0 ||
                            this.getConfigValue('isAllowGiftReceipt') ||
                            this.getConfigValue('isAllowPrintedCard')
                        );
                }

                // gift wrapping product configuration must override system configuration
                isWrappingEnabled = giftWrappingConfig.itemsInfo && giftWrappingConfig.itemsInfo[this.itemId] ?
                    giftWrappingConfig.itemsInfo[this.itemId]['is_available'] : this.getConfigValue('allowForItems');

                return isWrappingEnabled && this.getWrappingItems().length > 0;
            },

            /**
             * Get active wrapping info.
             */
            getActiveWrappingInfo: function () {
                var self = this;

                return _.find(this.getWrappingItems(), function (item) {
                    return item.id == self.getObservable('activeWrapping', self.itemId)(); //eslint-disable-line eqeqeq
                });
            },

            /**
             * @param {*} id
             */
            getWrappingById: function (id) {
                return _.find(this.getWrappingItems(), function (item) {
                    return item.id == id; //eslint-disable-line eqeqeq
                });
            },

            /**
             * @param {String} key
             * @return {*}
             */
            getConfigValue: function (key) {
                return giftWrappingConfig[key];
            },

            /**
             * Get price format
             */
            getPriceFormat: function () {
                return window.giftOptionsConfig.priceFormat;
            },

            /**
             * @return {*}
             */
            getPrintedCardPrice: function () {
                return giftWrappingConfig.cardInfo.hasOwnProperty('price') ?
                    giftWrappingConfig.cardInfo.price
                    : '';
            },

            /**
             * @return {Number}
             */
            getPrintedCardPriceWithTax: function () {
                return giftWrappingConfig.cardInfo.hasOwnProperty('price_incl_tax') ?
                    giftWrappingConfig.cardInfo['price_incl_tax'] : giftWrappingConfig.cardInfo.price;
            },

            /**
             * @return {Number}
             */
            getPrintedCardPriceWithoutTax: function () {
                return giftWrappingConfig.cardInfo.hasOwnProperty('price_excl_tax') ?
                    giftWrappingConfig.cardInfo['price_excl_tax']
                    : giftWrappingConfig.cardInfo.price;
            },

            /* eslint-disable eqeqeq*/
            /**
             * @param {*} remove
             * @return {Object}
             */
            getSubmitParams: function (remove) {
                return {
                    wrappingId: remove ? null : this.getObservable('activeWrapping', this.itemId)(),
                    wrappingAddPrintedCard: remove && this.itemId == 'orderLevel' ?
                        false : this.getObservable('wrapping-' + this.itemId, 'printedCard')(),
                    wrappingAllowGiftReceipt: remove && this.itemId == 'orderLevel' ?
                        false : this.getObservable('wrapping-' + this.itemId, 'giftReceipt')()
                };
            },

            /**
             * @return {*}
             */
            getAppliedWrappingId: function () {
                var levelType = this.itemId == 'orderLevel' ? 'orderLevel' : 'itemLevel',
                    appliedWrapping;

                if (!giftWrappingConfig.appliedWrapping.hasOwnProperty(levelType)) {
                    return null;
                }
                appliedWrapping = giftWrappingConfig.appliedWrapping[levelType];

                if (levelType == 'itemLevel') {
                    return appliedWrapping.hasOwnProperty(this.itemId) ? appliedWrapping[this.itemId] : null;
                }

                return appliedWrapping;
            },

            /**
             * @return {Boolean}
             */
            isExtraOptionsApplied: function () {
                var appliedPrintedCard = giftWrappingConfig.hasOwnProperty('appliedPrintedCard') ?
                        giftWrappingConfig.appliedPrintedCard : false,
                    appliedGiftReceipt = giftWrappingConfig.hasOwnProperty('appliedGiftReceipt') ?
                        giftWrappingConfig.appliedGiftReceipt : false;

                if (appliedGiftReceipt == true) {
                    this.getObservable('wrapping-' + this.itemId, 'giftReceipt')(true);
                }

                if (appliedPrintedCard == true) {
                    this.getObservable('wrapping-' + this.itemId, 'printedCard')(true);
                }

                return this.itemId == 'orderLevel' && (appliedGiftReceipt || appliedPrintedCard);
            },

            /* eslint-enable eqeqeq*/
            /**
             * Get gift wrapping price display mode.
             * @returns {Boolean}
             */
            displayWrappingBothPrices: function () {
                return !!giftWrappingConfig.displayWrappingBothPrices;
            },

            /**
             * Get printed card price display mode.
             * @returns {Boolean}
             */
            displayCardBothPrices: function () {
                return !!giftWrappingConfig.displayCardBothPrices;
            },

            /**
             * Get gift wrapping price display mode.
             * @returns {Boolean}
             */
            displayGiftWrappingInclTaxPrice: function () {
                return !!giftWrappingConfig.displayGiftWrappingInclTaxPrice;
            },

            /**
             * Get printed card price display mode.
             * @returns {Boolean}
             */
            displayCardInclTaxPrice: function () {
                return !!giftWrappingConfig.displayCardInclTaxPrice;
            },

            /**
             * After submit.
             */
            afterSubmit: function () {
                if (this.isWrappingAvailable()) {
                    cartCache.clear('totals');
                }
            }
        };

        _.bindAll(model, 'afterSubmit');

        return model;
    };
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    'Magento_GiftWrapping/js/view/summary/totals',[
        'Magento_Checkout/js/view/summary/abstract-total',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/totals',
        'Magento_GiftWrapping/js/model/gift-wrapping'
    ],
    function (Component, quote, totals, GiftWrapping) {
        'use strict';

        return Component.extend({
            defaults: {
                template: 'Magento_GiftWrapping/summary/totals'
            },
            totals: quote.getTotals(),
            model: {},
            excludingTaxMessage: '(Excluding Tax)',
            includingTaxMessage: '(Including Tax)',

            /**
             * @override
             */
            initialize: function (options) {
                this.model = new GiftWrapping(this.level);

                return this._super(options);
            },

            /**
             * Get gift wrapping price based on options.
             * @returns {int}
             */
            getValue: function () {
                var price = 0,
                    wrappingSegment;

                if (
                    this.totals() &&
                    totals.getSegment('giftwrapping') &&
                    totals.getSegment('giftwrapping').hasOwnProperty('extension_attributes')
                ) {
                    wrappingSegment = totals.getSegment('giftwrapping')['extension_attributes'];

                    switch (this.level) {
                        case 'order':
                            price = wrappingSegment.hasOwnProperty('gw_price') ?
                                wrappingSegment['gw_price'] :
                                0;
                            break;

                        case 'item':
                            price = wrappingSegment.hasOwnProperty('gw_items_price') ?
                                wrappingSegment['gw_items_price'] :
                                0;
                            break;

                        case 'printed-card':
                            price = wrappingSegment.hasOwnProperty('gw_card_price') ?
                                wrappingSegment['gw_card_price'] :
                                0;
                            break;
                    }
                }

                return this.getFormattedPrice(price);
            },

            /**
             * Get gift wrapping price (including tax) based on options.
             * @returns {int}
             */
            getIncludingTaxValue: function () {
                var price = 0,
                    wrappingSegment;

                if (
                    this.totals() &&
                    totals.getSegment('giftwrapping') &&
                    totals.getSegment('giftwrapping').hasOwnProperty('extension_attributes')
                ) {
                    wrappingSegment = totals.getSegment('giftwrapping')['extension_attributes'];

                    switch (this.level) {
                        case 'order':
                            price = wrappingSegment.hasOwnProperty('gw_price_incl_tax') ?
                                wrappingSegment['gw_price_incl_tax'] :
                                0;
                            break;

                        case 'item':
                            price = wrappingSegment.hasOwnProperty('gw_items_price_incl_tax') ?
                                wrappingSegment['gw_items_price_incl_tax'] :
                                0;
                            break;

                        case 'printed-card':
                            price = wrappingSegment.hasOwnProperty('gw_card_price_incl_tax') ?
                                wrappingSegment['gw_card_price_incl_tax'] :
                                0;
                            break;
                    }
                }

                return this.getFormattedPrice(price);
            },

            /**
             * Check gift wrapping option availability.
             * @returns {Boolean}
             */
            isAvailable: function () {
                var isAvailable = false,
                    wrappingSegment;

                if (!this.isFullMode()) {
                    return false;
                }

                if (
                    this.totals() &&
                    totals.getSegment('giftwrapping') &&
                    totals.getSegment('giftwrapping').hasOwnProperty('extension_attributes')
                ) {
                    wrappingSegment = totals.getSegment('giftwrapping')['extension_attributes'];

                    switch (this.level) {
                        case 'order':
                            isAvailable = wrappingSegment.hasOwnProperty('gw_order_id') ?
                                wrappingSegment['gw_order_id'] > 0 :
                                false;
                            break;

                        case 'item':
                            isAvailable = wrappingSegment.hasOwnProperty('gw_item_ids') ?
                                wrappingSegment['gw_item_ids'].length > 0 :
                                false;
                            break;

                        case 'printed-card':
                            isAvailable = !!parseFloat(wrappingSegment['gw_add_card']);
                            break;
                    }
                }

                return isAvailable;
            },

            /**
             * Check if both gift wrapping prices should be displayed.
             * @returns {Boolean}
             */
            displayBothPrices: function () {
                var displayBothPrices = false;

                switch (this.level) {
                    case 'order':
                        displayBothPrices = this.model.displayWrappingBothPrices();
                        break;

                    case 'item':
                        displayBothPrices = this.model.displayWrappingBothPrices();
                        break;

                    case 'printed-card':
                        displayBothPrices = this.model.displayCardBothPrices();
                        break;
                }

                return displayBothPrices;
            },

            /**
             * Check if gift wrapping prices should be displayed including tax.
             * @returns {Boolean}
             */
            displayPriceInclTax: function () {
                var displayPriceInclTax = false;

                switch (this.level) {
                    case 'order':
                        displayPriceInclTax = this.model.displayGiftWrappingInclTaxPrice();
                        break;

                    case 'item':
                        displayPriceInclTax = this.model.displayGiftWrappingInclTaxPrice();
                        break;

                    case 'printed-card':
                        displayPriceInclTax = this.model.displayCardInclTaxPrice();
                        break;
                }

                return displayPriceInclTax && !this.displayBothPrices();
            },

            /**
             * Check if gift wrapping prices should be displayed excluding tax.
             * @returns {Boolean}
             */
            displayPriceExclTax: function () {
                return !this.displayPriceInclTax() && !this.displayBothPrices();
            }
        });
    }
);

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

/**
 * @api
 */

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

    return Component.extend({
        defaults: {
            template: 'Magento_Weee/checkout/summary/weee'
        },
        isIncludedInSubtotal: window.checkoutConfig.isIncludedInSubtotal,
        totals: totals.totals,

        /**
         * @returns {Number}
         */
        getWeeeTaxSegment: function () {
            var weee = totals.getSegment('weee_tax') || totals.getSegment('weee');

            if (weee !== null && weee.hasOwnProperty('value')) {
                return weee.value;
            }

            return 0;
        },

        /**
         * Get weee value
         * @returns {String}
         */
        getValue: function () {
            return this.getFormattedPrice(this.getWeeeTaxSegment());
        },

        /**
         * Weee display flag
         * @returns {Boolean}
         */
        isDisplayed: function () {
            return this.isFullMode() && this.getWeeeTaxSegment() > 0;
        }
    });
});

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Magento_InventoryInStorePickupFrontend/js/model/pickup-address-converter',['underscore'], function (_) {
    'use strict';

    return {
        /**
         * Format address to use in store pickup
         *
         * @param {Object} address
         * @return {*}
         */
        formatAddressToPickupAddress: function (address) {
            var sourceCode = _.findWhere(address.customAttributes, {
                'attribute_code': 'sourceCode'
            });

            if (!sourceCode &&
                !_.isEmpty(address.extensionAttributes) &&
                address.extensionAttributes['pickup_location_code']
            ) {
                sourceCode = {
                    value: address.extensionAttributes['pickup_location_code']
                };
            }

            if (sourceCode && address.getType() !== 'store-pickup-address') {
                address = _.extend({}, address, {
                    saveInAddressBook: 0,

                    /**
                     * Is address can be used for billing
                     *
                     * @return {Boolean}
                     */
                    canUseForBilling: function () {
                        return false;
                    },

                    /**
                     * Returns address type
                     *
                     * @return {String}
                     */
                    getType: function () {
                        return 'store-pickup-address';
                    },

                    /**
                     * Returns address key
                     *
                     * @return {*}
                     */
                    getKey: function () {
                        return this.getType() + sourceCode.value;
                    }
                });
            }

            return address;
        }
    };
});

define('Born_Midtrans/js/view/checkout/cart/totals/CreditCardFee',[
    'ko',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_Checkout/js/model/totals'

], function (ko, Component, quote, priceUtils, totals) {
    'use strict';
    return Component.extend({
        defaults: {
            title: window.checkoutConfig.payment.midtranscci.handling_fee_title,
        },

        totals: quote.getTotals(),
        getValue: function() {
            var price = 0;
            if (this.totals() && totals.getSegment('credit_card_fee')) {
                price = totals.getSegment('credit_card_fee').value;
            }
            if(price != 0 && price != 0.0000 && price != null){
                return priceUtils.formatPrice(price, quote.getPriceFormat());
            }
            return null;
        },
        getInFormattedPrice: function() {
            var price = 0;
            if (this.totals() && totals.getSegment('credit_card_fee')) {
                price = totals.getSegment('credit_card_fee').value;
            }

            return priceUtils.formatPrice(price, quote.getPriceFormat());
        },
    });
});

define('Amasty_Conditions/js/model/subscriber',[
    'ko'
    ], function (ko) {
        return {
            isLoading: ko.observable(false)
        }
    }
);
define('Amasty_Conditions/js/action/recollect-totals',[
    'jquery',
    'mage/utils/wrapper',
    'underscore',
    'Amasty_Conditions/js/model/resource-url-manager',
    'Magento_Checkout/js/model/quote',
    'mage/storage',
    'Magento_Checkout/js/model/totals',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Customer/js/customer-data',
    'uiRegistry',
    'Amasty_Conditions/js/model/subscriber'
], function ($, wrapper, _, resourceUrlManager, quote, storage, totalsService, errorProcessor, customerData, registry, subscriber) {
    'use strict';

    var ajax,
        sendTimeout,
        sendingPayload;

    return function (force) {
        var serviceUrl,
            payload,
            address,
            paymentMethod,
            requiredFields = ['countryId', 'region', 'regionId', 'postcode', 'city'],
            newAddress = quote.shippingAddress() ? quote.shippingAddress() : quote.billingAddress(),
            city;

        serviceUrl = resourceUrlManager.getUrlForTotalsEstimationForNewAddress(quote);
        address = _.pick(newAddress, requiredFields);
        paymentMethod = quote.paymentMethod() ? quote.paymentMethod().method : null;
        
        city = '';
        if (quote.isVirtual() && quote.billingAddress()) {
            city = quote.billingAddress().city;
        } else if (quote.shippingAddress()) {
            city = quote.shippingAddress().city;
        }
        
        address.extension_attributes = {
            advanced_conditions: {
                custom_attributes: quote.shippingAddress() ? quote.shippingAddress().custom_attributes : [],
                payment_method: paymentMethod,
                city: city,
                shipping_address_line: quote.shippingAddress() ? quote.shippingAddress().street : null,
                billing_address_country: quote.billingAddress() ? quote.billingAddress().countryId : null,
                currency: totalsService.totals() ? totalsService.totals().quote_currency_code : null
            }
        };

        payload = {
            addressInformation: {
                address: address
            }
        };

        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'];
        }

        if (!_.isEqual(sendingPayload, payload) || force === true) {
            sendingPayload = payload;
            clearTimeout(sendTimeout);
            //delay for avoid multi request
            sendTimeout = setTimeout(function(){
                clearTimeout(sendTimeout);
                if (subscriber.isLoading() === true) {
                    ajax.abort();
                } else {
                    // Start loader for totals block
                    totalsService.isLoading(true);
                    subscriber.isLoading(true);
                }

                ajax = storage.post(
                    serviceUrl,
                    JSON.stringify(payload),
                    false
                ).done(function (result) {
                    quote.setTotals(result);
                    // Stop loader for totals block
                    totalsService.isLoading(false);
                    subscriber.isLoading(false);
                }).fail(function (response) {
                    if (response.responseText || response.status) {
                        errorProcessor.process(response);
                    }
                });
            }, 200);
        }
    };
});
/**
 * 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;
        }
    };
});

/**
 * 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_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('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();
        });
    };
});

/**
 * 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/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) {
                    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) {
                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.
 */

/**
 * 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.
 */
/**
 * 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.
 */

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);

    return Component.extend({
        defaults: {
            template: 'Magento_SalesRule/payment/discount'
        },
        couponCode: couponCode,

        /**
         * 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');
        }
    });
});

define('Amasty_Conditions/js/model/conditions-subscribe',[
    'jquery',
    'underscore',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Amasty_Conditions/js/action/recollect-totals',
    'Amasty_Conditions/js/model/subscriber',
    'Magento_Checkout/js/model/shipping-service',
    'Magento_Checkout/js/model/shipping-rate-processor/new-address',
    'Magento_Checkout/js/model/totals',
    'Magento_SalesRule/js/view/payment/discount',
    'rjsResolver'
], function ($, _, Component, quote, recollect, subscriber, shippingService, shippingProcessor, totals, discount, resolver) {
    'use strict';

    return Component.extend({
        previousShippingMethodData: {},
        previousItemsData: [],
        billingAddressCountry: null,
        city: null,
        street: null,
        isPageLoaded: false,
        initialize: function () {
            this._insertPolyfills();
            this._super();

            resolver(function() {
                this.isPageLoaded = true;

                totals.getItems().subscribe(this.storeOldItems, this, "beforeChange");
                totals.getItems().subscribe(this.recollectOnItems, this);
            }.bind(this));

            discount().isApplied.subscribe(function () {
                recollect(true);
            });

            quote.shippingAddress.subscribe(function (newShippingAddress) {
                // while page is loading do not recollect, should be recollected after shipping rates
                // for avoid extra requests to server
                if (this.isPageLoaded && this._isNeededRecollectShipping(newShippingAddress, this.city, this.street)) {
                    this.city = newShippingAddress.city;
                    this.street = newShippingAddress.street;
                    if (newShippingAddress) {
                        recollect();
                    }
                }
            }.bind(this));

            quote.billingAddress.subscribe(function (newBillAddress) {
                if (this._isNeededRecollectBilling(
                    newBillAddress,
                    this.billingAddressCountry,
                    this.billingAddressCity
                )) {
                    this.billingAddressCountry = newBillAddress.countryId;
                    this.billingAddressCity = newBillAddress.city;
                    if (!this._isVirtualQuote()
                        && (quote.shippingAddress() && newBillAddress.countryId !== quote.shippingAddress().countryId)
                    ) {
                        shippingProcessor.getRates(quote.shippingAddress());
                    }
                    recollect();
                }
            }.bind(this));

            //for invalid shipping address update
            shippingService.getShippingRates().subscribe(function (rates) {
                if (!this._isVirtualQuote()) {
                    recollect();
                }
            }.bind(this));

            quote.paymentMethod.subscribe(function (newMethodData) {
                recollect();
            }, this);

            quote.shippingMethod.subscribe(this.storeOldMethod, this, "beforeChange");
            quote.shippingMethod.subscribe(this.recollectOnShippingMethod, this);

            return this;
        },

        /**
         * Store before change shipping method, because sometimes shipping methods updates always (not by change)
         *
         * @param {Object} oldMethod
         */
        storeOldMethod: function (oldMethod) {
            this.previousShippingMethodData = oldMethod;
        },

        recollectOnShippingMethod: function (newMethodData) {
            if (!_.isEqual(this.previousShippingMethodData, newMethodData)) {
                recollect();
            }
        },

        /**
         * Store before change cart items
         *
         * @param {Array} oldItems
         * @since 1.3.13
         */
        storeOldItems: function (oldItems) {
            this.previousItemsData = this._prepareArrayForCompare(oldItems);
        },

        /**
         * Recollect totals on cart items update
         *
         * @param {Array} newItems
         * @since 1.3.13 improve compatibility with modules which allow update cart items on checkout page
         *        and ajax update cart items
         */
        recollectOnItems: function (newItems) {
            if (!_.isEqual(this.previousItemsData, this._prepareArrayForCompare(newItems))) {
                // totals should be already collected, trigger subscribers
                // for more stability but less performance can be replaced with recollect(true);
                subscriber.isLoading.valueHasMutated();
            }
        },

        /**
         * Remove all not simple types from array items
         *
         * @param {Array} data
         * @returns {Array}
         * @private
         * @since 1.3.13
         */
        _prepareArrayForCompare: function (data) {
            var result = [],
                itemData = {};

            _.each(data, function(item) {
                itemData = _.pick(item, function (value) {
                    return !_.isObject(value);
                });
                result.push(itemData);
            }.bind(this));

            return result;
        },

        _isVirtualQuote: function () {
            return quote.isVirtual()
                || window.checkoutConfig.activeCarriers && window.checkoutConfig.activeCarriers.length === 0;
        },

        _isNeededRecollectShipping: function (newShippingAddress, city, street) {
            return !this._isVirtualQuote()
                && (
                    newShippingAddress
                    && (newShippingAddress.city || newShippingAddress.street)
                    && (newShippingAddress.city != city || !_.isEqual(newShippingAddress.street, street)));
        },

        _isNeededRecollectBilling: function (newBillAddress, billingAddressCountry, billingAddressCity) {
            var isNeedRecollectByCountry = newBillAddress
                    && newBillAddress.countryId
                    && newBillAddress.countryId !== billingAddressCountry,
                isNeedRecollectByCity = newBillAddress
                    && newBillAddress.city
                    && newBillAddress.city !== billingAddressCity;

            return this.isPageLoaded && (isNeedRecollectByCountry || isNeedRecollectByCity);
        },

        _insertPolyfills: function () {
            if (typeof Object.assign != 'function') {
                // Must be writable: true, enumerable: false, configurable: true
                Object.defineProperty(Object, "assign", {
                    value: function assign(target, varArgs) { // .length of function is 2
                        'use strict';
                        if (target == null) { // TypeError if undefined or null
                            throw new TypeError('Cannot convert undefined or null to object');
                        }

                        var to = Object(target);

                        for (var index = 1; index < arguments.length; index++) {
                            var nextSource = arguments[index];

                            if (nextSource != null) { // Skip over if undefined or null
                                for (var nextKey in nextSource) {
                                    // Avoid bugs when hasOwnProperty is shadowed
                                    if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                                        to[nextKey] = nextSource[nextKey];
                                    }
                                }
                            }
                        }
                        return to;
                    },
                    writable: true,
                    configurable: true
                });
            }
        }
    });
});


define('text!Magento_GiftWrapping/template/summary/totals.html',[],function () { return '<!--\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n-->\n<!-- ko if: isAvailable() -->\n    <!-- ko if: displayBothPrices() -->\n        <tr class="totals giftwrapping excl">\n            <th class="mark">\n                <span data-bind="text: $t(title) + \' \' + $t(excludingTaxMessage)"></span>\n            </th>\n            <td data-bind="text: getValue(), attr: {\'data-th\': $t(excludingTaxMessage)}" class="amount"></td>\n        </tr>\n        <tr class="totals giftwrapping incl">\n            <th class="mark">\n                <span data-bind="text: $t(title) + \' \' + $t(includingTaxMessage)"></span>\n            </th>\n            <td data-bind="text: getIncludingTaxValue(), attr: {\'data-th\': $t(includingTaxMessage)}" class="amount"></td>\n        </tr>\n    <!-- /ko -->\n    <!-- ko if: displayPriceInclTax() -->\n        <tr class="totals giftwrapping">\n            <th class="mark">\n                <span data-bind="{i18n: title}"></span>\n            </th>\n            <td data-bind="{text: getIncludingTaxValue(), attr: {\'data-th\': $t(title)}}" class="amount"></td>\n        </tr>\n    <!-- /ko -->\n    <!-- ko if: displayPriceExclTax() -->\n        <tr class="totals giftwrapping">\n            <th class="mark">\n                <span data-bind="{i18n: title}"></span>\n            </th>\n            <td data-bind="{text: getValue(), attr: {\'data-th\': $t(title)}}" class="amount"></td>\n        </tr>\n    <!-- /ko -->\n<!-- /ko -->\n';});

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

/**
 * @api
 */

define('Magento_Tax/js/view/checkout/summary/tax',[
    'ko',
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/totals',
    'mage/translate',
    'underscore'
], function (ko, Component, quote, totals, $t, _) {
    'use strict';

    var isTaxDisplayedInGrandTotal = window.checkoutConfig.includeTaxInGrandTotal,
        isFullTaxSummaryDisplayed = window.checkoutConfig.isFullTaxSummaryDisplayed,
        isZeroTaxDisplayed = window.checkoutConfig.isZeroTaxDisplayed,
        taxAmount = 0,
        rates = 0;

    return Component.extend({
        defaults: {
            isTaxDisplayedInGrandTotal: isTaxDisplayedInGrandTotal,
            notCalculatedMessage: $t('Not yet calculated'),
            template: 'Magento_Tax/checkout/summary/tax'
        },
        totals: quote.getTotals(),
        isFullTaxSummaryDisplayed: isFullTaxSummaryDisplayed,

        /**
         * @return {Boolean}
         */
        ifShowValue: function () {
            if (this.isFullMode() && this.getPureValue() == 0) { //eslint-disable-line eqeqeq
                return isZeroTaxDisplayed;
            }

            return true;
        },

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

            return this.getPureValue() > 0 && isFullTaxSummaryDisplayed;
        },

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

            if (this.totals()) {
                taxTotal = totals.getSegment('tax');

                if (taxTotal) {
                    amount = taxTotal.value;
                }
            }

            return amount;
        },

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

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

            if (!this.isCalculated()) {
                return this.notCalculatedMessage;
            }
            amount = totals.getSegment('tax').value;

            return this.getFormattedPrice(amount);
        },

        /**
         * @param {*} amount
         * @return {*|String}
         */
        formatPrice: function (amount) {
            return this.getFormattedPrice(amount);
        },

        /**
         * @param {*} parent
         * @param {*} percentage
         * @return {*|String}
         */
        getTaxAmount: function (parent, percentage) {
            var totalPercentage = 0;

            taxAmount = parent.amount;
            rates = parent.rates;
            _.each(rates, function (rate) {
                totalPercentage += parseFloat(rate.percent);
            });

            return this.getFormattedPrice(this.getPercentAmount(taxAmount, totalPercentage, percentage));
        },

        /**
         * @param {*} amount
         * @param {*} totalPercentage
         * @param {*} percentage
         * @return {*|String}
         */
        getPercentAmount: function (amount, totalPercentage, percentage) {
            return parseFloat(amount * percentage / totalPercentage);
        },

        /**
         * @return {Array}
         */
        getDetails: function () {
            var taxSegment = totals.getSegment('tax');

            if (taxSegment && taxSegment['extension_attributes']) {
                return taxSegment['extension_attributes']['tax_grandtotal_details'];
            }

            return [];
        }
    });
});

define('PayPal_Braintree/js/model/step-navigator-mixin',[
    'mage/utils/wrapper',
    'jquery'
], function (wrapper, $) {
    'use strict';

    let mixin = {
        handleHash: function (originalFn) {
            var hashString = window.location.hash.replace('#', '');
            if (hashString.indexOf('venmo') > -1) {
                return false;
            }

            return originalFn();
        }
    };

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

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

/**
 * Customer store credit(balance) application
 */
define('Magento_CustomerBalance/js/action/remove-balance',[
    'jquery',
    'mage/url',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Checkout/js/model/quote',
    'mage/storage',
    'Magento_Ui/js/model/messageList',
    'mage/translate',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function (
    $,
    urlBuilder,
    errorProcessor,
    quote,
    storage,
    messageList,
    $t,
    fullScreenLoader,
    getPaymentInformationAction,
    totals
) {
    'use strict';

    return function () {
        var message = $t('The store credit payment has been removed from shopping cart.');

        messageList.clear();
        fullScreenLoader.startLoader();

        $.ajax({
            url: urlBuilder.build('storecredit/cart/unapply/'),
            type: 'POST',
            dataType: 'json',
            data: {
                cartId: quote.getQuoteId()
            }
        }).done(function (response) {
            var deferred;

            if (response) {
                deferred = $.Deferred();
                totals.isLoading(true);
                getPaymentInformationAction(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();
        });
    };
});

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

/**
 * Customer store credit(balance) application
 */

define('Magento_CustomerBalance/js/action/use-balance',[
    'jquery',
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'Magento_Checkout/js/model/error-processor',
    'mage/storage',
    'Magento_Ui/js/model/messageList',
    'mage/translate',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function (
    $,
    ko,
    quote,
    urlBuilder,
    errorProcessor,
    storage,
    messageList,
    $t,
    fullScreenLoader,
    getPaymentInformationAction,
    totals
) {
    'use strict';

    return function () {
        var message = $t('Your store credit was successfully applied');

        messageList.clear();
        fullScreenLoader.startLoader();

        return storage.post(
            urlBuilder.createUrl('/carts/mine/balance/apply', {})
        ).done(function (response) {
            var deferred;

            if (response) {
                deferred = $.Deferred();
                totals.isLoading(true);
                getPaymentInformationAction(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();
        });
    };
});

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

/**
 * Customer balance view model
 */
define('Magento_CustomerBalance/js/view/payment/customer-balance',[
    'ko',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils',
    'Magento_CustomerBalance/js/action/use-balance'
], function (ko, component, quote, priceUtils, useBalanceAction) {
    'use strict';

    var amountSubstracted = ko.observable(window.checkoutConfig.payment.customerBalance.amountSubstracted),
        isActive = ko.pureComputed(function () {
            var totals = quote.getTotals();

            return !amountSubstracted() && totals()['grand_total'] > 0;
        });

    return component.extend({
        defaults: {
            template: 'Magento_CustomerBalance/payment/customer-balance',
            isEnabled: true
        },
        isAvailable: window.checkoutConfig.payment.customerBalance.isAvailable,
        amountSubstracted: window.checkoutConfig.payment.customerBalance.amountSubstracted,
        usedAmount: window.checkoutConfig.payment.customerBalance.usedAmount,
        balance: window.checkoutConfig.payment.customerBalance.balance,

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe('isEnabled');

            return this;
        },

        /**
         * Get active status
         *
         * @return {Boolean}
         */
        isActive: function () {
            return isActive();
        },

        /**
         * Format customer balance
         *
         * @return {String}
         */
        formatBalance: function () {
            return priceUtils.formatPrice(this.balance, quote.getPriceFormat());
        },

        /**
         * Set amount substracted from checkout.
         *
         * @param {Boolean} isAmountSubstracted
         * @return {Object}
         */
        setAmountSubstracted: function (isAmountSubstracted) {
            amountSubstracted(isAmountSubstracted);

            return this;
        },

        /**
         * Send request to use balance
         */
        sendRequest: function () {
            amountSubstracted(true);
            useBalanceAction();
        }
    });
});

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

/**
 * Customer balance summary block info
 */
define('Magento_CustomerBalance/js/view/summary/customer-balance',[
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/totals',
    'Magento_CustomerBalance/js/action/remove-balance',
    'Magento_CustomerBalance/js/view/payment/customer-balance'
], function (Component, totals, removeCustomerBalance, customerBalance) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_CustomerBalance/summary/customer-balance',
            storeCreditFormName: 'checkout.steps.billing-step.payment.afterMethods.storeCredit',
            modules: {
                storeCreditForm: '${ $.storeCreditFormName }'
            }
        },
        totals: totals.totals(),

        /**
         * Used balance without any formatting
         *
         * @return {Number}
         */
        getPureValue: function () {
            var price = 0,
                segment;

            if (this.totals) {
                segment = totals.getSegment('customerbalance');

                if (segment) {
                    price = segment.value;
                }
            }

            return price;
        },

        /**
         * Used balance with currency sign and localization
         *
         * @return {String}
         */
        getValue: function () {
            return this.getFormattedPrice(this.getPureValue());
        },

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

        /**
         * Send request to unuse balance
         */
        sendRequest: function () {
            removeCustomerBalance();
            this.storeCreditForm().setAmountSubstracted(false);
            customerBalance();
        }
    });
});

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

define('Magento_InventoryInStorePickupFrontend/js/model/checkout-data-resolver-ext',[
    'mage/utils/wrapper',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/action/select-shipping-address',
    'Magento_Checkout/js/model/address-converter',
    'Magento_InventoryInStorePickupFrontend/js/model/pickup-address-converter'
], function (
    wrapper,
    checkoutData,
    selectShippingAddress,
    addressConverter,
    pickupAddressConverter
) {
    'use strict';

    return function (checkoutDataResolver) {
        checkoutDataResolver.resolveShippingAddress = wrapper.wrapSuper(
            checkoutDataResolver.resolveShippingAddress,
            function () {
                var shippingAddress,
                    pickUpAddress;

                if (checkoutData.getSelectedPickupAddress() && checkoutData.getSelectedShippingAddress()) {
                    shippingAddress = addressConverter.formAddressDataToQuoteAddress(
                        checkoutData.getSelectedPickupAddress()
                    );
                    pickUpAddress = pickupAddressConverter.formatAddressToPickupAddress(
                        shippingAddress
                    );

                    if (pickUpAddress.getKey() === checkoutData.getSelectedShippingAddress()) {
                        selectShippingAddress(pickUpAddress);

                        return;
                    }
                }
                this._super();
            });

        return checkoutDataResolver;
    };
});

/**
 * 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;
        }
    };
});

/**
 * 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;
        }
    };
});

/**
 * 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.
 */

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.
 */

/**
 * @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;
        }
    };
});

/* phpcs:ignoreFile */
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/
 Version: 1.9.0
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues
 */
(function(i){"use strict";"function"==typeof define&&define.amd?define('Amasty_Base/vendor/slick/slick.min',["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)})(function(i){"use strict";var e=window.Slick||{};e=function(){function e(e,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(e),appendDots:i(e),arrows:!0,asNavFor:null,prevArrow:'<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',nextArrow:'<button class="slick-next" aria-label="Next" type="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('<button type="button" />').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,focusOnChange:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:!1,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,swiping:!1,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(e),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(e).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,"undefined"!=typeof document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=t++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}var t=0;return e}(),e.prototype.activateADA=function(){var i=this;i.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(t<0||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):o===!0?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&i.options.adaptiveHeight===!0&&i.options.vertical===!1){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),s.options.rtl===!0&&s.options.vertical===!1&&(e=-e),s.transformsEnabled===!1?s.options.vertical===!1?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):s.cssTransitions===!1?(s.options.rtl===!0&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),s.options.vertical===!1?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),s.options.vertical===!1?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this,o=t.getNavTarget();null!==o&&"object"==typeof o&&o.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};e.options.fade===!1?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,e.options.fade===!1?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(i.options.infinite===!1&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1===0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;e.options.arrows===!0&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),e.options.infinite!==!0&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(o.options.dots===!0&&o.slideCount>o.options.slidesToShow){for(o.$slider.addClass("slick-dotted"),t=i("<ul />").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("<li />").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('<div class="slick-track"/>').appendTo(e.$slider):e.$slides.wrapAll('<div class="slick-track"/>').parent(),e.$list=e.$slideTrack.wrap('<div class="slick-list"/>').parent(),e.$slideTrack.css("opacity",0),e.options.centerMode!==!0&&e.options.swipeToSlide!==!0||(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.options.draggable===!0&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.options.rows>0){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;i<s;i++){var d=document.createElement("div");for(e=0;e<l.options.rows;e++){var a=document.createElement("div");for(t=0;t<l.options.slidesPerRow;t++){var c=i*r+(e*l.options.slidesPerRow+t);n.get(c)&&a.appendChild(n.get(c))}d.appendChild(a)}o.appendChild(d)}l.$slider.empty().append(o),l.$slider.children().children().children().css({width:100/l.options.slidesPerRow+"%",display:"inline-block"})}},e.prototype.checkResponsive=function(e,t){var o,s,n,r=this,l=!1,d=r.$slider.width(),a=window.innerWidth||i(window).width();if("window"===r.respondTo?n=a:"slider"===r.respondTo?n=d:"min"===r.respondTo&&(n=Math.min(a,d)),r.options.responsive&&r.options.responsive.length&&null!==r.options.responsive){s=null;for(o in r.breakpoints)r.breakpoints.hasOwnProperty(o)&&(r.originalSettings.mobileFirst===!1?n<r.breakpoints[o]&&(s=r.breakpoints[o]):n>r.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||l===!1||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!==0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var d=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(d),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t,o=this;if(e=o.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var s in e){if(i<e[s]){i=t;break}t=e[s]}return i},e.prototype.cleanUpEvents=function(){var e=this;e.options.dots&&null!==e.$dots&&(i("li",e.$dots).off("click.slick",e.changeSlide).off("mouseenter.slick",i.proxy(e.interrupt,e,!0)).off("mouseleave.slick",i.proxy(e.interrupt,e,!1)),e.options.accessibility===!0&&e.$dots.off("keydown.slick",e.keyHandler)),e.$slider.off("focus.slick blur.slick"),e.options.arrows===!0&&e.slideCount>e.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide),e.options.accessibility===!0&&(e.$prevArrow&&e.$prevArrow.off("keydown.slick",e.keyHandler),e.$nextArrow&&e.$nextArrow.off("keydown.slick",e.keyHandler))),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),e.options.accessibility===!0&&e.$list.off("keydown.slick",e.keyHandler),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>0&&(i=e.$slides.children().children(),i.removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){var e=this;e.shouldClick===!1&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",e.options.fade===!1?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;t.cssTransitions===!1?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;e.cssTransitions===!1?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick","*",function(t){var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&o.is(":focus")&&(e.focussed=!0,e.autoPlay())},0)}).on("blur.slick","*",function(t){i(this);e.options.pauseOnFocus&&(e.focussed=!1,e.autoPlay())})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){var i=this;return i.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(i.options.infinite===!0)if(i.slideCount<=i.options.slidesToShow)++o;else for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else if(i.options.centerMode===!0)o=i.slideCount;else if(i.options.asNavFor)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else o=1+Math.ceil((i.slideCount-i.options.slidesToShow)/i.options.slidesToScroll);return o-1},e.prototype.getLeft=function(i){var e,t,o,s,n=this,r=0;return n.slideOffset=0,t=n.$slides.first().outerHeight(!0),n.options.infinite===!0?(n.slideCount>n.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,n.options.vertical===!0&&n.options.centerMode===!0&&(2===n.options.slidesToShow?s=-1.5:1===n.options.slidesToShow&&(s=-2)),r=t*n.options.slidesToShow*s),n.slideCount%n.options.slidesToScroll!==0&&i+n.options.slidesToScroll>n.slideCount&&n.slideCount>n.options.slidesToShow&&(i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,r=(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,r=n.slideCount%n.options.slidesToScroll*t*-1))):i+n.options.slidesToShow>n.slideCount&&(n.slideOffset=(i+n.options.slidesToShow-n.slideCount)*n.slideWidth,r=(i+n.options.slidesToShow-n.slideCount)*t),n.slideCount<=n.options.slidesToShow&&(n.slideOffset=0,r=0),n.options.centerMode===!0&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:n.options.centerMode===!0&&n.options.infinite===!0?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:n.options.centerMode===!0&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=n.options.vertical===!1?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,n.options.variableWidth===!0&&(o=n.slideCount<=n.options.slidesToShow||n.options.infinite===!1?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=n.options.rtl===!0?o[0]?(n.$slideTrack.width()-o[0].offsetLeft-o.width())*-1:0:o[0]?o[0].offsetLeft*-1:0,n.options.centerMode===!0&&(o=n.slideCount<=n.options.slidesToShow||n.options.infinite===!1?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=n.options.rtl===!0?o[0]?(n.$slideTrack.width()-o[0].offsetLeft-o.width())*-1:0:o[0]?o[0].offsetLeft*-1:0,e+=(n.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){var e=this;return e.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(e.options.infinite===!1?i=e.slideCount:(t=e.options.slidesToScroll*-1,o=e.options.slidesToScroll*-1,i=2*e.slideCount);t<i;)s.push(t),t=o+e.options.slidesToScroll,o+=e.options.slidesToScroll<=e.options.slidesToShow?e.options.slidesToScroll:e.options.slidesToShow;return s},e.prototype.getSlick=function(){return this},e.prototype.getSlideCount=function(){var e,t,o,s,n=this;return s=n.options.centerMode===!0?Math.floor(n.$list.width()/2):0,o=n.swipeLeft*-1+s,n.options.swipeToSlide===!0?(n.$slideTrack.find(".slick-slide").each(function(e,s){var r,l,d;if(r=i(s).outerWidth(),l=s.offsetLeft,n.options.centerMode!==!0&&(l+=r/2),d=l+r,o<d)return t=s,!1}),e=Math.abs(i(t).attr("data-slick-index")-n.currentSlide)||1):n.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){var t=this;t.changeSlide({data:{message:"index",index:parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),t.options.accessibility===!0&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this,t=Math.ceil(e.slideCount/e.options.slidesToShow),o=e.getNavigableIndexes().filter(function(i){return i>=0&&i<e.slideCount});e.$slides.add(e.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==e.$dots&&(e.$slides.not(e.$slideTrack.find(".slick-cloned")).each(function(t){var s=o.indexOf(t);if(i(this).attr({role:"tabpanel",id:"slick-slide"+e.instanceUid+t,tabindex:-1}),s!==-1){var n="slick-slide-control"+e.instanceUid+s;i("#"+n).length&&i(this).attr({"aria-describedby":n})}}),e.$dots.attr("role","tablist").find("li").each(function(s){var n=o[s];i(this).attr({role:"presentation"}),i(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+e.instanceUid+s,"aria-controls":"slick-slide"+e.instanceUid+n,"aria-label":s+1+" of "+t,"aria-selected":null,tabindex:"-1"})}).eq(e.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end());for(var s=e.currentSlide,n=s+e.options.slidesToShow;s<n;s++)e.options.focusOnChange?e.$slides.eq(s).attr({tabindex:"0"}):e.$slides.eq(s).removeAttr("tabindex");e.activateADA()},e.prototype.initArrowEvents=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide),i.options.accessibility===!0&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},e.prototype.initDotEvents=function(){var e=this;e.options.dots===!0&&e.slideCount>e.options.slidesToShow&&(i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),e.options.accessibility===!0&&e.$dots.on("keydown.slick",e.keyHandler)),e.options.dots===!0&&e.options.pauseOnDotsHover===!0&&e.slideCount>e.options.slidesToShow&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"},e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),e.options.accessibility===!0&&e.$list.on("keydown.slick",e.keyHandler),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(e.setPosition)},e.prototype.initUI=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),i.options.dots===!0&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&e.options.accessibility===!0?e.changeSlide({data:{message:e.options.rtl===!0?"next":"previous"}}):39===i.keyCode&&e.options.accessibility===!0&&e.changeSlide({data:{message:e.options.rtl===!0?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=i(this).attr("data-srcset"),s=i(this).attr("data-sizes")||r.$slider.attr("data-sizes"),n=document.createElement("img");n.onload=function(){e.animate({opacity:0},100,function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),r.$slider.trigger("lazyLoaded",[r,e,t])})},n.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),r.$slider.trigger("lazyLoadError",[r,e,t])},n.src=t})}var t,o,s,n,r=this;if(r.options.centerMode===!0?r.options.infinite===!0?(s=r.currentSlide+(r.options.slidesToShow/2+1),n=s+r.options.slidesToShow+2):(s=Math.max(0,r.currentSlide-(r.options.slidesToShow/2+1)),n=2+(r.options.slidesToShow/2+1)+r.currentSlide):(s=r.options.infinite?r.options.slidesToShow+r.currentSlide:r.currentSlide,n=Math.ceil(s+r.options.slidesToShow),r.options.fade===!0&&(s>0&&s--,n<=r.slideCount&&n++)),t=r.$slider.find(".slick-slide").slice(s,n),"anticipated"===r.options.lazyLoad)for(var l=s-1,d=n,a=r.$slider.find(".slick-slide"),c=0;c<r.options.slidesToScroll;c++)l<0&&(l=r.slideCount-1),t=t.add(a.eq(l)),t=t.add(a.eq(d)),l--,d++;e(t),r.slideCount<=r.options.slidesToShow?(o=r.$slider.find(".slick-slide"),e(o)):r.currentSlide>=r.slideCount-r.options.slidesToShow?(o=r.$slider.find(".slick-cloned").slice(0,r.options.slidesToShow),e(o)):0===r.currentSlide&&(o=r.$slider.find(".slick-cloned").slice(r.options.slidesToShow*-1),e(o))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){var i=this;i.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(e){var t=this;if(!t.unslicked&&(t.$slider.trigger("afterChange",[t,e]),t.animating=!1,t.slideCount>t.options.slidesToShow&&t.setPosition(),t.swipeLeft=null,t.options.autoplay&&t.autoPlay(),t.options.accessibility===!0&&(t.initADA(),t.options.focusOnChange))){var o=i(t.$slides.get(t.currentSlide));o.attr("tabindex",0).focus()}},e.prototype.prev=e.prototype.slickPrev=function(){var i=this;i.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n,r,l=this,d=i("img[data-lazy]",l.$slider);d.length?(t=d.first(),o=t.attr("data-lazy"),s=t.attr("data-srcset"),n=t.attr("data-sizes")||l.$slider.attr("data-sizes"),r=document.createElement("img"),r.onload=function(){s&&(t.attr("srcset",s),n&&t.attr("sizes",n)),t.attr("src",o).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),l.options.adaptiveHeight===!0&&l.setPosition(),l.$slider.trigger("lazyLoaded",[l,t,o]),l.progressiveLazyLoad()},r.onerror=function(){e<3?setTimeout(function(){l.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),l.$slider.trigger("lazyLoadError",[l,t,o]),l.progressiveLazyLoad())},r.src=o):l.$slider.trigger("allImagesLoaded",[l])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,n.hasOwnProperty(e)){for(t=n[e].breakpoint;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;return"boolean"==typeof i?(e=i,i=e===!0?0:o.slideCount-1):i=e===!0?--i:i,!(o.slideCount<1||i<0||i>o.slideCount-1)&&(o.unload(),t===!0?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,void o.reinit())},e.prototype.setCSS=function(i){var e,t,o=this,s={};o.options.rtl===!0&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,o.transformsEnabled===!1?o.$slideTrack.css(s):(s={},o.cssTransitions===!1?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;i.options.vertical===!1?i.options.centerMode===!0&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),i.options.centerMode===!0&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),i.options.vertical===!1&&i.options.variableWidth===!1?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):i.options.variableWidth===!0?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();i.options.variableWidth===!1&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,t.options.rtl===!0?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&i.options.adaptiveHeight===!0&&i.options.vertical===!1){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":"undefined"!=typeof arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),i.options.fade===!1?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=i.options.vertical===!0?"top":"left",
    "top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),void 0===e.WebkitTransition&&void 0===e.MozTransition&&void 0===e.msTransition||i.options.useCSS===!0&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&i.animType!==!1&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&i.animType!==!1},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;if(t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),n.options.centerMode===!0){var r=n.options.slidesToShow%2===0?1:0;e=Math.floor(n.options.slidesToShow/2),n.options.infinite===!0&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e+r,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,t.slice(o-e+1+r,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")}else i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=n.options.infinite===!0?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-i<n.options.slidesToShow?t.slice(o-(n.options.slidesToShow-s),o+s).addClass("slick-active").attr("aria-hidden","false"):t.slice(o,o+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"));"ondemand"!==n.options.lazyLoad&&"anticipated"!==n.options.lazyLoad||n.lazyLoad()},e.prototype.setupInfinite=function(){var e,t,o,s=this;if(s.options.fade===!0&&(s.options.centerMode=!1),s.options.infinite===!0&&s.options.fade===!1&&(t=null,s.slideCount>s.options.slidesToShow)){for(o=s.options.centerMode===!0?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;e<o+s.slideCount;e+=1)t=e,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t+s.slideCount).appendTo(s.$slideTrack).addClass("slick-cloned");s.$slideTrack.find(".slick-cloned").find("[id]").each(function(){i(this).attr("id","")})}},e.prototype.interrupt=function(i){var e=this;i||e.autoPlay(),e.interrupted=i},e.prototype.selectHandler=function(e){var t=this,o=i(e.target).is(".slick-slide")?i(e.target):i(e.target).parents(".slick-slide"),s=parseInt(o.attr("data-slick-index"));return s||(s=0),t.slideCount<=t.options.slidesToShow?void t.slideHandler(s,!1,!0):void t.slideHandler(s)},e.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,d=null,a=this;if(e=e||!1,!(a.animating===!0&&a.options.waitForAnimate===!0||a.options.fade===!0&&a.currentSlide===i))return e===!1&&a.asNavFor(i),o=i,d=a.getLeft(o),r=a.getLeft(a.currentSlide),a.currentLeft=null===a.swipeLeft?r:a.swipeLeft,a.options.infinite===!1&&a.options.centerMode===!1&&(i<0||i>a.getDotCount()*a.options.slidesToScroll)?void(a.options.fade===!1&&(o=a.currentSlide,t!==!0&&a.slideCount>a.options.slidesToShow?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o))):a.options.infinite===!1&&a.options.centerMode===!0&&(i<0||i>a.slideCount-a.options.slidesToScroll)?void(a.options.fade===!1&&(o=a.currentSlide,t!==!0&&a.slideCount>a.options.slidesToShow?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o))):(a.options.autoplay&&clearInterval(a.autoPlayTimer),s=o<0?a.slideCount%a.options.slidesToScroll!==0?a.slideCount-a.slideCount%a.options.slidesToScroll:a.slideCount+o:o>=a.slideCount?a.slideCount%a.options.slidesToScroll!==0?0:o-a.slideCount:o,a.animating=!0,a.$slider.trigger("beforeChange",[a,a.currentSlide,s]),n=a.currentSlide,a.currentSlide=s,a.setSlideClasses(a.currentSlide),a.options.asNavFor&&(l=a.getNavTarget(),l=l.slick("getSlick"),l.slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide)),a.updateDots(),a.updateArrows(),a.options.fade===!0?(t!==!0?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight()):void(t!==!0&&a.slideCount>a.options.slidesToShow?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)))},e.prototype.startLoad=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),i.options.dots===!0&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),o=Math.round(180*t/Math.PI),o<0&&(o=360-Math.abs(o)),o<=45&&o>=0?s.options.rtl===!1?"left":"right":o<=360&&o>=315?s.options.rtl===!1?"left":"right":o>=135&&o<=225?s.options.rtl===!1?"right":"left":s.options.verticalSwiping===!0?o>=35&&o<=135?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1,!1;if(o.interrupted=!1,o.shouldClick=!(o.touchObject.swipeLength>10),void 0===o.touchObject.curX)return!1;if(o.touchObject.edgeHit===!0&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(e.options.swipe===!1||"ontouchend"in document&&e.options.swipe===!1||e.options.draggable===!1&&i.type.indexOf("mouse")!==-1))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,e.options.verticalSwiping===!0&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r,l=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!(!l.dragging||l.scrolling||n&&1!==n.length)&&(e=l.getLeft(l.currentSlide),l.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,l.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,l.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(l.touchObject.curX-l.touchObject.startX,2))),r=Math.round(Math.sqrt(Math.pow(l.touchObject.curY-l.touchObject.startY,2))),!l.options.verticalSwiping&&!l.swiping&&r>4?(l.scrolling=!0,!1):(l.options.verticalSwiping===!0&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&l.touchObject.swipeLength>4&&(l.swiping=!0,i.preventDefault()),s=(l.options.rtl===!1?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),l.options.verticalSwiping===!0&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,l.touchObject.edgeHit=!1,l.options.infinite===!1&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),l.options.vertical===!1?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,l.options.verticalSwiping===!0&&(l.swipeLeft=e+o*s),l.options.fade!==!0&&l.options.touchMove!==!1&&(l.animating===!0?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},e.prototype.swipeStart=function(i){var e,t=this;return t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow?(t.touchObject={},!1):(void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,void(t.dragging=!0))},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i,e=this;i=Math.floor(e.options.slidesToShow/2),e.options.arrows===!0&&e.slideCount>e.options.slidesToShow&&!e.options.infinite&&(e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),e.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===e.currentSlide?(e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):e.currentSlide>=e.slideCount-e.options.slidesToShow&&e.options.centerMode===!1?(e.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):e.currentSlide>=e.slideCount-1&&e.options.centerMode===!0&&(e.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").end(),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;i<r;i++)if("object"==typeof s||"undefined"==typeof s?o[i].slick=new e(o[i],s):t=o[i].slick[s].apply(o[i].slick,n),"undefined"!=typeof t)return t;return o}});

/**
 * 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_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 © Born, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define('Born_MapClub/js/model/payment/mapclub',['ko'], function (ko) {
    'use strict';

    var mapclubConfig = window.checkoutConfig.payment.mapclub;
    return {
        isLoggedIn: ko.observable(mapclubConfig.isLoggedIn),
        isAvailable: ko.observable(mapclubConfig.isAvailable),
        availablePoints: ko.observable(mapclubConfig.availablePoints),
        displayPoints: function (points) {
            var separator = '.';
            points += '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(points)) {
                points = points.replace(rgx, '$1' + separator + '$2');
            }

            return points;
        },
        usedPoints: ko.observable(mapclubConfig.usedPoints),
        conversionRate: ko.observable(mapclubConfig.conversionRate),
        isApplied: ko.observable(mapclubConfig.usedPoints),
        noticeText: ko.observable(mapclubConfig.noticeText)
    };
});
define('Amasty_Rules/js/view/cart/totals/discount-breakdown',[
    'Magento_SalesRule/js/view/summary/discount',
    'jquery',
    'Magento_Checkout/js/model/quote'
], function (Component, $, quote) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Amasty_Rules/summary/discount-breakdown',
            rules: false,
            cartSelector: '.cart-summary tr.totals',
            checkoutSelector: '.totals.discount'
        },

        initObservable: function () {
            this._super();
            this.observe(['rules']);

            return this;
        },

        /**
         * initialize
         */
        initialize: function () {
            this._super();
            this.initCollapseBreakdown();
            this.rules(this.getRules());
            this.getDiscountDataFromTotals(window.checkoutConfig.totalsData)
            quote.totals.subscribe(this.getDiscountDataFromTotals.bind(this));
        },

        /**
         * getRules
         */
        getRules: function () {
            return this.amount.length ? this.amount : '';
        },

        /**
         * @override
         *
         * @returns {Boolean}
         */
        isDisplayed: function () {
            return this.getPureValue() != 0;
        },

        /**
         * @override
         *
         * @returns {Boolean}
         */
        initCollapseBreakdown: function () {
            $(document).on('click', this.checkoutSelector, this.collapseBreakdown);
            $(document).on('click', this.cartSelector, this.collapseBreakdown);
        },

        collapseBreakdown: function () {
            $('.total-rules').toggle();
            $(this).find('.title').toggleClass('-collapsed');
        },

        showDiscountArrow: function () {
            $('.totals .title').addClass('-enabled');
        },

        /**
         * @param {Array} totals
         */
        getDiscountDataFromTotals: function (totals) {
            if (totals.extension_attributes && totals.extension_attributes.amrule_discount_breakdown) {
                this.rules(totals.extension_attributes.amrule_discount_breakdown);
            } else {
                this.rules(null);
            }
        }
    });
});

define('Amasty_Promo/js/discount-calculator',[
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils'
], function ($, quote, priceUtils) {
    var discountCalculator = {
        update: function (products, item) {
            var priceHtml = $(item.target).parent().find('span[data-price-type="basePrice"]').find('span[class="price"]');
            if (priceHtml.length) {
                var itemPrice = priceHtml.html().replace(/[^.,0-9]/gim, ''),
                    discount = 0,
                    productSku = $(item.target).closest('div.ampromo-item').attr('data-product-sku'),
                    product = null;
                itemPrice = itemPrice.replace(',','.');
                if (productSku in products) {
                    product = products[productSku];
                    var promoDiscount = String(product['discount']['discount_item']),
                        minimalPrice = product['discount']['minimal_price'];
                    if (promoDiscount === "" || promoDiscount === "100%" || promoDiscount === "null") {
                        discount = itemPrice;
                    } else if (promoDiscount.indexOf("%") !== -1) {
                        discount = this.getPercentDiscount(itemPrice, promoDiscount);
                    } else if (promoDiscount.indexOf("-") !== -1) {
                        discount = this.getFixedDiscount(itemPrice, promoDiscount);
                    } else {
                        discount = this.getFixedPrice(itemPrice, promoDiscount);
                    }

                    discount = this.getDiscountAfterMinimalPrice(minimalPrice, itemPrice, discount);
                    $(item.target).parent().find('span[data-price-type="newPrice"]').find('span[class="price"]')[0].innerHTML
                        = priceUtils.formatPrice(itemPrice - discount, quote.getPriceFormat());
                }
            }
        },

        getPercentDiscount: function (itemPrice, promoDiscount) {
            var percent = parseFloat(promoDiscount.replace("%", "", promoDiscount));

            return itemPrice * percent / 100;
        },

        getFixedDiscount: function (itemPrice, promoDiscount) {
            var discount = Math.abs(promoDiscount);
            if (discount > itemPrice) {
                discount = itemPrice;
            }

            return discount;
        },

        getFixedPrice: function (itemPrice, promoDiscount) {
            var discount = itemPrice - parseFloat(promoDiscount);
            if (discount < 0) {
                discount = 0;
            }

            return discount;
        },

        getDiscountAfterMinimalPrice: function (minimalPrice, itemPrice, discount) {
            itemPrice = Number(itemPrice);
            minimalPrice = Number(minimalPrice);
            if (itemPrice > minimalPrice && itemPrice - discount < minimalPrice) {
                discount = itemPrice- minimalPrice;
            }

            return discount;
        }
    };

    return discountCalculator;
});

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

/**
 * @api
 */
define('Magento_Catalog/js/price-box',[
    'jquery',
    'Magento_Catalog/js/price-utils',
    'underscore',
    'mage/template',
    'jquery-ui-modules/widget'
], function ($, utils, _, mageTemplate) {
    'use strict';

    var globalOptions = {
        productId: null,
        priceConfig: null,
        prices: {},
        priceTemplate: '<span class="price"><%- data.formatted %></span>'
    };

    $.widget('mage.priceBox', {
        options: globalOptions,
        qtyInfo: '#qty',

        /**
         * Widget initialisation.
         * Every time when option changed prices also can be changed. So
         * changed options.prices -> changed cached prices -> recalculation -> redraw price box
         */
        _init: function initPriceBox() {
            var box = this.element;

            box.trigger('updatePrice');
            this.cache.displayPrices = utils.deepClone(this.options.prices);
        },

        /**
         * Widget creating.
         */
        _create: function createPriceBox() {
            var box = this.element;

            this.cache = {};
            this._setDefaultsFromPriceConfig();
            this._setDefaultsFromDataSet();

            box.on('reloadPrice', this.reloadPrice.bind(this));
            box.on('updatePrice', this.onUpdatePrice.bind(this));
            $(this.qtyInfo).on('input', this.updateProductTierPrice.bind(this));
            box.trigger('price-box-initialized');
        },

        /**
         * Call on event updatePrice. Proxy to updatePrice method.
         * @param {Event} event
         * @param {Object} prices
         */
        onUpdatePrice: function onUpdatePrice(event, prices) {
            return this.updatePrice(prices);
        },

        /**
         * Updates price via new (or additional values).
         * It expects object like this:
         * -----
         *   "option-hash":
         *      "price-code":
         *         "amount": 999.99999,
         *         ...
         * -----
         * Empty option-hash object or empty price-code object treats as zero amount.
         * @param {Object} newPrices
         */
        updatePrice: function updatePrice(newPrices) {
            var prices = this.cache.displayPrices,
                additionalPrice = {},
                pricesCode = [],
                priceValue, origin, finalPrice;

            this.cache.additionalPriceObject = this.cache.additionalPriceObject || {};

            if (newPrices) {
                $.extend(this.cache.additionalPriceObject, newPrices);
            }

            if (!_.isEmpty(additionalPrice)) {
                pricesCode = _.keys(additionalPrice);
            } else if (!_.isEmpty(prices)) {
                pricesCode = _.keys(prices);
            }

            _.each(this.cache.additionalPriceObject, function (additional) {
                if (additional && !_.isEmpty(additional)) {
                    pricesCode = _.keys(additional);
                }
                _.each(pricesCode, function (priceCode) {
                    priceValue = additional[priceCode] || {};
                    priceValue.amount = +priceValue.amount || 0;
                    priceValue.adjustments = priceValue.adjustments || {};

                    additionalPrice[priceCode] = additionalPrice[priceCode] || {
                        'amount': 0,
                        'adjustments': {}
                    };
                    additionalPrice[priceCode].amount =  0 + (additionalPrice[priceCode].amount || 0) +
                        priceValue.amount;
                    _.each(priceValue.adjustments, function (adValue, adCode) {
                        additionalPrice[priceCode].adjustments[adCode] = 0 +
                            (additionalPrice[priceCode].adjustments[adCode] || 0) + adValue;
                    });
                });
            });

            if (_.isEmpty(additionalPrice)) {
                this.cache.displayPrices = utils.deepClone(this.options.prices);
            } else {
                _.each(additionalPrice, function (option, priceCode) {
                    origin = this.options.prices[priceCode] || {};
                    finalPrice = prices[priceCode] || {};
                    option.amount = option.amount || 0;
                    origin.amount = origin.amount || 0;
                    origin.adjustments = origin.adjustments || {};
                    finalPrice.adjustments = finalPrice.adjustments || {};

                    finalPrice.amount = 0 + origin.amount + option.amount;
                    _.each(option.adjustments, function (pa, paCode) {
                        finalPrice.adjustments[paCode] = 0 + (origin.adjustments[paCode] || 0) + pa;
                    });
                }, this);
            }

            this.element.trigger('priceUpdated', this.cache.displayPrices);
            this.element.trigger('reloadPrice');
        },

        /*eslint-disable no-extra-parens*/
        /**
         * Render price unit block.
         */
        reloadPrice: function reDrawPrices() {
            var priceFormat = (this.options.priceConfig && this.options.priceConfig.priceFormat) || {},
                priceTemplate = mageTemplate(this.options.priceTemplate);

            _.each(this.cache.displayPrices, function (price, priceCode) {
                price.final = _.reduce(price.adjustments, function (memo, amount) {
                    return memo + amount;
                }, price.amount);

                price.formatted = utils.formatPriceLocale(price.final, priceFormat);

                $('[data-price-type="' + priceCode + '"]', this.element).html(priceTemplate({
                    data: price
                }));
            }, this);
        },

        /*eslint-enable no-extra-parens*/
        /**
         * Overwrites initial (default) prices object.
         * @param {Object} prices
         */
        setDefault: function setDefaultPrices(prices) {
            this.cache.displayPrices = utils.deepClone(prices);
            this.options.prices = utils.deepClone(prices);
        },

        /**
         * Custom behavior on getting options:
         * now widget able to deep merge of accepted configuration.
         * @param  {Object} options
         * @return {mage.priceBox}
         */
        _setOptions: function setOptions(options) {
            $.extend(true, this.options, options);

            if ('disabled' in options) {
                this._setOption('disabled', options.disabled);
            }

            return this;
        },

        /**
         * setDefaultsFromDataSet
         */
        _setDefaultsFromDataSet: function _setDefaultsFromDataSet() {
            var box = this.element,
                priceHolders = $('[data-price-type]', box),
                prices = this.options.prices;

            this.options.productId = box.data('productId');

            if (_.isEmpty(prices)) {
                priceHolders.each(function (index, element) {
                    var type = $(element).data('priceType'),
                        amount = parseFloat($(element).data('priceAmount'));

                    if (type && !_.isNaN(amount)) {
                        prices[type] = {
                            amount: amount
                        };
                    }
                });
            }
        },

        /**
         * setDefaultsFromPriceConfig
         */
        _setDefaultsFromPriceConfig: function _setDefaultsFromPriceConfig() {
            var config = this.options.priceConfig;

            if (config && config.prices) {
                this.options.prices = config.prices;
            }
        },

        /**
         * Updates product final and base price according to tier prices
         */
        updateProductTierPrice: function updateProductTierPrice() {
            var originalPrice,
                prices = {'prices': {}};

            if (this.options.prices.finalPrice) {
                originalPrice = this.options.prices.finalPrice.amount;
                prices.prices.finalPrice = {'amount': this.getPrice('price') - originalPrice};
            }

            if (this.options.prices.basePrice) {
                originalPrice = this.options.prices.basePrice.amount;
                prices.prices.basePrice = {'amount': this.getPrice('basePrice') - originalPrice};
            }

            this.updatePrice(prices);
        },

        /**
         * Returns price.
         *
         * @param {String} priceKey
         * @returns {Number}
         */
        getPrice: function (priceKey) {
            var productQty = $(this.qtyInfo).val(),
                result,
                tierPriceItem,
                i;

            for (i = 0; i < this.options.priceConfig.tierPrices.length; i++) {
                tierPriceItem = this.options.priceConfig.tierPrices[i];
                if (productQty >= tierPriceItem.qty && tierPriceItem[priceKey]) {
                    result = tierPriceItem[priceKey];
                }
            }

            return result;
        }
    });

    return $.mage.priceBox;
});

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

define('Magento_Catalog/js/price-options',[
    'jquery',
    'underscore',
    'mage/template',
    'priceUtils',
    'priceBox',
    'jquery-ui-modules/widget'
], function ($, _, mageTemplate, utils) {
    'use strict';

    var globalOptions = {
        productId: null,
        priceHolderSelector: '.price-box', //data-role="priceBox"
        optionsSelector: '.product-custom-option',
        optionConfig: {},
        optionHandlers: {},
        optionTemplate: '<%= data.label %>' +
        '<% if (data.finalPrice.value > 0) { %>' +
        ' +<%- data.finalPrice.formatted %>' +
        '<% } else if (data.finalPrice.value < 0) { %>' +
        ' <%- data.finalPrice.formatted %>' +
        '<% } %>',
        controlContainer: 'dd'
    };

    /**
     * Custom option preprocessor
     * @param  {jQuery} element
     * @param  {Object} optionsConfig - part of config
     * @return {Object}
     */
    function defaultGetOptionValue(element, optionsConfig) {
        var changes = {},
            optionValue = element.val(),
            optionId = utils.findOptionId(element[0]),
            optionName = element.prop('name'),
            optionType = element.prop('type'),
            optionConfig = optionsConfig[optionId],
            optionHash = optionName;

        switch (optionType) {
            case 'text':
            case 'textarea':
                changes[optionHash] = optionValue ? optionConfig.prices : {};
                break;

            case 'radio':
                if (element.is(':checked')) {
                    changes[optionHash] = optionConfig[optionValue] && optionConfig[optionValue].prices || {};
                }
                break;

            case 'select-one':
                changes[optionHash] = optionConfig[optionValue] && optionConfig[optionValue].prices || {};
                break;

            case 'select-multiple':
                _.each(optionConfig, function (row, optionValueCode) {
                    optionHash = optionName + '##' + optionValueCode;
                    changes[optionHash] = _.contains(optionValue, optionValueCode) ? row.prices : {};
                });
                break;

            case 'checkbox':
                optionHash = optionName + '##' + optionValue;
                changes[optionHash] = element.is(':checked') ? optionConfig[optionValue].prices : {};
                break;

            case 'file':
                // Checking for 'disable' property equal to checking DOMNode with id*="change-"
                changes[optionHash] = optionValue || element.prop('disabled') ? optionConfig.prices : {};
                break;
        }

        return changes;
    }

    $.widget('mage.priceOptions', {
        options: globalOptions,

        /**
         * @private
         */
        _init: function initPriceBundle() {
            $(this.options.optionsSelector, this.element).trigger('change');
        },

        /**
         * Widget creating method.
         * Triggered once.
         * @private
         */
        _create: function createPriceOptions() {
            var form = this.element,
                options = $(this.options.optionsSelector, form),
                priceBox = $(this.options.priceHolderSelector, $(this.options.optionsSelector).element);

            if (priceBox.data('magePriceBox') &&
                priceBox.priceBox('option') &&
                priceBox.priceBox('option').priceConfig
            ) {
                if (priceBox.priceBox('option').priceConfig.optionTemplate) {
                    this._setOption('optionTemplate', priceBox.priceBox('option').priceConfig.optionTemplate);
                }
                this._setOption('priceFormat', priceBox.priceBox('option').priceConfig.priceFormat);
            }

            this._applyOptionNodeFix(options);

            options.on('change', this._onOptionChanged.bind(this));
        },

        /**
         * Custom option change-event handler
         * @param {Event} event
         * @private
         */
        _onOptionChanged: function onOptionChanged(event) {
            var changes,
                option = $(event.target),
                handler = this.options.optionHandlers[option.data('role')];

            option.data('optionContainer', option.closest(this.options.controlContainer));

            if (handler && handler instanceof Function) {
                changes = handler(option, this.options.optionConfig, this);
            } else {
                changes = defaultGetOptionValue(option, this.options.optionConfig);
            }
            $(this.options.priceHolderSelector).trigger('updatePrice', changes);
        },

        /**
         * Helper to fix issue with option nodes:
         *  - you can't place any html in option ->
         *    so you can't style it via CSS
         * @param {jQuery} options
         * @private
         */
        _applyOptionNodeFix: function applyOptionNodeFix(options) {
            var config = this.options,
                format = config.priceFormat,
                template = config.optionTemplate;

            template = mageTemplate(template);
            options.filter('select').each(function (index, element) {
                var $element = $(element),
                    optionId = utils.findOptionId($element),
                    optionConfig = config.optionConfig && config.optionConfig[optionId];

                $element.find('option').each(function (idx, option) {
                    var $option,
                        optionValue,
                        toTemplate,
                        prices;

                    $option = $(option);
                    optionValue = $option.val();

                    if (!optionValue && optionValue !== 0) {
                        return;
                    }

                    toTemplate = {
                        data: {
                            label: optionConfig[optionValue] && optionConfig[optionValue].name
                        }
                    };
                    prices = optionConfig[optionValue] ? optionConfig[optionValue].prices : null;

                    if (prices) {
                        _.each(prices, function (price, type) {
                            var value = +price.amount;

                            value += _.reduce(price.adjustments, function (sum, x) { //eslint-disable-line
                                return sum + x;
                            }, 0);
                            toTemplate.data[type] = {
                                value: value,
                                formatted: utils.formatPriceLocale(value, format)
                            };
                        });

                        $option.text(template(toTemplate));
                    }
                });
            });
        },

        /**
         * Custom behavior on getting options:
         * now widget able to deep merge accepted configuration with instance options.
         * @param  {Object}  options
         * @return {$.Widget}
         * @private
         */
        _setOptions: function setOptions(options) {
            $.extend(true, this.options, options);
            this._super(options);

            return this;
        }
    });

    return $.mage.priceOptions;
});

define('Amasty_Promo/js/popup',[
    'jquery',
    'underscore',
    'Amasty_Promo/js/discount-calculator',
    'Amasty_Base/vendor/slick/slick.min',
    'priceOptions',
    'Magento_Ui/js/modal/modal'
], function ($, _, discount) {
    'use strict';

    var RULE_TYPE_ONE = '1',
        RULE_TYPE_ALL = '0';

    $.widget('mage.ampromoPopup', {
        options: {
            slickSettings: {},
            sourceUrl: '',
            uenc: '',
            commonQty: 0,
            products: {},
            promoSku: {},
            formUrl: '',
            selectionMethod: 0,
            giftsCounter: 0,
            autoOpenPopup: 0,
            sliderItemsCount: 3,
            sliderWidthItem: 280,
            reloading: false,
            loading: true,
            delay: 1000
        },
        selectors: {
            leftNode: '[data-ampromo-js="qty-left-text"]',
            qtyInputNode: '[data-am-js="ampromo-qty-input"]'
        },
        isSliderInitialized: false,
        isMultipleMethod: 1,
        isEnableGiftsCounter: 1,
        isOpen: false,
        initPopup: false,
        openPopupAfterLoadTotals: false,

        /**
         * @private
         * @returns {void}
         */
        _create: function () {
            var products = $.extend({}, this.options.products);

            this.autoOpen = this.options.autoOpenPopup || window.location.hash === '#choose-gift';
            if (this.autoOpen) {
                this.show();
            }
            this.delay = this.options.delay;
            this.cancelLoading = true;
            this.options.promoSku = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['promo_sku'] : this.options.promoSku;
            this.options.products = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['triggered_products'] : null;
        },

        /**
         * @private
         * @returns {void}
         */
        _init: function () {
            this._initElements();
            this._initHandles();
        },

        /**
         * @private
         * @returns {void}
         */
        _initElements: function () {
            this.message = $('[data-ampopup-js="message"]');
            this.container = $('[data-ampromo-js="popup-container"]', this.element);
            this.titlePopup = $('[data-ampromo-js="popup-title"]', this.element);

            /**
             * @todo Change selector in CS ex. [data-ampromo-js]
             */
            this.showPopup = $('[data-role="ampromo-popup-show"]');
        },

        /**
         * @private
         * @returns {void}
         */
        _initHandles: function () {
            var self = this;

            self.element.on('mousedown', function (event) {
                var target = $(event.target);

                if (target.data('role') === 'ampromo-overlay') {
                    event.stopPropagation();
                    self.hide();
                }
            });
            self.showPopup.on('click', $.proxy(self.show, self));
            $(document).on('click', '[data-role="ampromo-popup-hide"]', $.proxy(self.hide, self));
            $(document).on('reloadPrice', function (item) {
                var products = $.extend({}, self.options.products);

                self.options.promoSku = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                    products['promo_sku'] : self.options.promoSku;
                discount.update(self.options.promoSku, item);
            });
        },

        /**
         * @returns {void}
         */
        show: function () {
            if (!this.isSliderInitialized) {
                this._initContent();
            }

            if (this.options.selectionMethod === this.isMultipleMethod) {
                this.checkAddButton();
            }

            if (!this.isOpen) {
                this.element.addClass('-show');
                this.isOpen = true;
            }
        },

        /**
         * @returns {void}
         */
        checkAddButton: function () {
            var self = this,
                stateCheckbox = false,
                stateInputs = true;

            this.productSelects.each(function () {
                if ($(this).children().prop('checked')) {
                    stateCheckbox = true;
                }
            });

            $.each(this.element.find('[data-am-js=ampromo-qty-input]'), function () {
                if ($(this).val() < 0 && !$(this).prop('disabled')) {
                    stateInputs = false;

                    return false;
                }

                return true;
            });

            if (stateCheckbox && stateInputs) {
                self.addToCartDisableOrEnable(false);
            } else {
                self.addToCartDisableOrEnable(true);
            }
        },

        /**
         * @param {Boolean} state
         * @returns {void}
         */
        addToCartDisableOrEnable: function (state) {
            this.element.find('[data-role=ampromo-item-buttons] button').attr('disabled', state);
        },

        /**
         * @returns {void}
         */
        hide: function () {
            this.isOpen = false;
            this.isClose = true;
            this.element.removeClass('-show');
        },

        /**
         *
         * @returns {void}
         */
        _loadItems: function () {
            var onSuccess = this._success.bind(this),
                config = {
                    url: this.options.sourceUrl,
                    method: 'GET',
                    data: {
                        uenc: this.options.uenc
                    },
                    success: onSuccess
                };

            $.ajax(config);
        },

        /**
         * @param {JSON} response
         * @param {String} response.popup
         * @param {Object} response.products
         * @returns {void}
         * @private
         */
        _success: function (response) {
            var isReload = !_.isEmpty(this.response) &&
                this.response.popup === response.popup &&
                this.response.products['common_qty'] === response.products['common_qty'];

            if (isReload) {
                this._initLoading();

                return;
            }

            this.response = $.extend({}, response);
            this.isSliderInitialized = false;
            this.container.html(response.popup);
            this.options.products = response.products;
            this.itemsCount = this.container.children().length;
            this.hasContent = !!this.itemsCount;

            if (this.hasContent) {
                this._initContent();
                this.container.trigger('contentUpdated');
                this._calcWidthTitle();
            }

            this._toggleMessage();

            if (this.response.autoOpenPopup) {
                this.autoOpen = true;
                this.isClose = false;
            }

            if (this.autoOpen) {
                if (!this.initPopup &&
                    this.hasContent &&
                    !this.isClose
                ) {
                    this.show();
                    this.initPopup = true;
                }

                this._trigger('init.ampopup');
            }
        },

        /**
         * @returns {void}
         */
        _initContent: function () {
            var products = $.extend({}, this.options.products);

            this.options.commonQty = 'common_qty' in products ?
                products['common_qty'] : this.options.commonQty;
            this.options.promoSku = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['promo_sku'] : this.options.promoSku;
            this.options.products = Object.prototype.hasOwnProperty.call(products, 'triggered_products') ?
                products['triggered_products'] : products;
            this._initElementsContent();
            this._initLoading();
            this._initOptions();
            this._initSlider();

            $('.ampromo-items-form').mage('validation');
        },

        /**
         * @private
         * @returns {void}
         */
        _initLoading: function () {
            var loadingElem,
                self = this,
                onRemoveLoading = self._removeLoading.bind(self);

            if (!self.hasContent) {
                return;
            }

            if (!self.options.loading) {
                self._removeLoading();

                return;
            }

            loadingElem = $('<div>', {
                class: 'ampromo-loading -show'
            });
            self.container.append(loadingElem);
            self.productList.addClass('-loading');
            self.loader = _.debounce(function () {
                if (self.cancelLoading) {
                    onRemoveLoading();
                }
            }, self.delay);
            self.loader();
        },

        /**
         * @private
         * @returns {void}
         */
        _removeLoading: function () {
            this.productList.removeClass('-loading');
            $('.ampromo-loading').removeClass('-show');
        },

        /**
         * @private
         * @returns {void}
         */
        _initElementsContent: function () {
            this.gallery = this.element.find('[data-role="ampromo-gallery"]');
            this.productList = this.element.find('[data-ampromo-js="popup-products"]');
            this.productSelects = this.element.find('[data-role="ampromo-product-select"]');
            this.productInputsQty = this.element.find('[data-am-js=ampromo-qty-input]');
            this.promoItems = this.element.find('[data-role=ampromo-item]');
        },

        /**
         * @returns {void}
         */
        _initOptions: function () {
            if (this.options.selectionMethod === this.isMultipleMethod) {
                this.initMultipleProductAdd();
            } else {
                this.initOneByOneProductAdd();
            }

            if (this.options.giftsCounter === this.isEnableGiftsCounter) {
                this.initProductQtyState();
                this.addCounterToPopup();

                if (this.options.selectionMethod === this.isMultipleMethod) {
                    this.addToCartDisableOrEnable(true);
                }
            }
        },

        /**
         * @returns {void}
         */
        initMultipleProductAdd: function () {
            var self = this,
                addButton = this.element.find('[data-am-js="ampromo-add-button"]'),
                onInitHandlersInputQty = self._initHandlersInputQty.bind(self),
                onInitHandlersProducts = self._initHandlersProducts.bind(self);

            this.productSelects.each(function () {
                var selectElem = $(this);

                selectElem.children().off('click').on('click', self._choiceProduct);
            });
            this.productInputsQty.each(onInitHandlersInputQty);
            this.promoItems.each(onInitHandlersProducts);
            addButton.off('click').on('click', function () {
                self.sendForm();
            });

            self.checkAddButton();
        },

        /**
         * @private
         * @returns {void}
         */
        _choiceProduct: function () {
            var checkbox = $(this),
                value = !checkbox.prop('checked');

            checkbox.prop('checked', value);
        },

        /**
         * @param {Number} index
         * @param {Element} element
         * @private
         * @returns {void}
         */
        _initHandlersInputQty: function (index, element) {
            var self = this,
                qtyInput = $(element),
                onDragEvent = this._isDragEventInit.bind(this);

            qtyInput.keyup(function () {
                self.checkAddButton();
                $.validator.validateSingleElement(this);
            });

            qtyInput.mouseenter(function () {
                if (onDragEvent()) {
                    self.gallery.slick('slickSetOption', 'draggable', false, false);
                }
            });

            qtyInput.mouseleave(function () {
                if (onDragEvent()) {
                    self.gallery.slick('slickSetOption', 'draggable', true, true);
                }
            });
        },

        /**
         * @private
         * @returns {Boolean}
         */
        _isDragEventInit: function () {
            var slickSettingsCurrent = this.gallery[0].slick.options,
                itemsCount = this.gallery.data('count'),
                slidesToShowCurrent = slickSettingsCurrent.slidesToShow;

            return itemsCount > slidesToShowCurrent;
        },

        /**
         * @param {Number} index
         * @param {Element} element
         * @private
         * @returns {void}
         */
        _initHandlersProducts: function (index, element) {
            var promoItems = $(element),
                self = this;

            promoItems
                .off('mousedown')
                .on('mousedown', function () {
                    self.slickStartTransform = $('.slick-track').css('transform');
                })
                .off('mouseup')
                .on('mouseup', {
                    'context': self
                }, self._onClickProduct);
        },

        /**
         * @param {Object} event
         * @private
         * @returns {void}
         */
        _onClickProduct: function (event) {
            var self = event.data.context,
                promoItem = $(this),
                excludedTags = ['INPUT', 'SELECT', 'LABEL', 'TEXTAREA'],
                currentAllowedQty = self.options.commonQty,
                isCheckbox,
                isInputQty,
                isAllowedTags,
                checkbox,
                qtyInput;

            self.slickEndTransform = $('.slick-track').css('transform');

            if (self.slickStartTransform !== self.slickEndTransform) {
                return;
            }

            checkbox = promoItem.find('[data-role=ampromo-product-select] input');
            qtyInput = promoItem.find('[data-am-js=ampromo-qty-input]');
            isCheckbox = event.target === checkbox[0];
            isInputQty = event.target === qtyInput[0] && qtyInput.prop('disabled');
            isAllowedTags = excludedTags.indexOf(event.target.tagName) === -1 &&
                excludedTags.indexOf(event.target.parentElement.tagName) === -1;

            if (self.options.giftsCounter !== self.isEnableGiftsCounter) {
                currentAllowedQty = currentAllowedQty - self.getSumQtys();
            }

            if (isCheckbox || isInputQty || isAllowedTags) {
                if (currentAllowedQty > 0 || promoItem.hasClass('-selected')) {
                    promoItem.toggleClass('-selected');
                    checkbox.prop('checked', !checkbox.prop('checked'));
                    self.checkboxState(checkbox);
                    self.checkAddButton();
                }
            }
        },

        /**
         * @returns {void}
         */
        sendForm: function () {
            var formData = this._prepareFormData(),

                /**
                 * @returns {void}
                 */
                onSuccess = function () {
                    window.location.reload();
                };

            this.addToCartDisableOrEnable(true);
            $.ajax({
                type: 'POST',
                url: this.options.formUrl,
                data: {
                    uenc: this.options.uenc,
                    data: formData
                },
                success: onSuccess
            });
        },

        _prepareFormData: function () {
            var formData = [],
                re = /\[(.*?)\]/,
                form = this.element.find('[data-ampromo-js="form-item"]');

            form.each(function (index, element) {
                var $element = $(element),
                    propertyTemp = {},
                    tmpBundleOpt = {},
                    tmpBundleQtyOpt = {},
                    tmpBundleMultiSelect = [];


                if (!$element.find('input[type="checkbox"]').prop('checked')) {
                    return true;
                }

                formData[index] = $element.serializeArray().reduce(function (obj, item) {
                    var key,
                        keyName,
                        selectKey,
                        tmpBundleCheckbox = {},
                        links = [];

                    if (item.name.indexOf('super_attribute') >= 0 || item.name.indexOf('options') >= 0) {
                        key = item.name.match(re)[1];
                        keyName = item.name.indexOf('super_attribute') >= 0 ? 'super_attribute' : 'options';

                        propertyTemp[key] = item.value;
                        obj[keyName] = propertyTemp;
                    } else if (item.name.indexOf('bundle_option_qty') >= 0) {
                        key = item.name.match(re)[1];
                        keyName = 'bundle_option_qty';
                        tmpBundleQtyOpt[key] = item.value;
                        obj[keyName] = tmpBundleQtyOpt;
                    } else if (item.name.indexOf('bundle_option') >= 0) {
                        key = item.name.match(re)[1];
                        keyName = 'bundle_option';
                        if (/\[]$/.test(item.name)) {
                            if (tmpBundleMultiSelect[key] === undefined) {
                                tmpBundleMultiSelect[key] = [];
                            }

                            tmpBundleMultiSelect[key].push(item.value);
                            tmpBundleOpt[key] = tmpBundleMultiSelect[key];
                        } else if (/\[(.*?)\]\[(.*?)\]$/.test(item.name)) {
                            selectKey = item.name.match(/\]\[(.*?)\]/)[1];
                            tmpBundleCheckbox[selectKey] = item.value;
                            if (tmpBundleOpt[key] === undefined) {
                                tmpBundleOpt[key] = {};
                            } else if (tmpBundleOpt[key][selectKey] === undefined) {
                                tmpBundleOpt[key][selectKey] = {};
                            }

                            tmpBundleOpt[key][selectKey] = item.value;
                        } else {
                            tmpBundleOpt[key] = item.value;
                        }

                        obj[keyName] = tmpBundleOpt;
                    } else if (item.name.indexOf('links[]') >= 0) {
                        links.push(item.value);
                        obj.links = links;
                    } else {
                        obj[item.name] = item.value;
                    }

                    return obj;
                }, {});

                formData[index]['rule_id'] = $element.find('.ampromo-qty').attr('data-rule');

                return true;
            });

            return formData;
        },

        /**
         * @returns {void}
         */
        initOneByOneProductAdd: function () {
            var onInitHandlersOneProductAdd = this.initHandlersOneProductAdd.bind(this);

            this.promoItems.each(onInitHandlersOneProductAdd);
        },

        /**
         * @param {Number} index
         * @param {Element} element
         * @private
         * @returns {void}
         */
        initHandlersOneProductAdd: function (index, element) {
            var promoItem = $(element);

            if (promoItem.find('.ampromo-options .fieldset .field').length !== 0) {
                promoItem.find('.tocart').off('click').on('click', function () {
                    $('.ampromo-item.-selected').removeClass('-selected');
                    promoItem.addClass('-selected');
                });
            }
        },

        /**
         * @returns {void}
         */
        initProductQtyState: function () {
            var self = this;

            this._setQtys();
            this.productInputsQty.each(function (index, element) {
                $(element).off('keyup').on('keyup', function () {
                    var qtyInput = $(this);

                    self._changeQty(qtyInput);
                    self.checkAddButton();
                    $.validator.validateSingleElement(this);
                });
            });
        },

        /**
         * @private
         * @returns {void}
         */
        _setQtys: function () {
            this._updateCommonQty();
            this._updateProductLeftQty();
        },

        /**
         * @private
         * @returns {void}
         */
        _updateCommonQty: function () {
            this.element.find('[data-role=ampromo-popup-common-qty]').html(this.options.commonQty);
        },

        /**
         * @private
         * @returns {Number} left value for target product
         */
        _getProductLeftQty: function(inputValue, item){
            var result;

            if (inputValue) {
                result = item.available_qty - inputValue > this.options.commonQty
                    ? this.options.commonQty
                    : item.available_qty - inputValue;
            } else {
                result = item.available_qty > this.options.commonQty
                    ? this.options.commonQty : item.available_qty;
            }

            if (Math.sign(result) === -1) {
                result = 0;
            }

            return result;
        },

        /**
         * @private
         * @returns {void}
         */
        _updateProductLeftQty: function () {
            var self = this;

            $.each(this.options.products, function (ruleId, rulesData) {
                var id = ruleId,
                    ruleType = rulesData['rule_type'];

                $.each(rulesData.sku, function (key, item) {
                    var productDomBySku = self.getProductDomBySku(key),
                        qtyInput = productDomBySku ? productDomBySku.find(self.selectors.qtyInputNode) : false,
                        inputValue,
                        leftNode,
                        qtyInt,
                        maxQty;

                    if (!qtyInput) {
                        return false;
                    }

                    leftNode = productDomBySku.find(self.selectors.leftNode);
                    inputValue = +qtyInput.val();
                    qtyInt = self._getProductLeftQty(inputValue, item);

                    maxQty = item.available_qty > self.options.commonQty
                        ? qtyInt + inputValue
                        : item.available_qty;

                    qtyInput.attr('data-rule', id);
                    qtyInput.attr('data-rule-type', ruleType);
                    qtyInput.attr('max', maxQty);

                    leftNode.html(qtyInt);
                });
            });
        },

        /**
         * @param {String} sku
         * @returns {jQuery}
         */
        getProductDomBySku: function (sku) {
            return this.getProductDom('data-product-sku', sku);
        },

        /**
         * @param {String} attribute
         * @param {String} value
         * @returns {jQuery|HTMLElement}
         */
        getProductDom: function (attribute, value) {
            var result = false;

            this.promoItems.each(function () {
                var promoItem = $(this),
                    attrValue = promoItem.attr(attribute);

                if (value === attrValue) {
                    result = promoItem;
                }
            });

            return result;
        },

        /**
         *
         * @param {jQuery} elem
         * @returns {void | Boolean}
         */
        _changeQty: function (elem) {
            var value = +elem.val(),
                maxValue = elem.attr('max'),
                newQty = value === '' ? 0 : parseInt(value, 10),
                productSku = this.getProductSku(elem),
                ruleId = this.getRuleId(elem),
                ruleType = this.getRuleType(elem);

            if (value > +maxValue) {
                elem.val(maxValue);
                newQty = maxValue;
            }

            this.updateValues(newQty, productSku, ruleId, ruleType, elem);
            this._setQtys();
        },

        /**
         * @param {Number} newQty
         * @param {String} productSku
         * @param {String} ruleId
         * @param {String} ruleType
         * @param {jQuery} elem
         * @returns {void}
         */
        updateValues: function (newQty, productSku, ruleId, ruleType, elem) {
            var self = this,
                newValue = 0,
                qty = newQty,
                countOfThisFreeItem = 0,
                countOfRulesFreeItem = 0,
                sumQtyByRuleId,
                itemRuleType;

            if (!this.isValidNumber(qty) || newQty > +elem.attr('max')) {
                return;
            }

            $.each(this.options.products, function (itemRuleId, ruleData) {
                var allSkuForRule = Object.keys(ruleData.sku),
                    firstSku = self.getFirstAvailableSku(allSkuForRule, ruleData);

                itemRuleType = self.options.products[itemRuleId]['rule_type'];

                switch (itemRuleType) {
                    case '1':
                        countOfRulesFreeItem += ruleData.sku[firstSku]['initial_value'];
                        break;

                    case '0':
                        $.each(self.options.products[itemRuleId].sku, function (itemSku, skuProps) {
                            countOfRulesFreeItem += skuProps['initial_value'];
                        });
                        break;

                    default:
                        break;
                }

                $.each(ruleData.sku, function (skuId, skuProps) {
                    sumQtyByRuleId = self.getSumQtysByRuleId()[itemRuleId];
                    countOfThisFreeItem = +self.options.promoSku[skuId].qty;

                    if (itemRuleId !== ruleId) {
                        return;
                    }

                    if (ruleType === RULE_TYPE_ONE) {
                        if (qty < countOfThisFreeItem - (sumQtyByRuleId - qty)) {
                            newValue = countOfThisFreeItem - sumQtyByRuleId;
                        } else if (productSku === skuId) {
                            newValue = 0;
                            qty = countOfThisFreeItem;
                        }

                        self.setProductQty(ruleId, skuId, qty, skuProps, newValue);
                    }

                    if (ruleType === RULE_TYPE_ALL && productSku === skuId) {
                        if (qty > countOfThisFreeItem) {
                            qty = countOfThisFreeItem;
                            elem.val(qty);
                        }

                        if (qty === 0) {
                            newValue = countOfThisFreeItem;
                        } else if (qty <= countOfThisFreeItem) {
                            newValue = countOfThisFreeItem - qty;
                        } else {
                            newValue = 0;
                            qty = countOfThisFreeItem;
                        }

                        self.setProductQty(ruleId, skuId, qty, skuProps, newValue);
                    }
                });
            });

            if (self.getSumQtys() < countOfRulesFreeItem) {
                this.options.commonQty = countOfRulesFreeItem - self.getSumQtys();
            } else {
                this.options.commonQty = 0;
            }
        },

        /**
         * @param allSkuForRule
         * @param ruleData
         * @returns {String}
         */
        getFirstAvailableSku: function (allSkuForRule, ruleData) {
            let maxQty = 0;
            let maxIndex = 0;

            for (let index = 0; index < allSkuForRule.length; index++) {
                if (ruleData.sku[allSkuForRule[index]].qty > maxQty
                    && ruleData.sku[allSkuForRule[index]].available_qty != 0
                ) {
                    maxQty = ruleData.sku[allSkuForRule[index]].qty;
                    maxIndex = index;
                }
            }

            return allSkuForRule[maxIndex];
        },

        /**
         * @returns {Object}
         */
        getSumQtysByRuleId: function () {
            var sumQtysByRuleId = {};

            $.each($('[data-am-js=ampromo-qty-input]'), function () {
                var itemRuleId = $(this).attr('data-rule'),
                    value = $(this).val(),
                    qty = value === '' ? 0 : parseInt(value, 10);

                if (qty >= 0) {
                    if (sumQtysByRuleId[itemRuleId]) {
                        sumQtysByRuleId[itemRuleId] += qty;
                    } else {
                        sumQtysByRuleId[itemRuleId] = qty;
                    }
                }
            });

            return sumQtysByRuleId;
        },

        /**
         * @returns {Number}
         */
        getSumQtys: function () {
            var sumQtys = 0;

            this.element.find('[data-am-js=ampromo-qty-input]').each(function () {
                var value = this.value,
                    qty = value === '' ? 0 : parseInt(value, 10);

                if (qty >= 0) {
                    sumQtys += qty;
                }
            });

            return sumQtys;
        },

        /**
         * @returns {void}
         */
        addCounterToPopup: function () {
            var self = this;

            $.each(this.options.products, function (ruleId, ruleData) {
                $.each(ruleData.sku, function (skuId, itemData) {
                    self.options.products[ruleId].sku[skuId]['old_value'] = itemData.qty;
                    self.options.products[ruleId].sku[skuId]['initial_value'] = itemData.qty;
                });
            });
        },

        /**
         * @private
         * @returns {void}
         */
        _initSlider: function () {
            if (this.gallery.hasClass('slick-initialized')) {
                this.gallery.slick('unslick');
            }

            this.gallery.slick(this.options.slickSettings);
            this.isSliderInitialized = true;
        },

        /**
         * @returns {void}
         */
        _calcWidthTitle: function () {
            var itemsCountReal = +this.gallery.data('count'),
                titleWidth = itemsCountReal >= this.options.sliderItemsCount ?
                    this.options.sliderItemsCount * this.options.sliderWidthItem :
                    itemsCountReal * this.options.sliderWidthItem;

            this.titlePopup.css('max-width', titleWidth + 'px');
        },

        /**
         * @returns {void}
         */
        _toggleMessage: function () {
            var isToggle = this._isToggleMessage();

            this.message.toggle(isToggle);
        },

        /**
         * @returns {Boolean}
         */
        _isToggleMessage: function () {
            return this.itemsCount > 0;
        },

        /**
         * @param {String} ruleId
         * @param {String} skuId
         * @param {Number} newQty
         * @param {Object} skuProps
         * @param {Number} newValue
         * @returns {void}
         */
        setProductQty: function (ruleId, skuId, newQty, skuProps, newValue) {
            this.options.products[ruleId].sku[skuId].qty =
                newQty === skuProps['old_value'] || this.isValidNumber(newValue) || newValue === 0 ?
                    newValue :
                    skuProps['old_value'];
        },

        /**
         * @param {Number} value
         * @returns {Boolean}
         */
        isValidNumber: function (value) {
            var isValid = $.isNumeric(value);

            if (value < 0 || !isValid) {
                this.addToCartDisableOrEnable(true);

                return false;
            }

            return true;
        },

        /**
         * @param {jQuery} elem
         * @returns {mage.ampromoPopup}
         */
        checkboxState: function (elem) {
            var product = this.getProductDomByElem(elem),
                selectInput = product
                    .find('[data-am-js="ampromo-qty-input"]'),
                isChecked = $(elem).prop('checked'),
                value = isChecked ? 1 : 0;

            selectInput.val(value);
            selectInput.keyup().prop('disabled', !isChecked);

            return this;
        },

        /**
         * @param {jQuery} elem
         * @returns {String}
         */
        getProductSku: function (elem) {
            return this.getProductDomByElem(elem).attr('data-product-sku');
        },

        /**
         * @param {jQuery} elem
         * @returns {String}
         */
        getRuleId: function (elem) {
            return this.getProductDomByElem(elem).find('.ampromo-qty').attr('data-rule');
        },

        /**
         * @param {jQuery} elem
         * @returns {String}
         */
        getRuleType: function (elem) {
            return this.getProductDomByElem(elem).find('.ampromo-qty').attr('data-rule-type');
        },

        /**
         * @param {jQuery} elem
         * @returns {jQuery}
         */
        getProductDomByElem: function (elem) {
            return elem.parents('[data-role=ampromo-item]');
        },

        /**
         * @returns {void}
         */
        reload: function () {
            this._loadItems();
            this.initPopup = false;
            this.options.loading = false;
            this.cancelLoading = false;
        }
    });

    return $.mage.ampromoPopup;
});

/**
 * Copyright © Born, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define('Born_GrabExpress/js/model/address-converter-mixin',[
    'jquery',
    'mage/utils/wrapper'
], function ($, wrapper) {
    'use strict';

    return function (addressConverter) {
        addressConverter.quoteAddressToFormAddressData =
            wrapper.wrapSuper(addressConverter.quoteAddressToFormAddressData, function (addrs) {
                var output = this._super(addrs);
                var customAttributesObject;
                if ($.isArray(addrs.customAttributes)) {
                    customAttributesObject = {};
                    addrs.customAttributes.forEach(function (value) {
                        customAttributesObject[value.attribute_code] = value.value;
                    });
                    output.custom_attributes = customAttributesObject;
                }

                return output;
        });

        return addressConverter;
    };
});

define('text!Magento_Weee/template/checkout/summary/weee.html',[],function () { return '<!--\n/**\n* Copyright © Magento, Inc. All rights reserved.\n* See COPYING.txt for license details.\n*/\n-->\n<!-- ko if: isDisplayed() -->\n<tr class="totals">\n    <th data-bind="text: title" class="mark" scope="row"></th>\n    <td class="amount" data-bind="attr: {\'data-th\': title}">\n        <span class="price" data-bind="text: getValue()"></span>\n    </td>\n</tr>\n<!-- /ko -->\n';});

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

define('Magento_InventoryInStorePickupFrontend/js/checkout-data-ext',[
    'Magento_Customer/js/customer-data'
], function (
    storage
) {
    'use strict';

    return function (checkoutData) {

        var cacheKey = 'checkout-data',

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

            /**
             * @return {Object}
             */
            getData = function () {
                //Makes sure that checkout storage is initiated (any method can be used)
                checkoutData.getSelectedShippingAddress();

                return storage.get(cacheKey)();
            };

        /**
         * Save the pickup address in persistence storage
         *
         * @param {Object} data
         */
        checkoutData.setSelectedPickupAddress = function (data) {
            var obj = getData();

            obj.selectedPickupAddress = data;
            saveData(obj);
        };

        /**
         * Get the pickup address from persistence storage
         *
         * @return {*}
         */
        checkoutData.getSelectedPickupAddress = function () {
            return getData().selectedPickupAddress || null;
        };

        return checkoutData;
    };
});

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

define('Magento_InventoryInStorePickupFrontend/js/model/quote-ext',[
    'ko',
    'Magento_InventoryInStorePickupFrontend/js/model/pickup-address-converter'
], function (ko, pickupAddressConverter) {
    'use strict';

    return function (quote) {
        var shippingAddress = quote.shippingAddress;

        /**
         * Makes sure that shipping address gets appropriate type when it points
         * to a store pickup location.
         */
        quote.shippingAddress = ko.pureComputed({
            /**
             * Return quote shipping address
             */
            read: function () {
                return shippingAddress();
            },

            /**
             * Set quote shipping address
             */
            write: function (address) {
                shippingAddress(
                    pickupAddressConverter.formatAddressToPickupAddress(address)
                );
            }
        });

        return quote;
    };
});


define('text!Amasty_Rules/template/summary/discount-breakdown.html',[],function () { return '<!-- ko if: rules -->\n<!-- ko foreach: {data: rules, as: \'rule\', afterRender: showDiscountArrow} -->\n<tr class="total-rules">\n    <th class="mark" scope="row">\n        <span class="rule-name" data-bind="text:rule.rule_name"></span>\n    </th>\n    <td class="amount">\n        <span class="rule-amount" data-bind="text:rule.rule_amount"></span>\n    </td>\n</tr>\n<!-- /ko -->\n<!-- /ko -->\n';});


define('text!Born_Midtrans/template/checkout/cart/totals/CreditCardFee.html',[],function () { return '<!--\n/**\n * @package   Born_Midtrans\n * @author    Parveen Kumar\n * @copyright 2024 Copyright Born Group, Inc. http://www.borngroup.com/\n * @license   http://www.borngroup.com/\n */\n-->\n<!-- ko -->\n<!-- ko if: (getValue())-->\n<tr class="totals fee excl">\n    <th class="mark" colspan="1" scope="row" data-bind="text: title"></th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValue()"></span>\n    </td>\n</tr>\n<!--/ko-->\n<!-- /ko -->\n';});

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

define('Born_MapClub/js/model/quote-mixin',[
    'mage/utils/wrapper',
    'Born_MapClub/js/model/payment/mapclub'
], function (wrapper, mapclubAccount) {
    'use strict';

    return function (quote) {
        quote.setTotals = wrapper.wrapSuper(quote.setTotals, function (data) {
            this._super(data);
            mapclubAccount.usedPoints(data['extension_attributes']['mapclub_points']);
        });

        return quote;
    };
});
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 *
 */
define('Magento_Reward/js/action/remove-points-from-summary',[
    'underscore',
    'mage/storage',
    'Magento_Checkout/js/model/error-processor',
    'Magento_Ui/js/model/messageList',
    'mage/translate',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Checkout/js/action/get-payment-information',
    'Magento_Checkout/js/model/totals'
], function (
    _,
    storage,
    errorProcessor,
    messageList,
    $t,
    fullScreenLoader,
    getPaymentInformationAction,
    totals
) {
    'use strict';

    return function (url) {
        var responseMessage;

        messageList.clear();
        fullScreenLoader.startLoader();
        storage.post(
            url, {}
        ).done(function (response) {
            totals.isLoading(true);
            getPaymentInformationAction().done(function () {
                totals.isLoading(false);
            });

            if (_.isObject(response) && !_.isUndefined(response.message)) {
                responseMessage = {
                    'message': $t(response.message)
                };

                if (response.errors) {
                    messageList.addErrorMessage(responseMessage);
                } else {
                    messageList.addSuccessMessage(responseMessage);
                }
            }
        }).fail(function (response) {
            totals.isLoading(false);
            errorProcessor.process(response);
        }).always(function () {
            fullScreenLoader.stopLoader();
        });
    };
});

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

define('Magento_Reward/js/view/summary/reward',[
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/totals',
    'Magento_Reward/js/action/remove-points-from-summary'
], function (Component, totals, removeRewardPointsAction) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Magento_Reward/summary/reward'
        },
        totals: totals.totals(),

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

            if (this.totals) {
                segment = totals.getSegment('reward');

                if (segment) {
                    price = segment.value;
                }
            }

            return price;
        },

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

        /**
         * Get reward points.
         */
        getRewardPoints: function () {
            return totals.totals()['extension_attributes']['reward_points_balance'];
        },

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

        /**
         * @return {String}
         */
        getRewardPointsRemoveUrl: function () {
            return window.checkoutConfig.review.reward.removeUrl + '?_referer=' +  window.location.hash.substr(1);
        },

        /**
         * Remove Reward Points
         */
        removeRewardPoints: function () {
            return removeRewardPointsAction(this.getRewardPointsRemoveUrl());
        }
    });
});

define('Magento_Checkout/js/view/summary/abstract-total-mixin',[], function () {
    "use strict";

    return function (target) {
        return target.extend({
            /**
             * @return {*}
             */
            isFullMode: function () {
                if (!this.getTotals()) {
                    return false;
                }
                // show totals block on checkout shipping step
                return true;
            }
        });
    }
});
define('Amasty_Conditions/js/model/shipping-rates-validation-rules-mixin',[
    'jquery',
    'mage/utils/wrapper',
    'uiRegistry'
], function ($, wrapper) {
    "use strict";

    return function (shippingRatesValidationRules) {
        shippingRatesValidationRules.getObservableFields = wrapper.wrap(shippingRatesValidationRules.getObservableFields,
            function (originalAction) {
                var fields = originalAction();
                fields.push('street');
                fields.push('city');
                fields.push('region_id');

                return fields;
            }
        );

        return shippingRatesValidationRules;
    };
});

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

define('Magento_GiftCardAccount/js/model/payment/gift-card-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_GiftCardAccount/js/action/remove-gift-card-from-quote',[
        'jquery',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/action/get-payment-information',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/model/error-processor',
        'Magento_GiftCardAccount/js/model/payment/gift-card-messages',
        'mage/translate'
    ],
    function (
        $,
        urlBuilder,
        storage,
        customer,
        quote,
        getPaymentInformationAction,
        fullScreenLoader,
        errorProcessor,
        messageList
    ) {
        'use strict';

        return function (giftCardCode) {
            var serviceUrl,
                message = $.mage.__('Gift Card %1 was removed.').replace('%1', giftCardCode);

            if (!customer.isLoggedIn()) {
                serviceUrl = urlBuilder.createUrl('/carts/guest-carts/:cartId/giftCards/:giftCardCode', {
                    cartId: quote.getQuoteId(),
                    giftCardCode: giftCardCode
                });
            } else {
                serviceUrl = urlBuilder.createUrl('/carts/mine/giftCards/:giftCardCode', {
                    giftCardCode: giftCardCode
                });
            }

            messageList.clear();
            fullScreenLoader.startLoader();

            return storage.delete(
                serviceUrl
            ).done(
                function (response) {
                    if (response) {
                        $.when(getPaymentInformationAction()).always(function () {
                            fullScreenLoader.stopLoader();
                        });
                        messageList.addSuccessMessage({
                            'message': message
                        });
                    }
                }
            ).fail(
                function (response) {
                    errorProcessor.process(response, messageList);
                    fullScreenLoader.stopLoader();
                }
            );
        };
    }
);

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

define('Magento_GiftCardAccount/js/view/summary/gift-card-account',[
    'jquery',
    'ko',
    'Magento_Checkout/js/view/summary/abstract-total',
    'mage/url',
    'Magento_Checkout/js/model/totals',
    'Magento_GiftCardAccount/js/action/remove-gift-card-from-quote'
], function ($, ko, generic, url, totals, removeAction) {
    'use strict';

    return generic.extend({
        defaults: {
            template: 'Magento_GiftCardAccount/summary/gift-card-account'
        },

        /**
         * Get information about applied gift cards and their amounts
         *
         * @returns {Array}.
         */
        getAppliedGiftCards: function () {
            if (totals.getSegment('giftcardaccount')) {
                return JSON.parse(totals.getSegment('giftcardaccount')['extension_attributes']['gift_cards']);
            }

            return [];
        },

        /**
         * @return {Object|Boolean}
         */
        isAvailable: function () {
            return this.isFullMode() && totals.getSegment('giftcardaccount') &&
                totals.getSegment('giftcardaccount').value != 0; //eslint-disable-line eqeqeq
        },

        /**
         * @param {Number} usedBalance
         * @return {*|String}
         */
        getAmount: function (usedBalance) {
            return this.getFormattedPrice(usedBalance);
        },

        /**
         * @param {String} giftCardCode
         * @param {Object} event
         */
        removeGiftCard: function (giftCardCode, event) {
            event.preventDefault();

            if (giftCardCode) {
                removeAction(giftCardCode);
            }
        }
    });
});

/**
 * Kemana_Checkout
 *
 * @see README.md
 *
 */

/*global define*/
define(
    'Kemana_Checkout/js/model/shipping-rates-validator',[
        'jquery',
        'Magento_Checkout/js/model/shipping-rates-validation-rules',
        'mage/translate',
        'uiRegistry',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/action/select-shipping-address',
        'mageUtils'
    ],
    function ($, shippingRatesValidationRules, $t, uiRegistry, addressConverter, selectShippingAddress, utils) {
        'use strict';
        var postcodeElementName = 'postcode';
        var postcodeElement = null;
        var districtIdElement = null;
        var districtIdElementName = 'district_id';
        var cityIdElement = null;
        var cityIdElementName = 'city_id';

        return function(shippingRatesValidator){

            shippingRatesValidator.validateDelay = 1000;

            shippingRatesValidator.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);
                }

                if ($.inArray(districtIdElementName, elements) === -1) {
                    // district id
                    elements.push(districtIdElementName);
                }

                if ($.inArray(cityIdElementName, elements) === -1) {
                    // city id
                    elements.push(cityIdElementName);
                }

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


            shippingRatesValidator.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);
                    postcodeElement = element;
                }

                if (element.index === districtIdElementName) {
                    this.bindHandler(element, delay);
                    districtIdElement = element;
                }

                if (element.index === cityIdElementName) {
                    this.bindHandler(element, delay);
                    cityIdElement = element;
                }
            };

            shippingRatesValidator.validateFields = function () {
                var addressFrm = addressConverter.formDataProviderToFlatData(
                        this.collectObservedData(),
                        'shippingAddress'
                    ),
                    address,
                    addressFlat;

                if (utils.isEmpty(addressFrm.custom_attributes.city_id)) {
                    $('select[name="custom_attributes[city_id]"]').blur(function () {
                        if (this.value === "") {
                            if ($('body').hasClass("checkout-index-index") && $('body').hasClass("store-view-th_th")) {
                                cityIdElement.error($t('required') + $t(cityIdElement.label));
                            }else{
                                cityIdElement.error($t(cityIdElement.label) + $t(' is required.'));
                            }
                        }
                    });
                    return;
                } else {
                    cityIdElement.error(null);
                }

                if (utils.isEmpty(addressFrm.custom_attributes.district_id)) {
                    $('select[name="custom_attributes[district_id]"]').blur(function () {
                        if (this.value === "") {
                            districtIdElement.error($t(districtIdElement.label + ' is required.'));
                        }
                    });
                    return;
                } else {
                    districtIdElement.error(null);
                }
                $('input[name="telephone"]').focusin(function () {
                    $(this).parent().find('.field-error').css("display", "none");
                });
                $('input[name="postcode"]').focusin(function () {
                    $(this).parent().find('.field-error').css("display", "none");
                });
                $('input[name="telephone"]').focusout(function () {
                    $(this).parent().find('.field-error').css("display", "block");
                });
                $('input[name="postcode"]').focusout(function () {
                    $(this).parent().find('.field-error').css("display", "block");
                });

                if (this.validateAddressData(addressFrm)) {
                    addressFlat = uiRegistry.get('checkoutProvider').shippingAddress;
                    addressFlat.city = addressFrm.custom_attributes.city_id + '/' + addressFrm.custom_attributes.district_id;
                    address = addressConverter.formAddressDataToQuoteAddress(addressFlat);
                    selectShippingAddress(address);
                }
            };

            return shippingRatesValidator;
        }
    }
);


define('text!Magento_Tax/template/checkout/summary/subtotal.html',[],function () { return '<!--\n/**\n * Copyright © 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('Amasty_Promo/js/model/promo-subscribe',[
    'ko',
    'jquery',
    'uiComponent',
    'Amasty_Conditions/js/model/subscriber',
    'Amasty_Promo/js/popup'
], function (ko, $, Component, subscriber) {
    'use strict';

    return Component.extend({

        initialize: function () {
            this._super();

            subscriber.isLoading.subscribe(function (isLoading) {
                if (!isLoading) {
                    $('[data-role=ampromo-overlay]').ampromoPopup('reload');
                }
            });

            return this;
        }
    });
});


define('text!Born_Eds/template/summary/eds-discount.html',[],function () { return '<!-- ko if: isDisplayed() -->\n<tr class="totals eds_discount excl">\n    <th class="mark" colspan="1" scope="row" data-bind="text: getLabel()"></th>\n    <td class="amount">\n        <span class="price" data-bind="text: getValue(), attr: {\'data-th\': getLabel()}"></span>\n    </td>\n</tr>\n<!-- /ko -->\n';});

/**
 * @package   Born_Eds
 * @author    Manish Bhojwani (Manish.Bhojwani@BornGroup.com)
 * @copyright 2022 Copyright Born Group, Inc. http://www.borngroup.com/
 * @license   http://www.borngroup.com/ Private
 * @link      http://www.borngroup.com/
 */

define('Born_Eds/js/view/summary/eds-discount',[
    '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: {
            template: 'Born_Eds/summary/eds-discount'
        },

        totals: quote.getTotals(),
        /**
         * @override
         *
         * @returns {Boolean}
         */
        isDisplayed : function() {
            return window.checkoutConfig.eds.active && Math.abs(totals.getSegment('eds_discount').value) > 0;
        },
        getLabel : function() {
            var title = window.checkoutConfig.eds.title;
            if (this.totals()) {
                title = totals.getSegment('eds_discount').title !== '' ?
                    totals.getSegment('eds_discount').title : title;
            }
            return title;
        },
        getValue : function() {
            var price = 0;
            if (this.totals()) {
                price = totals.getSegment('eds_discount').value;
            }
            return this.getFormattedPrice(price);
        }
    });
});

/**
 * 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('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);
        }
    });
});

/**
 * 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_CurrencyFormatter
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
define('Mageplaza_CurrencyFormatter/js/view/summary/abstract-total',[
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils'
], function ($, quote, priceUtils) {
    'use strict';

    var content   = '%s',
        newFormat = {
            decimalSymbol: '',
            groupLength: '',
            groupSymbol: '',
            integerRequired: '',
            pattern: '',
            precision: '',
            requiredPrecision: ''
        };

    var mixins = {
        getFormattedPrice: function (price) {
            var format     = quote.getPriceFormat(),
                newPattern = null,
                newPrice   = null;

            if (price >= 0) {
                return this._super(price);
            }

            if (format.showMinus && format.minusSign && format.symbol) {
                newPrice = price * -1;
                switch (format.showMinus){
                    case 'before_value':
                        newPattern = format.pattern.replace(content, format.minusSign + content);
                        break;
                    case 'after_value':
                        newPattern = format.pattern.replace(content, content + format.minusSign);
                        break;
                    case 'before_symbol':
                        newPattern = format.pattern.replace(format.symbol, format.minusSign + format.symbol);
                        break;
                    case 'after_symbol':
                        newPattern = format.pattern.replace(format.symbol, format.symbol + format.minusSign);
                        break;
                    default:
                        newPattern = format.pattern;
                        break;
                }

                if (format.pattern.indexOf(format.symbol) === -1) {
                    newPattern = format.minusSign + format.pattern;
                }

                $.each(newFormat, function (key) {
                    if (key === 'pattern') {
                        newFormat['pattern'] = newPattern;
                    } else {
                        newFormat[key] = format[key];
                    }
                });

                return priceUtils.formatPrice(newPrice, newFormat);
            }

            return this._super(price);
        }
    };

    return function (AbstractTotal) {
        return AbstractTotal.extend(mixins);
    };
});



define("bundles/product-cart-checkout", function(){});

//# sourceMappingURL=product-cart-checkout.js.map