cdn-7.com Open in urlscan Pro
2606:4700::6812:f87  Public Scan

URL: https://cdn-7.com/media/js/8eb67eef77f676005e848cd03907299c.js?v=109348821
Submission Tags: falconsandbox
Submission: On February 24 via api from US — Scanned from DE

Form analysis 0 forms found in the DOM

Text Content

(function () {
    var msg = 'Hello inspector, we are hiring! https://team.emma-sleep.com/team/technology-and-software-engineering';
    var chromeFirefox=new RegExp('chrome|firefox','i');if(chromeFirefox.test(navigator.userAgent)){console.log('%c ' + msg,'color: #1e2b5a; font-weight: bold');}else{console.log(msg);}
})();

/**
 * OpenMage
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * @category    Varien
 * @package     js
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/**************************** WEEE STUFF ********************************/
function taxToggle(details, switcher, expandedClassName)
{
    if ($(details).style.display == 'none') {
        $(details).show();
        $(switcher).addClassName(expandedClassName);
    } else {
        $(details).hide();
        $(switcher).removeClassName(expandedClassName);
    }
}

/**
 * Namespaces
 * @type {Object}
 */
var PAYONE = {};
PAYONE.Handler = {};
PAYONE.Service = {};
PAYONE.Validation = {};

/**
 * A Gatewaay to send Requests to Payone
 *
 * @param data
 * @constructor
 */
PAYONE.Gateway = function (config, callback) {
    this.config = config;
    this.callback = callback;
    this.request = '';
    this.response = '';

    this.call = function (data) {

        this.initRequest(data);

        // Options
        var options = {
            callback_function_name:'PAYONE.Callback.invoke'
        };

        // AJAX Callback
        PAYONE.Callback.gateway = this;
        PAYONE.Callback.callback = this.callback;

        // Send Request to PAYONE
        var request = new PayoneRequest(this.request, options);
        request.checkAndStore();
    };

    this.initRequest = function (data) {
        this.request = data;

        // Add Default Parameters
        for (var key in this.config) {
            this.request[key] = this.config[key];
        }

        // init Request
        this.request.callback_method = 'PAYONE.Callback.invoke';
    }

    this.setResponse = function (response) {
        this.response = response;
    };

    this.getLastResponse = function () {
        return this.response;
    };

    this.getLastRequest = function () {
        return this.request;
    };

    this.setCallback = function (callback) {
        this.callback = callback;
    };
};

/**
 * A Callback Object that replaces default PAYONE Callback and improves Callback Handling
 *
 * @type {Object}
 */
PAYONE.Callback = {
    /**
     * @type {Object} reference to the Gateway Object
     */
    gateway:'',
    /**
     * @type callback should be a valid Callback
     */
    callback:'',

    /**
     * Callback entry method
     *
     * @param response
     */
    invoke:function (response) {
        this.gateway.setResponse(response);

        document.getElementsByTagName("body")[0].removeChild(payoneCallbackFunction.payoneScript);

        var callback = this.callback;
        callback(response);
    }
};

/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com
 * @author          Matthias Walter <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

/**
 * PAYONE Service CreditCardCheck
 *
 * @param config
 * @constructor
 */
PAYONE.Service.CreditCardCheck = function (handler, form, config) {
    this.handler = handler;
    this.form = form;
    this.config = config;
    this.origMethod = '';
    this.iframes = false;

    /**
     * Enhances payment.save and runs Validate and CreditCardCheck for CreditCards
     * @todo rename this method?
     * @param origMethod
     */
    this.exec = function (origMethod) {
        var check = this.handler.haveToValidate();

        if (check == 1) {
            this.handler.origMethod = origMethod;
            // Payone credit card payment method is available, and selected, initiate credit card check:
            if (this.validate(this.form)) {
                if(this.iframes == false) {
                    this.creditcardcheck();
                } else {
                    this.creditcardcheckHosted();
                }
            }
        }
        else {
            origMethod();
        }
    };
    
    this.initHosted = function (fieldconfig, type_id) {
        var configId = false;
        var elementCcType = $('payone_creditcard_cc_type_select');
        var iFrameCvc = $("payone_creditcard_cc_cid_div");
        if (elementCcType != undefined) {

            var ccTypeConfigKey = elementCcType.value;
            var ccTypeSplit = ccTypeConfigKey.split('_');
            configId = ccTypeSplit[0];
            var ccType = ccTypeSplit[1];
            $("payone_creditcard_cc_type").setValue(ccType);

            if(elementCcType.length > 1 && $('payone_cc_check_validation_types') && $('payone_cc_check_validation_types').value.indexOf(ccType) != -1){
                if(iFrameCvc) iFrameCvc.hide();
             }
        }

        aConfig = this.getConfig();
        request = aConfig.gateway[configId];

        var iframes = new Payone.ClientApi.HostedIFrames(fieldconfig, request);
        iframes.setCardType(ccType);

        document.getElementById(type_id).onchange = function () {
            var elementCcType = $('payone_creditcard_cc_type_select');

            if (elementCcType != undefined) {

                var ccTypeConfigKey = elementCcType.value;
                var ccTypeSplit = ccTypeConfigKey.split('_');
                var ccType = ccTypeSplit[1];
                var selectedValueIFrame = ccTypeConfigKey.substring(ccTypeConfigKey.indexOf("_") + 1);
                if($('payone_cc_check_validation_types') && $('payone_cc_check_validation_types').value.indexOf(selectedValueIFrame) != -1){
                    if(iFrameCvc) iFrameCvc.hide();
                } else {
                    if(iFrameCvc) iFrameCvc.show();
                }
                iframes.setCardType(ccType); // on change: set new type of credit card to process
            }
        };
        this.iframes = iframes;
        return iframes;
    }

    /**
     * Trigger CVC Code as configured
     *
     * @param element
     */
    this.displayCheckCvc = function (element) {
        config = $('payone_creditcard_config_cvc').value.evalJSON();
        ccKey = element.value;

        var selectedValue = element.value.substring(element.value.indexOf("_") + 1);

        var cvcDiv = $("payone_creditcard_cc_cid_div");
        if (cvcDiv != undefined && cvcDiv != null) {
            configCcKey = config[ccKey];
            //check if selected creditcard is in hideCvcTypes
            if($('payone_cc_check_validation_types') && $('payone_cc_check_validation_types').value.indexOf(selectedValue) != -1){
                cvcDiv.hide();
                $('payone_cc_check_validation').value = 1;
            } else {
                cvcDiv.show();

            }
        }
    };

    /**
     * Validate the Form Data
     *
     * @param form Form Object
     * @return {*}
     */
    this.validate = function (form) {
        var elementCcType = $('payone_creditcard_cc_type_select');
        if (elementCcType != undefined) {
            var ccTypeConfigKey = elementCcType.value;
            var ccTypeSplit = ccTypeConfigKey.split('_');
            var configId = ccTypeSplit[0];

            var ccType = ccTypeSplit[1];
            $("payone_creditcard_config_id").setValue(configId);
            $("payone_creditcard_cc_type").setValue(ccType);
        }

        config = this.getConfig();
        configValidation = config.validation;

        validation = new PAYONE.Validation.CreditCard(configValidation);
        return validation.validate(form);
    };

    /**
     * Perform creditcard check via Payone Client API
     */
    this.creditcardcheck = function () {
        var configId = $("payone_creditcard_config_id").value;

        config = this.getConfig();
        configGateway = config.gateway[configId];

        var data = this.mapRequestCreditCardCheck();

        var payoneGateway = new PAYONE.Gateway(
            configGateway,
            function (response) {
                return window.payone.handleResponseCreditcardCheck(response, false);
            }
        );
        payoneGateway.call(data);
    };
    
    this.creditcardcheckHosted = function () {
        if (this.iframes.isComplete()) {
            $('payone_creditcard_hosted_error').hide();
            $('payone_creditcard_cc_owner').value = $('name_on_card').value;
            this.iframes.creditCardCheck('processPayoneResponseCCHosted');
        } else {
            $('payone_creditcard_hosted_error').show();
        }
    }

    /**
     * Collect PAYONE CreditCardCheck Request Parameters
     *
     * @return {*}
     */
    this.mapRequestCreditCardCheck = function () {
        data = {
            'cardexpiremonth':$('payone_creditcard_cc_expiration_month').value,
            'cardexpireyear':$('payone_creditcard_cc_expiration_year').value,
            'cardtype':$('payone_creditcard_cc_type').value
        };
        if($('payone_pseudocardpan').value == '') {
            data.cardholder = $('payone_creditcard_cc_owner').value;
            data.cardpan = $('payone_creditcard_cc_number').value;
        } else {
            data.pseudocardpan = $('payone_pseudocardpan').value;
        }

        cid = $('payone_creditcard_cc_cid');
        if (cid != undefined) {
            data.cardcvc2 = cid.value;
        }

        return data;
    };

    /**
     * Handle response
     *
     * @param response
     * @return {Boolean}
     */
    this.handleResponseCreditcardCheck = function (response, blIsHostedIframe) {
        return this.handler.handleResponse(response, blIsHostedIframe);
    };

    /**
     * Get Config (auto-initialize)
     *
     * @return {*}
     */
    this.getConfig = function () {
        if (this.config == '' || this.config == undefined) {
            configJson = $('payone_creditcard_config').value;
            this.config = configJson.evalJSON();
        }

        return this.config;
    };
};

PAYONE.Handler.CreditCardCheck = {};
PAYONE.Handler.CreditCardCheck.OnepageCheckout = function () {
    this.origMethod = '';

    this.haveToValidate = function () {
        var radio_p1_cc = $('p_method_payone_creditcard');
        if (radio_p1_cc != undefined && radio_p1_cc != null && radio_p1_cc.checked) {
            if($('payone_cc_check_validation').value == 0) {
                return 0;
            }

            if (checkout.loadWaiting != false) {
                return 0;
            }

            if (payment.validate() != true) {
                return 0;
            }

            return 1;
        }

        return 0;
    };

    this.handleResponse = function (response, blIsHostedIframe) {
        if (response.status != 'VALID') {
            // Failure
            if(typeof response.customermessage != 'undefined') {
                alert(response.customermessage);
            } else if(typeof response.errormessage != 'undefined') {
                alert(response.errormessage);
            }

            checkout.setLoadWaiting(false);
            return false;
        }

        // Success!
        var pseudocardpan = response.pseudocardpan;
        var truncatedcardpan = response.truncatedcardpan;
        
        if(blIsHostedIframe) {
            var cardexpiredate = response.cardexpiredate;
            $('payone_cardexpiredate').setValue(cardexpiredate);
        }

        $('payone_pseudocardpan').setValue(pseudocardpan);
        $('payone_truncatedcardpan').setValue(truncatedcardpan);
        $('payone_creditcard_cc_number').setValue(truncatedcardpan);

        cid = $('payone_creditcard_cc_cid');
        if (cid != undefined) {
            $('payone_creditcard_cc_cid').setValue('')
        }

        checkout.setLoadWaiting('payment', false);

        // Post payment form to Magento:
        var request = new Ajax.Request(
            payment.saveUrl,
            {
                method:'post',
                onComplete:payment.onComplete,
                onSuccess:payment.onSave,
                onFailure:checkout.ajaxFailure.bind(checkout),
                parameters:Form.serialize(payment.form)
            }
        );
    };
};

PAYONE.Handler.CreditCardCheck.Admin = function () {
    this.origMethod = '';

    this.haveToValidate = function () {
        var radio_p1_cc = $('p_method_payone_creditcard');

        if (radio_p1_cc != undefined && radio_p1_cc != null && radio_p1_cc.checked
            && $('payone_pseudocardpan').value == '') {
            if($('payone_cc_check_validation').value == 0) {
                return 0;
            }

            return 1;
        }

        return 0;
    };

    this.handleResponse = function (response, blIsHostedIframe) {
        if (response.status != 'VALID') {
            // Failure
            // Failure
            if(typeof response.customermessage != 'undefined') {
                alert(response.customermessage);
            } else if(typeof response.errormessage != 'undefined') {
                alert(response.errormessage);
            }

            return false;
        }

        // Success!
        var pseudocardpan = response.pseudocardpan;
        var truncatedcardpan = response.truncatedcardpan;

        if(blIsHostedIframe) {
            var cardexpiredate = response.cardexpiredate;
            $('payone_cardexpiredate').setValue(cardexpiredate);
        }

        $('payone_pseudocardpan').setValue(pseudocardpan);
        $('payone_truncatedcardpan').setValue(truncatedcardpan);
        $('payone_creditcard_cc_number').setValue(truncatedcardpan);

        cid = $('payone_creditcard_cc_cid');
        if (cid != undefined) {
            $('payone_creditcard_cc_cid').setValue('')
        }

        // remove validation class cause CreditCard is validated
        // @todo when changing CardData it has to be added again or we exchange the form with labels and provide an edit button
        $('payone_creditcard_cc_number').removeClassName('validate-cc-number');
        $('payone_creditcard_cc_number').removeClassName('validate-payone-cc-type');
        this.origMethod();
    };
};

PAYONE.Validation.CreditCard = function (config) {
    this.config = config;
    this.validationsCc = '';
    this.validationsCcMagento = '';

    this.validate = function (form) {
        this.initValidationType();
        
        if($('payone_pseudocardpan').value == '') {
            //Validation.add('validate-payone-cc-type', 'Credit card number does not match credit card type.', this.validateType, this);
            Validation.add('validate-payone-cc-validity-period', 'Credit card validity period is too short.', this.validateValidityPeriod, this);
        }

        var validator = new Validation(form);
        return validator.validate();
    };

    /**
     * Creditcard Validity Period Validation
     *
     * @param v
     * @param elm
     * @return {Boolean}
     */
    this.validateValidityPeriod = function (v, elm) {
        var year = $('payone_creditcard_cc_expiration_year').value;
        var validityCc = new Date(year, v, 1); // Start of next month

        return validityCc.getTime() > this.options.get('config').allowed_validity * 1000; // milliseconds vs. seconds
    };

    /**
     * Creditcard Type Validation
     *
     * @param v
     * @param elm
     * @return {Boolean}
     */
    this.validateType = function (v, elm) {
        // remove credit card number delimiters such as "-" and space
        elm.value = removeDelimiters(elm.value);
        v = removeDelimiters(v);

        var ccTypeContainer = $(elm.id.substr(0, elm.id.indexOf('_cc_number')) + '_cc_type');
        if (!ccTypeContainer) {
            return true;
        }

        var ccType = ccTypeContainer.value;
        var ccTypeValidator = this.options.get('validationsCc').get(ccType);

        if (typeof ccTypeValidator == 'undefined') {
            return false;
        }

        // Disabled checks:
        if (ccTypeValidator[0] == false) {
            return true;
        }

        // Validate credit card number according to type:
        var result = false;
        if (ccTypeValidator[0] && v.match(ccTypeValidator[0])) {
            result = true;
        }

        if (!result) {
            return false;
        }

        if (ccTypeContainer.hasClassName('validation-failed') && Validation.isOnChange) {
            Validation.validate(ccTypeContainer);
        }

        return true;
    };

    this.initValidationType = function () {
        if (Validation.creditCardTypes) {
            this.validationsCcMagento = Validation.creditCardTypes;
        }
        else if (Validation.creditCartTypes) {
            // typo in certain Magento versions..
            this.validationsCcMagento = Validation.creditCartTypes;
        }

        // validations for Payone credit card types
        this.validationsCc = $H(
            {
            'O':[new RegExp('(^(5[0678])\\d{11,18}$)|(^(6[^0357])\\d{11,18}$)|(^(601)[^1]\\d{9,16}$)|(^(6011)\\d{9,11}$)|(^(6011)\\d{13,16}$)|(^(65)\\d{11,13}$)|(^(65)\\d{15,18}$)|(^(633)[^34](\\d{9,16}$))|(^(6333)[0-4](\\d{8,10}$))|(^(6333)[0-4](\\d{12}$))|(^(6333)[0-4](\\d{15}$))|(^(6333)[5-9](\\d{8,10}$))|(^(6333)[5-9](\\d{12}$))|(^(6333)[5-9](\\d{15}$))|(^(6334)[0-4](\\d{8,10}$))|(^(6334)[0-4](\\d{12}$))|(^(6334)[0-4](\\d{15}$))|(^(67)[^(59)](\\d{9,16}$))|(^(6759)](\\d{9,11}$))|(^(6759)](\\d{13}$))|(^(6759)](\\d{16}$))|(^(67)[^(67)](\\d{9,16}$))|(^(6767)](\\d{9,11}$))|(^(6767)](\\d{13}$))|(^(6767)](\\d{16}$))'),
                new RegExp('^[0-9]{3}$'),
                false],
            'V':this.validationsCcMagento.get('VI'),
            'A':this.validationsCcMagento.get('AE'),
            'M':this.validationsCcMagento.get('MC'),
            'J':this.validationsCcMagento.get('JCB'),
            'C':this.validationsCcMagento.get('DI'),
            'D':this.validationsCcMagento.get('OT'),
            'B':this.validationsCcMagento.get('OT'),
            'U':this.validationsCcMagento.get('OT')
            }
        );
    };

    this.getConfig = function () {
        return this.config;
    };
};

function payoneChangedCreditCardInfo() 
{
    $('payone_pseudocardpan').value = '';
    $('payone_cc_check_validation').value = 1;
    $('payone_creditcard_cc_number').addClassName('validate-cc-number');
}

function processPayoneResponseCCHosted(response) 
{
    payone.handleResponseCreditcardCheck(response, true);
}
/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com, Copyright (c) 2017 <info@e3n.de> - www.e3n.de
 * @author          Matthias Walter <info@noovias.com>, Tim Rein <web.it.rein@gmail.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com, http://www.e3n.de
 */

/**
 *
 * @param typeCode
 * @param methodCode
 * @param element
 * @param country
 * @param currency
 */
function payoneSwitchOnlineBankTransfer(typeCode, methodCode, element, country, currency) {

    var accountNumberWrap = $('account_number_wrap');
    var bankCodeWrap = $('bank_code_wrap');
    var sepaIbanWrap = $('sepa_iban_wrap');
    var sepaBicWrap = $('sepa_bic_wrap');
    var bankGroupWrapAt = $('bank_group_wrap_at');
    var bankGroupWrapNl = $('bank_group_wrap_nl');
    var accountNumberInput = $(methodCode + '_account_number');
    var bankCodeInput = $(methodCode + '_bank_code');
    var sepaIbanInput = $(methodCode + '_sepa_iban');
    var sepaBicInput = $(methodCode + '_sepa_bic');
    var bankGroupSelectAt = $(methodCode + '_bank_group_at');
    var bankGroupSelectNl = $(methodCode + '_bank_group_nl');
    var sofortueberweisungShowIban = $(methodCode + '_pnt_show_iban');
    //
    var epsPaymentMethodContainer =  $("dt_method_payone_online_bank_transfer_eps") || $('p_method_payone_online_bank_transfer_eps');
    var idlPaymentMethodContainer =  $("dt_method_payone_online_bank_transfer_idl") || $('p_method_payone_online_bank_transfer_idl');
    var giropayPaymentMethodContainer =  $("dt_method_payone_online_bank_transfer_giropay") || $('p_method_payone_online_bank_transfer_giropay');
    var pffPaymentMethodContainer =  $("dt_method_payone_online_bank_transfer_pff") || $('p_method_payone_online_bank_transfer_pff');
    var sofortPaymentMethodContainer =  $("dt_method_payone_online_bank_transfer_sofortueberweisung") || $('p_method_payone_online_bank_transfer_sofortueberweisung');



    function enableBankGroupNl() {
        if (bankGroupWrapNl) {
            bankGroupWrapNl.show();
            bankGroupSelectNl.removeAttribute("disabled");
        }
    }

    function enableBankGroupAt() {
        if (bankGroupWrapAt) {
            bankGroupWrapAt.show();
            bankGroupSelectAt.removeAttribute("disabled");
        }
    }

    function enableAccountNumber() {
        if (accountNumberWrap) {
            accountNumberWrap.show();
            accountNumberInput.removeAttribute("disabled");
        }
    }

    function enableBankCode() {
        if (bankCodeWrap) {
            bankCodeWrap.show();
            bankCodeInput.removeAttribute("disabled");
        }
    }

    function enableSepaIban() {

        if (sepaIbanWrap) {
            sepaIbanWrap.show();
            sepaIbanInput.removeAttribute("disabled");
        }
    }

    function enableSepaBic() {

        if (sepaBicWrap) {
            sepaBicWrap.show();
            sepaBicInput.removeAttribute("disabled");
        }
    }

    if (typeCode == 'EPS') {
        if(epsPaymentMethodContainer) {
            epsPaymentMethodContainer.on("click", function (event) {
                disableAll();
                enableBankGroupAt();
            });
        }
    }
    if (typeCode == 'IDL') {
        if (idlPaymentMethodContainer) {
            idlPaymentMethodContainer.on("click", function (event) {
                disableAll();
                enableBankGroupNl();
            });
        }
    }
    if (typeCode == 'GPY') {
        if (giropayPaymentMethodContainer) {
            giropayPaymentMethodContainer.on("click", function (event) {
                disableAll();
                enableSepaIban();
                enableSepaBic();
            });
        }
    }


    if (typeCode == 'PFF') {
        if(pffPaymentMethodContainer){
            pffPaymentMethodContainer.on("click", function (event) {
                disableAll();
            });
        }
    }

    if (typeCode == 'PNT') {
        if(sofortPaymentMethodContainer){
            sofortPaymentMethodContainer.on("click", function (event) {
                disableAll();
                if (sofortueberweisungShowIban.value == 1) {
                    enableSepaIban();
                    enableSepaBic();
                }

                if (country == 'CH' && currency == 'CHF') {
                    enableAccountNumber();
                    enableBankCode();
                }
            });
        }
    }

    if (typeCode === 'PFC' || typeCode === 'P24' || typeCode === 'BCT') {
        disableAll();
    }

    function disableAll() {
        if (accountNumberWrap && accountNumberInput) {
            accountNumberWrap.hide();
            accountNumberInput.setAttribute("disabled", "disabled");
        }

        if (bankCodeWrap && bankCodeInput) {
            bankCodeWrap.hide();
            bankCodeInput.setAttribute("disabled", "disabled");
        }

        if (sepaIbanWrap && sepaIbanInput) {
            sepaIbanWrap.hide();
            sepaIbanInput.setAttribute("disabled", "disabled");
        }

        if (sepaBicWrap && sepaBicInput) {
            sepaBicWrap.hide();
            sepaBicInput.setAttribute("disabled", "disabled");
        }

        if (bankGroupWrapNl && bankGroupSelectNl) {
            bankGroupWrapNl.hide();
            bankGroupSelectNl.setAttribute("disabled", "disabled");
        }
    }

}

function copyOnlineBankTransferSepaIban(code) {
    var input_sepa_iban_xxx_el = $(code + '_sepa_iban_xxx');
    var input_sepa_iban_el = $(code + '_sepa_iban');
    input_sepa_iban_el.value = input_sepa_iban_xxx_el.value;
}

/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com
 * @author          Matthias Walter <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

/**
 * @param element
 */
function payoneSwitchSafeInvoice(element)
{
    if (element == undefined) {
        return;
    }

    var ElementValue = element.value;
    var ElementValueSplit = ElementValue.split('_');
    var typeId = ElementValueSplit[0];
    var typeCode = ElementValueSplit[1];
    $("payone_safe_invoice_sin_type").setValue(typeCode);
    $("payone_safe_invoice_config_id").setValue(typeId);

    var divOne = $('payone_klarna_invoice_terms_div');
    var divTwo = $('payone_klarna_additional_fields');

    if (divOne == undefined || divTwo == undefined) {
        return;
    }

    if (typeCode == 'KLV'){
        divOne.show();
        divTwo.show();
    } else {
        divOne.hide();
        divTwo.hide();
    }
}

Event.observe(
    document, "dom:loaded", function () {
    payoneSwitchSafeInvoice($('payone_safe_invoice_sin_type_select'));
    }
);

Event.observe(
    document, "dom:ready", function () {
    payoneSwitchSafeInvoice($('payone_safe_invoice_sin_type_select'));
    }
);

Ajax.Responders.register(
    {
    onComplete: function (transport, element) {
        var typeSelect = $('payone_safe_invoice_sin_type_select');
        if (typeSelect == undefined) {
            return;
        }

        var url = element.request.url;
        if (url.indexOf('checkout/onepage/saveShippingMethod') !== -1 || url.indexOf('checkout/onepage/progress') !== 1) {
            payoneSwitchSafeInvoice(typeSelect);
        }
    }
    }
);

/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com
 * @author          Matthias Walter <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

function showBankData(code, configShowBankData) 
{
    var bankCountry = $(code + '_bank_country').getValue();
    if (configShowBankData && configShowBankData == 1) {
        if (bankCountry == "DE") {
            $('input_box_payone_account_number').show();
            $('input_box_payone_bank_code').show();
        } else {
            $('input_box_payone_account_number').hide();
            $('input_box_payone_bank_code').hide();
        }
    }
}

/**
 *
 * @param code
 */
function checkIbanCountryCode(code) 
{
    var ibanEl = $(code + '_sepa_iban');
    if (!ibanEl || typeof ibanEl === 'undefined') {
        return;
    }

    var bankCountryEl = $(code + '_bank_country');
    if (!bankCountryEl || typeof bankCountryEl === 'undefined') {
        return;
    }

    var bankCountryCode = bankCountryEl.value;
    var value = ibanEl.value;
    if (value.length < 2) {
        return;
    }

    var countryCode = value.substring(0, 2).toUpperCase();
    var validationAdvice = $("advice-validate-sepa-iban-countrycode");
    if (countryCode != bankCountryCode) {
        ibanEl.value = "";
        ibanEl.addClassName("validation-failed");
        if (!validationAdvice || typeof validationAdvice === 'undefined') {
            var valText = Translator.translate("Entered IBAN is not valid for selected bank country");
            ibanEl.insert(
                {
                after: '<div class="validation-advice" id="advice-validate-sepa-iban-countrycode">' + valText + '</div>'
                }
            );
        }
    } else {
        ibanEl.removeClassName('validation-failed');
        if (validationAdvice && typeof validationAdvice !== 'undefined') {
            validationAdvice.remove();
        }
    }
}

function disableElement(element) 
{
    if (element == undefined) {
        return;
    }

    element.value = '';
    element.disabled = true;
    element.removeClassName('required-entry');
    element.removeClassName('validation-failed');
    var validationHint = element.next('div .validation-advice');
    if (typeof validationHint !== 'undefined') {
        validationHint.remove();
    }
}

function enableElement(element) 
{
    if (element == undefined) {
        return;
    }

    element.disabled = false;
    element.toggleClassName('require-entry');
}

function copyDebitPaymentSepaIban(code) 
{
    var input_sepa_iban_xxx_el = $(code + '_sepa_iban_xxx');
    var input_sepa_iban_el = $(code + '_sepa_iban');
    input_sepa_iban_el.value = input_sepa_iban_xxx_el.value;
}

function blockPaymentMethodInputs(code, configShowBankData) 
{
    var input_sepa_iban_el = $(code + '_sepa_iban');
    var input_sepa_bic_el = $(code + '_sepa_bic');
    var input_account_number_el = $(code + '_account_number');
    var input_bank_code_el = $(code + '_bank_code');

    if (input_sepa_iban_el.value != '' && Validation.get('validate-sepa-iban').test(input_sepa_iban_el.value) == true) {
        disableElement(input_account_number_el);
        var inputboxpayoneaccountnumber = $('input_box_payone_account_number');
        if (inputboxpayoneaccountnumber != undefined) {
            inputboxpayoneaccountnumber.hide();
        }

        disableElement(input_bank_code_el);
        var inputboxpayonebankcode = $('input_box_payone_bank_code');
        if (inputboxpayonebankcode != undefined) {
            inputboxpayonebankcode.hide();
        }
    } else {
        enableElement(input_account_number_el);
        enableElement(input_bank_code_el);
        showBankData(code, configShowBankData);
    }

    if (input_account_number_el != undefined
        && input_account_number_el.value != ''
        && Validation.get('validate-digits').test(input_account_number_el.value) == true
        && input_bank_code_el.value != ''
        && Validation.get('validate-bank-code').test(input_bank_code_el.value) == true
        && Validation.get('validate-digits').test(input_bank_code_el.value) == true) {
        disableElement(input_sepa_iban_el);
        $('input_box_payone_sepa_iban').hide();
        if(input_sepa_bic_el) {
            disableElement(input_sepa_bic_el);
            $('input_box_payone_sepa_bic').hide();
        }
    } else {
        enableElement(input_sepa_iban_el);
        $('input_box_payone_sepa_iban').show();
        if(input_sepa_bic_el) {
            enableElement(input_sepa_bic_el);
            $('input_box_payone_sepa_bic').show();
        }
    }
}

/**
 *
 * @param checkboxEl
 */
function changeSubmitButtonStatus(checkboxEl) 
{
    if (checkboxEl.checked) {
        $$('.btn-checkout')[0].removeAttribute("disabled");
        $$('.btn-checkout')[0].show();
    } else {
        $$('.btn-checkout')[0].setAttribute("disabled", "disabled");
        $$('.btn-checkout')[0].hide();
    }
}
/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com
 * @author          Matthias Walter <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

/**
 *
 * @param input
 */
function inputToUpperCase(input) 
{
    var caretPosition = getCaretPos(input);
    input.value = input.value.toUpperCase().replace(/\s/g, '');
    setCaretPos(input, caretPosition);
}

/**
 *
 * @param input
 */
function inputToUppaerCaseAndNumbers(input) 
{
    var caretPosition = getCaretPos(input);
    input.value = input.value.toUpperCase().replace(/\W|[_]/g, '');
    setCaretPos(input, caretPosition);
}

/**
 *
 * @param input
 */
function inputToNumbers(input) 
{
    var caretPosition = getCaretPos(input);
    input.value = input.value.replace(/\D/g, '');
    setCaretPos(input, caretPosition);
}

/**
 *
 * @param oField
 * @returns {number}
 */
function getCaretPos(oField) 
{
    var iCaretPos = 0;
    if (Prototype.Browser.IE) {
        var oSel = document.selection.createRange();
        oSel.moveStart('character', -oField.value.length);
        iCaretPos = oSel.text.length;
    } else {
        iCaretPos = oField.selectionEnd;
    }

    return iCaretPos;
}

/**
 *
 * @param oField
 * @param iCaretPos
 */
function setCaretPos(oField, iCaretPos) 
{
    if (Prototype.Browser.IE) {
        var oSel = document.selection.createRange();
        oSel.moveStart('character', -oField.value.length);
        oSel.moveStart('character', iCaretPos);
        oSel.moveEnd('character', 0);
        oSel.select();
    } else {
        oField.selectionStart = iCaretPos;
        oField.selectionEnd = iCaretPos;
        oField.focus();
    }
}
/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2021 <kontakt@fatchip.de> - www.fatchip.de
 * @author          Fatchip GmbH <kontakt@fatchip.de>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            https://www.fatchip.de
 */

function payWithApplePay(amount, country, currency, networks, createSessionUrl, createPaymentUrl) {
    var session = new ApplePaySession(3, {
        countryCode: country,
        currencyCode: currency,
        supportedNetworks: networks,
        merchantCapabilities: ['supports3DS', 'supportsDebit', 'supportsCredit'],
        total: { label: 'Emma Sleep', amount: amount },
        requiredShippingContactFields: [
            "postalAddress",
            "name",
            "phone",
            "email"
        ],
        shippingMethods: [
            { label: "Standard Shipping", amount: "0", identifier: "delivery", detail: "Free shipping included." },
        ]
    });


    session.onvalidatemerchant = function (evt) {
        var validationUrl = evt.validationURL;

        new Ajax.Request(createSessionUrl,
            {
                method: 'post',
                parameters: {
                    validationUrl: validationUrl
                },
                onSuccess: function (response) {
                    var data = JSON.parse(response.responseText);
                    if (201 !== response.status) {
                        alert(data.status + ' ' + response.status + ' : ' + data.message);
                        return
                    }
                    session.completeMerchantValidation(data.merchantSession);
                },
                onFailure: function (response) {
                    var data = JSON.parse(response.responseText);
                    alert(data.status + ' ' + response.status + ' : ' + data.message);
                }
            }
        );
    };

    session.onpaymentauthorized = function (evt) {
        var token = evt.payment.token,
            address = evt.payment.shippingContact;

        new Ajax.Request(createPaymentUrl,
            {
                method: 'post',
                parameters: {
                    token: JSON.stringify(token),
                    address: JSON.stringify(address)
                },
                onSuccess: function (response) {
                    var data = JSON.parse(response.responseText);

                    if (200 !== response.status) {
                        session.completePayment({
                            status: ApplePaySession.STATUS_FAILURE,
                            errors: [data.message]
                        });
                        return
                    }

                    session.completePayment({
                        status: ApplePaySession.STATUS_SUCCESS,
                        errors: []
                    });

                    window.location = data.redirectUrl;
                },
                onFailure: function (response) {
                    var data = JSON.parse(response.responseText);
                    session.completePayment({
                        status: ApplePaySession.STATUS_FAILURE,
                        errors: [data.message]
                    });
                }
            }
        );
    };

    session.begin()
}

function checkDevice(registerDeviceUrl) {
    var allowedDevice = 0;
    if (window.ApplePaySession) {
        var canMakePayments = ApplePaySession.canMakePayments();
        if (canMakePayments) {
            allowedDevice = 1;
        }
    }

    new Ajax.Request(registerDeviceUrl,
        {
            method: 'post',
            parameters: { allowed: allowedDevice },
            onSuccess: checkDeviceSuccess,
            onFailure: checkDeviceFailure
        }
    );
}
function checkDeviceSuccess(response) {
    var responseData = JSON.parse(response.responseText);

    if (200 !== response.status) {
        alert("Bad response\n" + responseData.message);
    }
}
function checkDeviceFailure(response) {
    var responseData = JSON.parse(response.responseText);
    alert("Failure : Call failed\n" + responseData.message);
}

if ('undefined' === typeof applePayRegisterDeviceUrl) {
    var applePayRegisterDeviceUrl = 'https://' + window.location.hostname + '/payone_core/applepay/registerDevice';
}
checkDevice(applePayRegisterDeviceUrl);

/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2012 <info@noovias.com> - www.noovias.com
 * @author          Matthias Walter <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

var Translator = new Translate([]);

Validation.add(
    'validate-bank-code', Translator.translate('Bank code must contain 8 digits'), function (value) {
    value = value.replace(/\s/g, '');
    if (value == '') {
        return true;
    }

    if (value.length != 8) {
        return false;
    }

    return true;
    }
);

Validation.add(
    'validate-sepa-iban', Translator.translate('IBAN should contain only letters and digits'), function (value) {
    value = value.replace(/\s/g, '');
    if (value == '') {
        return true;
    }

    if (!/[a-zA-Z]{2}[A-Za-z0-9]{10,}$/.test(value)) {
        return false;
    }

    return true;
    }
);

Validation.add(
    'validate-sepa-bic', Translator.translate('BIC can contain only 8-11 characters: digits and letters'), function (value) {
    value = value.replace(/\s/g, '');
    if (value == '') {
        return true;
    }

    if (!/[A-Za-z0-9]{8,11}$/.test(value)) {
        return false;
    }

    return true;
    }
);
/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         js
 * @subpackage      payone
 * @copyright       Copyright (c) 2013 <info@noovias.com> - www.noovias.com
 * @author          Alexander Dite <info@noovias.com>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.noovias.com
 */

function payoneKlarnaCustomerDobInput(output_element)
{
    var daySelect = $('payone_klarna_additional_fields_customer_dob_day');
    var monthSelect = $('payone_klarna_additional_fields_customer_dob_month');
    var yearSelect = $('payone_klarna_additional_fields_customer_dob_year');
    if(output_element == 'payone_financing_klarna_additional_fields_customer_dob_full') {
        var daySelect = $('payone_financing_klarna_additional_fields_customer_dob_day');
        var monthSelect = $('payone_financing_klarna_additional_fields_customer_dob_month');
        var yearSelect = $('payone_financing_klarna_additional_fields_customer_dob_year');
    }

    var hiddenDobFull = $(output_element);

    if (daySelect == undefined || monthSelect == undefined || yearSelect == undefined
        || hiddenDobFull == undefined)  {
        return;
    }

    hiddenDobFull.value = yearSelect.value + "-" + monthSelect.value + "-" + daySelect.value
        + " 00:00:00";
}
class cartMini {
    constructor(){
        if(
            $j('body').hasClass('checkout-onepage-success') ||
            $j('body').hasClass('customer-account-logoutsuccess') ||
            $j('body').hasClass('customer-account-index') ||
            $j('body').hasClass('checkout-klarna-success') ||
            window.location.hash === '#empty_cart'
        ) {
            registry('cart_qty', null, false);
        }
        this.updateQty();


        $j('#checkout-cart-summary, #shopping-cart-table').on('click','.cart__product-remove',function(event) {
            event.preventDefault();
            cartMini.prototype.removeItem(event.currentTarget)
        });
    }

    getStepLoader(currentStep){

        if(currentStep == 'shipping_method'){
            return 'shipping-method';
        }

        return currentStep;

    }

    removeItem(el){

        var url = jQuery(el).attr('delete-url');
        var formKeyElement = $j('input[name=form_key]');
        var form_key = false;

        if(formKeyElement.length > 0){

            this.showCheckoutLoader();
            jQuery(el).addClass('disabled');
            jQuery(el).find('.cart__product-remove--loader').removeClass('is-hidden');

            form_key = formKeyElement[0].value;
            $j.ajax({
                type: 'POST',
                dataType: 'json',
                data: {
                    form_key: form_key
                },
                url: url
            }).done(function(result){
                registry('cart_qty', result.qty, false);
                location.reload();
            });

        }else{
            console.log('missing form key');
        }

    }

    updateQty(){

        if(registry('cart_qty')) {
            var qty = registry('cart_qty');
            var container = $j('#mini-cart-qty')
            if(container){
                container.html(qty);
                if(qty > 0 )
                {
                    container.removeClass('is-hidden');
                }
            }
        }
    }

    submit(form){

        this.showCheckoutLoader();
        form.submit();

    }

    showCheckoutLoader(){
        if(typeof checkout !== 'undefined'){
            var loader = jQuery("#"+this.getStepLoader(checkout.currentStep) + '-please-wait');
            if(loader){
                loader.show();
            }
        }
    }
};
var stripeTokens = {};

var initStripe = function(apiKey, securityMethod, callback)
{
    if (typeof callback == "undefined")
        callback = function() {};

    stripe.securityMethod = securityMethod;
    stripe.apiKey = apiKey;
    stripe.onStripeInitCallback = callback;

    if (stripe.securityMethod == 1)
        stripe.loadStripeJsV2(stripe.onLoadStripeJsV2);

    // We always load v3 so that we use Payment Intents
    stripe.loadStripeJsV3(stripe.onLoadStripeJsV3);

    // Disable server side card validation when Stripe.js is enabled
    if (typeof AdminOrder != 'undefined' && AdminOrder.prototype.loadArea && typeof AdminOrder.prototype._loadArea == 'undefined')
    {
        AdminOrder.prototype._loadArea = AdminOrder.prototype.loadArea;
        AdminOrder.prototype.loadArea = function(area, indicator, params)
        {
            if (typeof area == "object" && area.indexOf('card_validation') >= 0)
                area = area.splice(area.indexOf('card_validation'), 0);

            if (area.length > 0)
                this._loadArea(area, indicator, params);
        };
    }

    // Integrate Stripe.js with various One Step Checkout modules
    initOSCModules();
    stripe.onWindowLoaded(initOSCModules); // Run it again after the page has loaded in case we missed an ajax based OSC module

    // Integrate Stripe.js with the multi-shipping payment form
    stripe.onWindowLoaded(initMultiShippingForm);

    // Errors at the checkout review step should send the customer back to the payment section
    stripe.initReviewStepErrors();
    stripe.onWindowLoaded(stripe.initReviewStepErrors); // For OSC modules

    // Integrate Stripe.js with the admin area
    stripe.onWindowLoaded(initAdmin); // Needed when refreshing the browser
    initAdmin(); // Needed when the payment method is loaded through an ajax call after adding the shipping address
};

var stripe = {
    version: '1.1.9',

    // Properties
    billingInfo: null,
    multiShippingFormInitialized: false,
    oscInitialized: false,
    applePayButton: null,
    applePaySuccess: false,
    applePayResponse: null,
    securityMethod: 0,
    card: null,
    paymentFormValidator: null,
    stripeJsV2: null,
    stripeJsV3: null,
    apiKey: null,
    sourceId: null,
    iconsContainer: null,
    paymentIntent: null,
    paymentIntents: [],
    isAdmin: false,
    PRAPIEvent: null,
    isDynamicCustomerAuthenticationInitialized: false,
    isAlertProxyInitialized: false,
    is3DSecureOpen: false,
    onStripeInitCallback: function() {},

    // Methods
    placeOrder: function() {}, // Will be overwritten dynamically
    shouldLoadStripeJsV2: function()
    {
        return (stripe.securityMethod == 1 || (stripe.securityMethod == 2 && stripe.isApplePayEnabled()));
    },
    loadStripeJsV2: function(callback)
    {
        if (!stripe.shouldLoadStripeJsV2())
            return callback();

        var script = document.getElementsByTagName('script')[0];
        var stripeJsV2 = document.createElement('script');
        stripeJsV2.src = "https://js.stripe.com/v2/";
        stripeJsV2.onload = function()
        {
            stripe.onLoadStripeJsV2();
            callback();
        };
        stripeJsV2.onerror = function(evt) {
            console.warn("Stripe.js v2 could not be loaded");
            console.error(evt);
            callback();
        };
        script.parentNode.insertBefore(stripeJsV2, script);
    },
    loadStripeJsV3: function(callback)
    {
        var script = document.getElementsByTagName('script')[0];
        var stripeJsV3 = document.createElement('script');
        stripeJsV3.src = "https://js.stripe.com/v3/";
        stripeJsV3.onload = function()
        {
            stripe.onLoadStripeJsV3();
            if (typeof callback === 'function') {
                callback();
            }
        };
        stripeJsV3.onerror = function(evt) {
            console.warn("Stripe.js v3 could not be loaded");
            console.error(evt);
        };
        // Do this on the next cycle so that stripe.onLoadStripeJsV2() finishes first
        script.parentNode.insertBefore(stripeJsV3, script);
    },
    onLoadStripeJsV2: function()
    {
        if (!stripe.stripeJsV2)
        {
            Stripe.setPublishableKey(stripe.apiKey);
            stripe.stripeJsV2 = Stripe;
        }
    },
    onLoadStripeJsV3: function()
    {
        if (!stripe.stripeJsV3)
        {
            var params = {
                betas: ['payment_intent_beta_3']
            };
            stripe.stripeJsV3 = Stripe(stripe.apiKey, params);
        }

        stripe.initLoadedStripeJsV3();
    },
    initLoadedStripeJsV3: function()
    {
        stripe.initStripeElements();
        stripe.onWindowLoaded(stripe.initStripeElements);

        stripe.initPaymentRequestButton();
        stripe.onWindowLoaded(stripe.initPaymentRequestButton);

        stripe.onStripeInitCallback();
    },
    onWindowLoaded: function(callback)
    {
        if (window.attachEvent)
            window.attachEvent("onload", callback); // IE
        else
            window.addEventListener("load", callback); // Other browsers
    },
    initReviewStepErrors: function()
    {
        if (typeof Review == 'undefined' || typeof Review.prototype.nextStep == 'undefined')
            return;

        Review.prototype._nextStep = Review.prototype.nextStep;

        var nextStep = Review.prototype.nextStep;
        Review.prototype.nextStep = function(transport)
        {
            if (stripe.oscInitialized)
                return this._nextStep(transport);

            if (transport) {
                var response = transport.responseJSON || transport.responseText.evalJSON(true) || {};

                if (response.redirect) {
                    this.isSuccess = true;
                    location.href = encodeURI(response.redirect);
                    return;
                }
                if (response.success) {
                    this.isSuccess = true;
                    location.href = encodeURI(this.successUrl);
                }
                else{
                    var msg = response.error_messages;
                    if (Object.isArray(msg)) {
                        msg = msg.join("\n").stripTags().toString();
                    }
                    if (msg) {
                        stripe.displayReviewStepError(msg);
                    }
                }

                if (response.update_section) {
                    $('checkout-'+response.update_section.name+'-load').update(response.update_section.html);
                }

                if (response.goto_section) {
                    checkout.gotoSection(response.goto_section, true);
                }
            }
        };
        if (typeof review != 'undefined')
        {
            review.nextStep = Review.prototype.nextStep;
            review._nextStep = Review.prototype._nextStep;
        }
    },
    displayReviewStepError: function(msg)
    {
        if (msg.indexOf("reusable source you provided is consumed") >= 0)
        {
            alert("Your card was declined");
            stripe.displayCardError("Your card was declined", true);
            deleteStripeToken();
        }
        else if (msg.indexOf("card was declined") >= 0)
        {
            alert(msg);
            stripe.displayCardError(msg, true);
            deleteStripeToken();
        }
        else
            alert(msg);
    },
    validatePaymentForm: function(callback)
    {
        if (!this.paymentFormValidator)
            this.paymentFormValidator = new Validation('payment_form_stripe_payments');

        if (!this.paymentFormValidator.form)
            this.paymentFormValidator = new Validation('new-card');

        if (!this.paymentFormValidator.form)
            return true;

        this.paymentFormValidator.reset();

        result = this.paymentFormValidator.validate();

        // The Magento validator will try to pass over injected Stripe Elements, so to exclude those,
        // check if any of the form elements have a validation-failed class
        if (!result)
        {
            var failedElements = Form.getElements('payment_form_stripe_payments').findAll(function(elm){
                return $(elm).hasClassName('validation-failed');
            });
            if (failedElements.length === 0)
                return true;
        }

        return result;
    },
    placeAdminOrder: function(e)
    {
        var radioButton = document.getElementById('p_method_stripe_payments');
        if (radioButton && !radioButton.checked)
            return order.submit();

        createStripeToken(function(err)
        {
            if (err)
                alert(err);
            else
                order.submit();
        });
    },
    addAVSFieldsTo: function(cardDetails)
    {
        var owner = stripe.getSourceOwner();
        cardDetails.name = owner.name;
        cardDetails.address_line1 = owner.address.line1;
        cardDetails.address_line2 = owner.address.line2;
        cardDetails.address_zip = owner.address.postal_code;
        cardDetails.address_city = owner.address.city;
        cardDetails.address_state = owner.address.state;
        cardDetails.address_country = owner.address.country;
        return cardDetails;
    },
    getSourceOwner: function()
    {
        // Format is
        var owner = {
            name: null,
            email: null,
            phone: null,
            address: {
                city: null,
                country: null,
                line1: null,
                line2: null,
                postal_code: null,
                state: null
            }
        };

        // If there is an address select dropdown, don't read the address from the input fields in case
        // the customer changes the address from the dropdown. Dropdown value changes do not update the
        // plain input fields
        if (!document.getElementById('billing-address-select'))
        {
            // Scenario 1: We are in the admin area creating an order for a guest who has no saved address yet
            var line1 = document.getElementById('order-billing_address_street0');
            var postcode = document.getElementById('order-billing_address_postcode');
            var email = document.getElementById('order-billing_address_email');

            // Scenario 2: Checkout page with an OSC module and a guest customer
            if (!line1)
                line1 = document.getElementById('billing:street1');

            if (!postcode)
                postcode = document.getElementById('billing:postcode');

            if (!email)
                email = document.getElementById('billing:email');

            if (line1)
                owner.address.line1 = line1.value;

            if (postcode)
                owner.address.postal_code = postcode.value;

            if (email)
                owner.email = email.value;

            // New fields
            if (document.getElementById('billing:firstname'))
                owner.name = document.getElementById('billing:firstname').value + ' ' + document.getElementById('billing:lastname').value;

            if (document.getElementById('billing:telephone'))
                owner.phone = document.getElementById('billing:telephone').value;

            if (document.getElementById('billing:city'))
                owner.address.city = document.getElementById('billing:city').value;

            if (document.getElementById('billing:country_id'))
                owner.address.country = document.getElementById('billing:country_id').value;

            if (document.getElementById('billing:street2'))
                owner.address.line2 = document.getElementById('billing:street2').value;

            if (document.getElementById('billing:region'))
                owner.address.state = document.getElementById('billing:region').value;
        }

        // Scenario 3: Checkout or admin area and a registered customer already has a pre-loaded billing address
        if (stripe.billingInfo !== null)
        {
            if (owner.email === null && stripe.billingInfo.email !== null)
                owner.email = stripe.billingInfo.email;

            if (owner.address.line1 === null && stripe.billingInfo.line1 !== null)
                owner.address.line1 = stripe.billingInfo.line1;

            if (owner.address.postal_code === null && stripe.billingInfo.postcode !== null)
                owner.address.postal_code = stripe.billingInfo.postcode;

            // New fields
            if (owner.name === null && stripe.billingInfo.name !== null)
                owner.name = stripe.billingInfo.name;

            if (owner.phone === null && stripe.billingInfo.phone !== null)
                owner.phone = stripe.billingInfo.phone;

            if (owner.address.city === null && stripe.billingInfo.city !== null)
                owner.address.city = stripe.billingInfo.city;

            if (owner.address.country === null && stripe.billingInfo.country !== null)
                owner.address.country = stripe.billingInfo.country;

            if (owner.address.line2 === null && stripe.billingInfo.line2 !== null)
                owner.address.line2 = stripe.billingInfo.line2;

            if (owner.address.state === null && stripe.billingInfo.state !== null)
                owner.address.state = stripe.billingInfo.state;
        }

        if (!owner.phone)
            delete owner.phone;

        return owner;
    },
    displayCardError: function(message, inline)
    {
        // Some OSC modules have the Place Order button away from the payment form
        if (stripe.oscInitialized && typeof inline == 'undefined')
        {
            alert(message);
            return;
        }

        // When we use a saved card, display the message as an alert
        var newCardRadio = document.getElementById('new_card');
        if (newCardRadio && !newCardRadio.checked)
        {
            alert(message);
            return;
        }

        var box = $('stripe-payments-card-errors');

        if (box)
        {
            try
            {
                checkout.gotoSection("payment");
            }
            catch (e) {}

            box.update(message);
            box.addClassName('populated');
        }
        else
            alert(message);
    },
    clearCardErrors: function()
    {
        var box = $('stripe-payments-card-errors');

        if (box)
        {
            box.update("");
            box.removeClassName('populated');
        }
    },
    isApplePayEnabled: function()
    {
        // Some OSC modules will refuse to reload the payment method when the billing address is changed for a customer.
        // We can't use Apple Pay without a billing address
        if (typeof paramsApplePay == "undefined" || !paramsApplePay)
            return false;

        return true;
    },
    hasNoCountryCode: function()
    {
        return (typeof paramsApplePay.country == "undefined" || !paramsApplePay.country || paramsApplePay.country.length === 0);
    },
    getCountryElement: function()
    {
        var element = document.getElementById('billing:country_id');

        if (!element)
            element = document.getElementById('billing_country_id');

        if (!element)
        {
            var selects = document.getElementsByName('billing[country_id]');
            if (selects.length > 0)
                element = selects[0];
        }

        return element;
    },
    getCountryCode: function()
    {
        var element = stripe.getCountryElement();

        if (!element)
            return null;

        if (element.value && element.value.length > 0)
            return element.value;

        return null;
    },
    initResetButton: function()
    {
        var resetButton = document.getElementById('apple-pay-reset');
        resetButton.addEventListener('click', resetApplePayToken);
        resetButton.disabled = false;
    },
    getStripeElementsStyle: function()
    {
        // Custom styling can be passed to options when creating an Element.
        return {
            base: {
                // Add your base input styles here. For example:
                fontSize: '16px',
                lineHeight: '24px'
                // iconColor: '#c4f0ff',
                // color: '#31325F'
        //         fontWeight: 300,
        //         fontFamily: '"Helvetica Neue", Helvetica, sans-serif',

        //         '::placeholder': {
        //             color: '#CFD7E0'
        //         }
            }
        };
    },
    getStripeElementCardNumberOptions: function()
    {
        return {
            // iconStyle: 'solid',
            // hideIcon: false,
            style: stripe.getStripeElementsStyle()
        };
    },
    getStripeElementCardExpiryOptions: function()
    {
        return {
            style: stripe.getStripeElementsStyle()
        };
    },
    getStripeElementCardCvcOptions: function()
    {
        return {
            style: stripe.getStripeElementsStyle()
        };
    },
    getStripeElementsOptions: function()
    {
        return {
            locale: 'auto'
        };
    },
    initStripeElements: function()
    {
        if (stripe.securityMethod != 2)
            return;

        if (document.getElementById('stripe-payments-card-number') === null)
            return;

        var elements = stripe.stripeJsV3.elements(stripe.getStripeElementsOptions());

        var cardNumber = stripe.card = elements.create('cardNumber', stripe.getStripeElementCardNumberOptions());
        cardNumber.mount('#stripe-payments-card-number');
        cardNumber.addEventListener('change', stripe.stripeElementsOnChange);

        var cardExpiry = elements.create('cardExpiry', stripe.getStripeElementCardExpiryOptions());
        cardExpiry.mount('#stripe-payments-card-expiry');
        cardExpiry.addEventListener('change', stripe.stripeElementsOnChange);

        var cardCvc = elements.create('cardCvc', stripe.getStripeElementCardCvcOptions());
        cardCvc.mount('#stripe-payments-card-cvc');
        cardCvc.addEventListener('change', stripe.stripeElementsOnChange);
    },
    stripeElementsOnChange: function(event)
    {
        if (typeof event.brand != 'undefined')
            stripe.onCardNumberChanged(event.brand);

        if (event.error)
            stripe.displayCardError(event.error.message, true);
        else
            stripe.clearCardErrors();
    },
    onCardNumberChanged: function(cardType)
    {
        stripe.onCardNumberChangedFade(cardType);
        stripe.onCardNumberChangedSwapIcon(cardType);
    },
    resetIconsFade: function()
    {
        stripe.iconsContainer.className = 'input-box';
        var children = stripe.iconsContainer.getElementsByTagName('img');
        for (var i = 0; i < children.length; i++)
            children[i].className = '';
    },
    onCardNumberChangedFade: function(cardType)
    {
        if (!stripe.iconsContainer)
            stripe.iconsContainer = document.getElementById('stripe-payments-accepted-cards');

        if (!stripe.iconsContainer)
            return;

        stripe.resetIconsFade();

        if (!cardType || cardType == "unknown") return;

        var img = document.getElementById('stripe_payments_' + cardType + '_type');
        if (!img) return;

        img.className = 'active';
        stripe.iconsContainer.className = 'input-box stripe-payments-detected';
    },
    cardBrandToPfClass: {
        'visa': 'pf-visa',
        'mastercard': 'pf-mastercard',
        'amex': 'pf-american-express',
        'discover': 'pf-discover',
        'diners': 'pf-diners',
        'jcb': 'pf-jcb',
        'unknown': 'pf-credit-card',
    },
    onCardNumberChangedSwapIcon: function(cardType)
    {
        var brandIconElement = document.getElementById('stripe-payments-brand-icon');
        var pfClass = 'pf-credit-card';
        if (cardType in stripe.cardBrandToPfClass)
            pfClass = stripe.cardBrandToPfClass[cardType];

        for (var i = brandIconElement.classList.length - 1; i >= 0; i--)
            brandIconElement.classList.remove(brandIconElement.classList[i]);

        brandIconElement.classList.add('pf');
        brandIconElement.classList.add(pfClass);
    },
    initPaymentRequestButton: function()
    {
        if (!stripe.isApplePayEnabled())
            return;

        if (stripe.hasNoCountryCode())
            paramsApplePay.country = stripe.getCountryCode();

        if (stripe.hasNoCountryCode())
            return;

        var paymentRequest;
        try
        {
            paymentRequest = stripe.stripeJsV3.paymentRequest(paramsApplePay);
            var elements = stripe.stripeJsV3.elements();
            var prButton = elements.create('paymentRequestButton', {
                paymentRequest: paymentRequest,
            });
        }
        catch (e)
        {
            console.warn(e.message);
            return;
        }

        // Check the availability of the Payment Request API first.
        paymentRequest.canMakePayment().then(function(result)
        {
            if (result)
            {
                if (!document.getElementById('payment-request-button'))
                    return;

                prButton.mount('#payment-request-button');
                $('payment_form_stripe_payments').addClassName('payment-request-api-supported');
                if ($('co-payment-form'))
                    $('co-payment-form').addClassName('payment-request-api-supported');
                stripe.initResetButton();
            }
        });

        paymentRequest.on('paymentmethod', function(result)
        {
            try
            {
                stripe.PRAPIEvent = result;
                setStripeToken(result.paymentMethod.id + ':' + result.paymentMethod.card.brand + ':' + result.paymentMethod.card.last4);
                setApplePayToken(result.paymentMethod);
                stripe.closePaysheet('success');
            }
            catch (e)
            {
                stripe.closePaysheet('fail');
                console.error(e);
            }
        });
    },
    isPaymentMethodSelected: function()
    {
        if (typeof payment != 'undefined' && typeof payment.currentMethod != 'undefined' && payment.currentMethod.length > 0)
            return (payment.currentMethod == 'stripe_payments');
        else
        {
            var radioButton = document.getElementById('p_method_stripe_payments');
            if (!radioButton || !radioButton.checked)
                return false;

            return true;
        }
    },
    selectMandate: function()
    {
        document.getElementById('stripe_payments_sepa_iban').classList.remove("required-entry");
    },
    selectNewIBAN: function()
    {
        document.getElementById('new_mandate').checked = 1;
        document.getElementById('stripe_payments_sepa_iban').classList.add("required-entry");
    },
    setLoadWaiting: function(section)
    {
        // Check if defined first in case of an OSC module rewriting the whole thing
        if (typeof checkout != 'undefined' && checkout && checkout.setLoadWaiting)
        {
            try
            {
                // OSC modules may also cause crashes if they have stripped away the html elements
                checkout.setLoadWaiting(section);
            }
            catch (e) {}
        }
        else
            stripe.toggleAdminSave(section);
    },
    // Triggered when the user clicks a saved card radio button
    useCard: function()
    {
        var token = stripe.getSelectedSavedCard();

        // User wants to use a new card
        if (token == null)
        {
            enablePaymentFormValidation();
            deleteStripeToken();
            stripe.sourceId = null;
        }
        // User wants to use a saved card
        else
        {
            disablePaymentFormValidation();
            setStripeToken(token);
            stripe.sourceId = stripe.cleanToken(token);
        }
    },
    getSelectedSavedCard: function()
    {
        var elements = document.getElementsByName("payment[cc_saved]");
        if (elements.length == 0)
            return null;
        var selected = null;
        for (var i = 0; i < elements.length; i++)
            if (elements[i].checked)
                selected = elements[i];
        if (!selected)
            return null;
        if (selected.value == 'new_card')
            return null;
        return selected.value;
    },
    // Converts tokens in the form "src_1E8UX32WmagXEVq4SpUlSuoa:Visa:4242" into src_1E8UX32WmagXEVq4SpUlSuoa
    cleanToken: function(token)
    {
        if (token.indexOf(":") >= 0)
            return token.substring(0, token.indexOf(":"));
        return token;
    },
    shouldSaveCard: function()
    {
        var saveCardInput = document.getElementById('stripe_payments_cc_save');
        if (!saveCardInput)
            return false;
        return saveCardInput.checked;
    },
    getPaymentIntent: function(callback)
    {
        new Ajax.Request(
            MAGENTO_BASE_URL + 'stripe_payments/api/get_payment_intent', {
                method: 'post',
                onComplete: function (response)
                {
                    try
                    {
                        callback(null, response.responseJSON.paymentIntent);
                    }
                    catch (e)
                    {
                        callback("Could not retrieve payment details, please contact us for help");
                        console.error(response);
                    }
                }
            }
        );
    },
    handleCardPayment: function(done)
    {
        try
        {
            stripe.closePaysheet('success');

            stripe.stripeJsV3.handleCardPayment(stripe.paymentIntent).then(function(result)
            {
                if (result.error)
                    return done(result.error.message);

                return done();
            });
        }
        catch (e)
        {
            done(e.message);
        }
    },
    handleCardAction: function(done)
    {
        try
        {
            stripe.closePaysheet('success');

            stripe.stripeJsV3.handleCardAction(stripe.paymentIntent).then(function(result)
            {
                if (result.error)
                    return done(result.error.message);

                return done();
            });
        }
        catch (e)
        {
            done(e.message);
        }
    },
    processNextAuthentication: function(done)
    {
        if (stripe.paymentIntents.length > 0)
        {
            stripe.paymentIntent = stripe.paymentIntents.pop();
            stripe.authenticateCustomer(function(err)
            {
                if (err)
                    done(err);
                else
                    stripe.processNextAuthentication(done);
            });
        }
        else
        {
            stripe.paymentIntent = null;
            return done();
        }
    },
    authenticateCustomer: function(done)
    {
        try
        {
            stripe.stripeJsV3.retrievePaymentIntent(stripe.paymentIntent).then(function(result)
            {
                if (result.error)
                    return done(result.error);

                if (result.paymentIntent.status == "requires_action"
                    || result.paymentIntent.status == "requires_source_action")
                {
                    if (result.paymentIntent.confirmation_method == "manual")
                        return stripe.handleCardAction(done);
                    else
                        return stripe.handleCardPayment(done);
                }

                return done();
            });
        }
        catch (e)
        {
            done(e.message);
        }
    },
    isNextAction3DSecureRedirect: function(result)
    {
        if (!result)
            return false;

        if (typeof result.paymentIntent == 'undefined' || !result.paymentIntent)
            return false;

        if (typeof result.paymentIntent.next_action == 'undefined' || !result.paymentIntent.next_action)
            return false;

        if (typeof result.paymentIntent.next_action.use_stripe_sdk == 'undefined' || !result.paymentIntent.next_action.use_stripe_sdk)
            return false;

        if (typeof result.paymentIntent.next_action.use_stripe_sdk.type == 'undefined' || !result.paymentIntent.next_action.use_stripe_sdk.type)
            return false;

        return (result.paymentIntent.next_action.use_stripe_sdk.type == 'three_d_secure_redirect');
    },
    paymentIntentCanBeConfirmed: function()
    {
        // If stripe.sourceId exists, it means that we are using a saved card source, which is not going to be a 3DS card
        // (because those are hidden from the admin saved cards section)
        return !stripe.sourceId;
    },
    maskError: function(err)
    {
        var errLowercase = err.toLowerCase();
        var pos1 = errLowercase.indexOf("Invalid API key provided".toLowerCase());
        var pos2 = errLowercase.indexOf("No API key provided".toLowerCase());
        if (pos1 === 0 || pos2 === 0)
            return 'Invalid Stripe API key provided.';

        return err;
    },
    closePaysheet: function(withResult)
    {
        try
        {
            if (!stripe.PRAPIEvent)
                return;

            stripe.PRAPIEvent.complete(withResult);
        }
        catch (e)
        {
            // Will get here if we already closed it
        }
    },
    isApplePayInsideForm: function()
    {
        return stripe.applePayLocation == 2;
    },
    triggerCustomerAuthentication: function()
    {
        if (stripe.is3DSecureOpen)
            return;

        stripe.agreeToTerms();
        stripe.is3DSecureOpen = true;
        stripe.authenticateCustomer(function(err)
        {
            stripe.is3DSecureOpen = false;

            if (err)
                return stripe.displayCardError(err);

            stripe.placeOrder();
        });
    },
    agreeToTerms: function()
    {
        // Some OSC modules such as LotusBreath and Idev OSC reload the page when customer authentication is required
        // causing the terms and agreements checkboxes to lose their value. We re-agree here so that we can resubmit the form.
        var agreements = $$(".checkout-agreements input[type=checkbox]");
        for (var i = 0; i < agreements.length; i++)
            agreements[i].checked = true;
    },
    parseErrorMessage: function(msg)
    {
        stripe.paymentIntent = null;

        if (msg == "Authentication Required")
            return true;

        // Case of subscriptions
        if (msg.indexOf("Authentication Required: ") === 0)
        {
            stripe.paymentIntent = msg.substring("Authentication Required: ".length);
            return true;
        }
        // FME QuickCheckout prefers to inform us that this is a core exception...
        else if (msg.indexOf("Core Exception: Authentication Required: ") === 0)
        {
            stripe.paymentIntent = msg.substring("Core Exception: Authentication Required: ".length);
            return true;
        }

        return false;
    },
    isAuthenticationRequired: function(msgs)
    {
        if (typeof msgs == "undefined")
            return false;

        if (typeof msgs[0] == "string")
        {
            var multipleMsgs = msgs[0].split(/\n/);
            if (multipleMsgs.length > 0)
            {
                for (var i = 0; i < multipleMsgs.length; i++)
                    if (stripe.parseErrorMessage(multipleMsgs[i]))
                        return true;
            }
        }

        return false;
    },
    initAlertProxy: function(authenticationMethod)
    {
        if (stripe.isAlertProxyInitialized)
            return;

        stripe.isAlertProxyInitialized = true;

        (function(proxied)
        {
            window.alert = function()
            {
                if (stripe.isAuthenticationRequired(arguments))
                {
                    authenticationMethod();
                }
                else
                    return proxied.apply(this, arguments);
            };
        })
        (window.alert);
    },
    searchForAuthenticationRequiredError: function(authenticationMethod)
    {
        // Some OSC modules will not alert the error, they will instead redirect to the same page and add the error in a DOM element.
        // Here we handle those cases
        var errors = $$('.onestepcheckout-error')
            .concat($$('.error-msg li'))
            .concat($$('.error-msg span'))
            .concat($$('.opc-message-container'))
            .concat($$('#saveOder-error'));

        for (var i = 0; i < errors.length; i++)
        {
            if (!errors[i])
                continue;

            if (stripe.parseErrorMessage(errors[i].innerText))
            {
                errors.each(Element.hide);
                $$('ul.messages').each(Element.hide);
                authenticationMethod();
                break;
            }
        }
    },
    toggleAdminSave: function(disable)
    {
        if (typeof disableElements != 'undefined' && typeof enableElements != 'undefined')
        {
            if (disable)
                disableElements('save');
            else
                enableElements('save');
        }
    },
    ach:
    {
        token: null,
        verificationError: 'Could not verify bank account details!',

        getParams: function()
        {
            var routingNumber = $('stripe-ach-routing_number').value;
            var accountNumber = $('stripe-ach-account_number').value;
            var accountHolderName = $('stripe-ach-account_holder_name').value;
            var accountHolderType = $('stripe-ach-account_holder_type').value;
            var country = $('stripe-ach-country').value;
            var currency = $('stripe-ach-currency').value;

            if (routingNumber.length === 0 ||
                accountNumber.length === 0 ||
                accountHolderName.length === 0 ||
                accountHolderType.length === 0)
            {
                stripe.ach.verificationError = 'Please enter your account details';
                return false;
            }

            if (country.length === 0 ||
                currency.length === 0)
            {
                stripe.ach.verificationError = 'Your country or currency could not be determined';
                return false;
            }

            return {
              country: country,
              currency: currency,
              routing_number: routingNumber,
              account_number: accountNumber,
              account_holder_name: accountHolderName,
              account_holder_type: accountHolderType,
            };
        },
        generateToken: function()
        {
            var params = stripe.ach.getParams();

            if (!params)
                return;

            if (params.routing_number.length < 9)
                return;

            if (params.account_number.length < 4)
                return;

            if (!stripe.stripeJsV3)
            {
                stripe.ach.verificationError = 'Could not verify bank details because the Stripe.js v3 security method has not been enabled';
                return;
            }

            stripe.ach.hideErrors();

            stripe.stripeJsV3.createToken('bank_account', params).then(function(result)
            {
                if (result.token)
                    stripe.ach.setToken(result.token.id, result.token.bank_account);
                else
                {
                    if (result.error)
                        stripe.ach.verificationError = result.error.message;
                    else
                        stripe.ach.verificationError = 'Your bank account details could not be used to verify your account';

                    stripe.ach.showErrors();
                }
            });
        },
        validateForm: function(value)
        {
            stripe.ach.generateToken();

            if (stripe.ach.token)
                return true;

            stripe.ach.showErrors();

            return false;
        },
        resetToken: function()
        {
            stripe.ach.token = null;
            $('stripe-ach-token').value = "";

            stripe.ach.hideSuccessMessage();
            stripe.ach.hideErrors();
            stripe.ach.generateToken();
        },
        setToken: function(token, bank_account)
        {
            stripe.ach.token = token;
            $('stripe-ach-token').value = token;

            stripe.ach.showSuccessMessage();
            stripe.ach.hideErrors();
        },
        setVerificationError: function()
        {
            setTimeout(function(){
                var el = $('advice-stripe-payments-ach-generate-token-stripe-ach-token');
                if (el)
                    el.innerText = stripe.ach.verificationError;
            }, 10);
        },
        hideErrors: function()
        {
            $('ach-bank-account-details').removeClassName("showVerificationError");
            stripe.ach.verificationError = 'Could not verify bank account details!';
            stripe.ach.setVerificationError();
        },
        showErrors: function()
        {
            $('ach-bank-account-details').addClassName("showVerificationError");
            stripe.ach.setVerificationError();
        },
        hideSuccessMessage: function()
        {
            $('stripe-ach-account-verified').style.display = "none";
        },
        showSuccessMessage: function()
        {
            $('stripe-ach-account-verified').style.display = "block";
        }
    }
};

var initAdmin = function()
{
    var btn = document.getElementById('order-totals');
    if (btn) btn = btn.getElementsByTagName('button');
    if (btn && btn[0]) btn = btn[0];
    if (btn) btn.onclick = stripe.placeAdminOrder;

    var topBtns = document.getElementsByClassName('save');
    for (var i = 0; i < topBtns.length; i++)
    {
        topBtns[i].onclick = stripe.placeAdminOrder;
    }
};

var setApplePayToken = function(token)
{
    if (!stripe.isApplePayEnabled())
        return;

    var radio = document.querySelector('input[name="payment[cc_saved]"]:checked');
    if (!radio || (radio && radio.value == 'new_card'))
        disablePaymentFormValidation();

    if ($('new_card'))
        $('new_card').removeClassName('validate-one-required-by-name');

    $('apple-pay-result-brand').update(token.card.brand);
    $('apple-pay-result-last4').update(token.card.last4);
    $('payment_form_stripe_payments').addClassName('apple-pay-success');

    if (!stripe.isApplePayInsideForm() && $('co-payment-form'))
        $('co-payment-form').addClassName('apple-pay-success');

    $('apple-pay-result-brand').className = "type " + token.card.brand;
    stripe.applePaySuccess = true;
    stripe.applePayToken = token;
    stripe.sourceId = token.id;

    // Ensure that a payment method is selected if Apple Pay is used outside the payment form
    var el = document.getElementById("p_method_stripe_payments");
    if (el) el.checked = true;
};

var resetApplePayToken = function()
{
    if (!stripe.isApplePayEnabled())
        return;

    var radio = document.querySelector('input[name="payment[cc_saved]"]:checked');
    if (!radio || (radio && radio.value == 'new_card'))
        enablePaymentFormValidation();

    if ($('new_card'))
        $('new_card').addClassName('validate-one-required-by-name');

    $('payment_form_stripe_payments').removeClassName('apple-pay-success');

    if (!stripe.isApplePayInsideForm() && $('co-payment-form'))
        $('co-payment-form').removeClassName('apple-pay-success');

    if ($('apple-pay-result-brand'))
    {
        $('apple-pay-result-brand').update();
        $('apple-pay-result-last4').update();
        $('apple-pay-result-brand').className = "";
    }
    deleteStripeToken();
    stripe.applePaySuccess = false;
    stripe.applePayToken = null;
};

var getCardDetails = function()
{
    // Validate the card
    var cardName = document.getElementById('stripe_payments_cc_owner');
    var cardNumber = document.getElementById('stripe_payments_cc_number');
    var cardCvc = document.getElementById('stripe_payments_cc_cid');
    var cardExpMonth = document.getElementById('stripe_payments_expiration');
    var cardExpYear = document.getElementById('stripe_payments_expiration_yr');

    var isValid = cardName && cardName.value && cardNumber && cardNumber.value && cardCvc && cardCvc.value && cardExpMonth && cardExpMonth.value && cardExpYear && cardExpYear.value;

    if (!isValid) return null;

    var cardDetails = {
        name: cardName.value,
        number: cardNumber.value,
        cvc: cardCvc.value,
        exp_month: cardExpMonth.value,
        exp_year: cardExpYear.value
    };

    cardDetails = stripe.addAVSFieldsTo(cardDetails);

    return cardDetails;
};

var createStripeToken = function(callback)
{
    stripe.clearCardErrors();

    // Card validation, displays the error at the payment form section
    if (!stripe.validatePaymentForm())
        return;

    // Terms and Agreements validation, shows as an alert
    var terms = $$('#checkout-agreements input[type=checkbox]');

    stripe.setLoadWaiting('review');
    var done = function(err)
    {
        stripe.setLoadWaiting(false);

        if (err)
        {
            resetApplePayToken();
            err = stripe.maskError(err);
        }

        return callback(err);
    };

    if (stripe.applePaySuccess)
    {
        return done();
    }

    // First check if the "Use new card" radio is selected, return if not
    var cardDetails, newCardRadio = document.getElementById('new_card');
    if (newCardRadio && !newCardRadio.checked)
    {
        if (stripe.sourceId)
            setStripeToken(stripe.sourceId);
        else
            return done("No card specified");

        return done(); // We are using a saved card token for the payment
    }

    try
    {
        var data = {
            billing_details: stripe.getSourceOwner()
        };

        stripe.stripeJsV3.createPaymentMethod('card', stripe.card, data).then(function(result)
        {
            if (result.error)
                return done(result.error.message);

            var cardKey = result.paymentMethod.id;
            var token = result.paymentMethod.id + ':' + result.paymentMethod.card.brand + ':' + result.paymentMethod.card.last4;
            stripeTokens[cardKey] = token;
            setStripeToken(token);

            return done();
        });
    }
    catch (e)
    {
        return done(e.message);
    }
};

function setStripeToken(token)
{
    try
    {
        var input, inputs = document.getElementsByClassName('stripejs-token');
        if (inputs && inputs[0]) input = inputs[0];
        else input = document.createElement("input");
        input.setAttribute("type", "hidden");
        input.setAttribute("name", "payment[cc_stripejs_token]");
        input.setAttribute("class", 'stripejs-token');
        input.setAttribute("value", token);
        input.disabled = false; // Gets disabled when the user navigates back to shipping method
        var form = document.getElementById('payment_form_stripe_payments');
        if (!form) form = document.getElementById('co-payment-form');
        if (!form) form = document.getElementById('order-billing_method_form');
        if (!form) form = document.getElementById('onestepcheckout-form');
        if (!form && typeof payment != 'undefined') form = document.getElementById(payment.formId);
        if (!form)
        {
            form = document.getElementById('new-card');
            input.setAttribute("name", "newcard[cc_stripejs_token]");
        }
        form.appendChild(input);
    } catch (e) {}
}

function deleteStripeToken()
{
    var input, inputs = document.getElementsByClassName('stripejs-token');
    if (inputs && inputs[0]) input = inputs[0];
    if (input && input.parentNode) input.parentNode.removeChild(input);
}

// Multi-shipping form support for Stripe.js
var multiShippingForm = null, multiShippingFormSubmitButton = null;

function submitMultiShippingForm(e)
{
    if (!stripe.isPaymentMethodSelected())
        return true;

    if (e.preventDefault) e.preventDefault();

    if (!multiShippingFormSubmitButton) multiShippingFormSubmitButton = document.getElementById('payment-continue');
    if (multiShippingFormSubmitButton) multiShippingFormSubmitButton.disabled = true;

    createStripeToken(function(err)
    {
        if (multiShippingFormSubmitButton) multiShippingFormSubmitButton.disabled = false;

        if (err)
            stripe.displayCardError(err);
        else
            multiShippingForm.submit();
    });

    return false;
}

// Multi-shipping form
var initMultiShippingForm = function()
{
    if (typeof payment == 'undefined' ||
        payment.formId != 'multishipping-billing-form' ||
        stripe.multiShippingFormInitialized)
        return;

    multiShippingForm = document.getElementById(payment.formId);
    if (!multiShippingForm) return;

    if (multiShippingForm.attachEvent)
        multiShippingForm.attachEvent("submit", submitMultiShippingForm);
    else
        multiShippingForm.addEventListener("submit", submitMultiShippingForm);

    stripe.multiShippingFormInitialized = true;
};

var isCheckbox = function(input)
{
    return input.attributes && input.attributes.length > 0 &&
        (input.type === "checkbox" || input.attributes[0].value === "checkbox" || input.attributes[0].nodeValue === "checkbox");
};

var disablePaymentFormValidation = function()
{
    var i, inputs = document.querySelectorAll(".stripe-input");
    var parentId = 'payment_form_stripe_payments';

    $(parentId).removeClassName("stripe-new");
    for (i = 0; i < inputs.length; i++)
    {
        if (isCheckbox(inputs[i])) continue;
        $(inputs[i]).removeClassName('required-entry');
    }
};

var enablePaymentFormValidation = function()
{
    var i, inputs = document.querySelectorAll(".stripe-input");
    var parentId = 'payment_form_stripe_payments';

    $(parentId).addClassName("stripe-new");
    for (i = 0; i < inputs.length; i++)
    {
        if (isCheckbox(inputs[i])) continue;
        $(inputs[i]).addClassName('required-entry');
    }
};

var toggleValidation = function(evt)
{
    $('new_card').removeClassName('validate-one-required-by-name');
    if (evt.target.value == 'stripe_payments')
        $('new_card').addClassName('validate-one-required-by-name');
};

var initSavedCards = function(isAdmin)
{
    if (isAdmin)
    {
        // Adjust validation if necessary
        var newCardRadio = document.getElementById('new_card');
        if (newCardRadio)
        {
            var methods = document.getElementsByName('payment[method]');
            for (var j = 0; j < methods.length; j++)
                methods[j].addEventListener("click", toggleValidation);
        }
    }
};

var saveNewCard = function()
{
    var saveButton = document.getElementById('stripe-savecard-button');
    var wait = document.getElementById('stripe-savecard-please-wait');
    saveButton.style.display = "none";
    wait.style.display = "block";

    if (typeof Stripe != 'undefined')
    {
        createStripeToken(function(err)
        {
            saveButton.style.display = "block";
            wait.style.display = "none";

            if (err)
                stripe.displayCardError(err);
            else
                document.getElementById("new-card").submit();

        });
        return false;
    }

    return true;
};

var initOSCModules = function()
{
    if (stripe.oscInitialized) return;

    // Front end bindings
    if (typeof IWD != "undefined" && typeof IWD.OPC != "undefined")
    {
        IWD.OPC.isAuthenticationInProgress = false;

        // IWD OnePage Checkout override, which is a tad of a mess
        var proceed = function()
        {
            if (typeof $j == 'undefined') // IWD 4.0.4
                $j = $j_opc; // IWD 4.0.8

            var form = $j('#co-payment-form').serializeArray();
            IWD.OPC.Checkout.xhr = $j.post(IWD.OPC.Checkout.config.baseUrl + 'onepage/json/savePayment',form, IWD.OPC.preparePaymentResponse,'json');
        };

        stripe.placeOrder = function()
        {
            proceed();
        };

        IWD.OPC.savePayment = function()
        {
            if (!IWD.OPC.saveOrderStatus)
                return;

            if (IWD.OPC.Checkout.xhr !== null)
                IWD.OPC.Checkout.xhr.abort();

            IWD.OPC.Checkout.lockPlaceOrder();

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            if (IWD.OPC.isAuthenticationInProgress && typeof IWD.OPC.saveOrder != "undefined") // IWD 4.3.4
            {
                IWD.OPC.isAuthenticationInProgress = false; // Turn it off on the second order submission
                IWD.OPC.saveOrder();
                return;
            }

            createStripeToken(function(err)
            {
                IWD.OPC.Checkout.xhr = null;
                IWD.OPC.Checkout.unlockPlaceOrder();

                if (err)
                {
                    IWD.OPC.Checkout.hideLoader();
                    stripe.displayCardError(err);
                }
                else
                    stripe.placeOrder();
            });
        };

        stripe.onWindowLoaded(function()
        {
            var msgs = $$('.opc-message-container');
            if (msgs.length > 0)
            {
                msgs[0].addEventListener('DOMNodeInserted', function(evt) {
                    stripe.searchForAuthenticationRequiredError(function()
                    {
                        setTimeout(function()
                        {
                            $$('.opc-messages-action button')[0].click();
                        });
                        setTimeout(function()
                        {
                            IWD.OPC.isAuthenticationInProgress = true;

                            stripe.authenticateCustomer(function(err)
                            {
                                if (err)
                                    return stripe.displayCardError(err);

                                // We cannot use stripe.placeOrder with IWD
                                // stripe.placeOrder();
                                $$('#checkout-review-submit button')[0].click();
                            });
                        }, 10);
                    });
                }, false);
            }
        });

        stripe.oscInitialized = true;
    }
    // Magik OneStepCheckout v1.0.1
    else if (typeof MGKOSC != "undefined")
    {
        window.addEventListener("load", function()
        {
            var proceed = checkout.save.bind(checkout);

            stripe.placeOrder = function()
            {
                proceed();
            };

            checkout.save = function(element)
            {
                if (!stripe.isPaymentMethodSelected())
                    return stripe.placeOrder();

                createStripeToken(function(err)
                {
                    if (err)
                        stripe.displayCardError(err);
                    else
                        stripe.placeOrder();
                });
            };
            stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
            stripe.oscInitialized = true;
        });
    }
    // MageCloud Clarion OSC v1.0.2
    else if ($('onestepcheckout_orderform') && $$('.btn-checkout').length > 0)
    {
        var checkoutButton = $$('.btn-checkout').pop();
        stripe.placeOrder = function()
        {
            checkout.save();
        };
        checkoutButton.onclick = function(e)
        {
            e.preventDefault();

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };
        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    else if ($('onestep_form'))
    {
        // MageWorld OneStepCheckoutPro v3.4.4
        var initOSC = function()
        {
            OneStep.Views.Init.prototype._updateOrder = OneStep.Views.Init.prototype.updateOrder;
            OneStep.Views.Init.prototype.updateOrder = function()
            {
                var proceed = this._updateOrder.bind(this);

                stripe.placeOrder = function()
                {
                    proceed();
                };

                if (!stripe.isPaymentMethodSelected())
                    return stripe.placeOrder();

                var self = this;

                this.$el.find("#review-please-wait").show();
                window.OneStep.$('.btn-checkout').attr('disabled','disabled');

                createStripeToken(function(err)
                {
                    if (err)
                    {
                        self.$el.find("#review-please-wait").hide();
                        window.OneStep.$('.btn-checkout').removeAttr('disabled');
                        stripe.displayCardError(err);
                    }
                    else
                        stripe.placeOrder();
                });

            };
        };

        window.addEventListener("load", initOSC);
        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    // FancyCheckout 1.2.6
    else if ($('fancycheckout_orderform'))
    {
        var placeOrderButton = $$('button.btn-checkout')[0];
        if (!placeOrderButton)
            return;

        stripe.placeOrder = function()
        {
            billingForm.submit();
        };

        placeOrderButton.onclick = function(e)
        {
            if(!billingForm.validator.validate())
                return;

            jQuery('#control_overlay').show();
            jQuery('.opc_wrapper').css('opacity','0.5');

            e.preventDefault();

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                {
                    stripe.displayCardError(err);
                    jQuery('#control_overlay').hide();
                    jQuery('.opc_wrapper').css('opacity','1');
                }
                else
                    stripe.placeOrder();
            });
        };

        stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    else if ($('onestepcheckout-form') && !$('quickcheckout-ajax-loader'))
    {
        // MageBay OneStepCheckout 1.1.5
        // Idev OneStepCheckout 4.5.4
        var setLoading = function(flag)
        {
            if (typeof jQuery == 'undefined')
                return;

            var placeOrderButton = $('onestepcheckout-place-order');
            if (!placeOrderButton)
                return;

            var loading = jQuery('.onestepcheckout-place-order-loading');

            if (flag == true)
            {
                if (loading.length > 0)
                    loading.remove();

                /* Disable button to avoid multiple clicks */
                placeOrderButton.removeClassName('orange').addClassName('grey');
                placeOrderButton.disabled = true;

                var loaderelement = new Element('span').
                    addClassName('onestepcheckout-place-order-loading').
                    update('Please wait, processing your order...');

                placeOrderButton.parentNode.appendChild(loaderelement);
            }
            else
            {
                location.reload();

                if (loading.length > 0)
                    loading.remove();

                placeOrderButton.disabled = false;
            }
        }

        var initIdevOSC = function()
        {
            if (typeof $('onestepcheckout-form').proceed != 'undefined')
                return;

            stripe.placeOrder = function()
            {
                $('onestepcheckout-form').proceed();
            };

            $('onestepcheckout-form').proceed = $('onestepcheckout-form').submit;
            $('onestepcheckout-form').submit = function(e)
            {
                if (!stripe.isPaymentMethodSelected())
                    return stripe.placeOrder();

                setLoading(true);

                createStripeToken(function(err)
                {
                    if (err)
                    {
                        stripe.displayCardError(err);
                        setLoading(false);
                    }
                    else
                        stripe.placeOrder();
                });
            };

            // Idev OneStepCheckout 4.1.0
            if (typeof submitOsc != 'undefined' && typeof $('onestepcheckout-form')._submitOsc == 'undefined')
            {
                $('onestepcheckout-form')._submitOsc = submitOsc;
                submitOsc = function(form, url, message, image)
                {
                    stripe.placeOrder = function()
                    {
                        $('onestepcheckout-form')._submitOsc(form, url, message, image);
                    };

                    if (!stripe.isPaymentMethodSelected())
                        return stripe.placeOrder();

                    setLoading(true);

                    createStripeToken(function(err)
                    {
                        if (err)
                        {
                            stripe.displayCardError(err);
                            setLoading(false);
                        }
                        else
                            stripe.placeOrder();
                    });
                };
            }
        };

        // This is triggered when the billing address changes and the payment method is refreshed
        window.addEventListener("load", initIdevOSC);

        stripe.onWindowLoaded(function()
        {
            stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
        });

        stripe.oscInitialized = true;
    }
    else if (typeof AWOnestepcheckoutForm != 'undefined')
    {
        // AheadWorks OneStepCheckout 1.3.5
        AWOnestepcheckoutForm.prototype.__sendPlaceOrderRequest = AWOnestepcheckoutForm.prototype._sendPlaceOrderRequest;
        AWOnestepcheckoutForm.prototype._sendPlaceOrderRequest = function()
        {
            var self = this;

            stripe.placeOrder = function()
            {
                self.__sendPlaceOrderRequest();
            };

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                {
                    stripe.displayCardError(err);
                    try
                    {
                        self.enablePlaceOrderButton();
                        self.hidePleaseWaitNotice();
                        self.hideOverlay();
                    }
                    catch (e) {}
                }
                else
                    stripe.placeOrder();
            });
        };
        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    // NextBits OneStepCheckout 1.0.3
    else if (typeof checkoutnext != 'undefined' && typeof Review.prototype.proceed == 'undefined')
    {
        Review.prototype.proceed = Review.prototype.save;
        Review.prototype.save = function()
        {
            var self = this;

            stripe.placeOrder = function()
            {
                self.proceed();
            };

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        if (typeof review != 'undefined')
            review.save = Review.prototype.save;

        stripe.oscInitialized = true;
    }
    // Magecheckout OSC 2.2.1
    else if (typeof MagecheckoutSecuredCheckoutPaymentMethod != 'undefined')
    {
        MagecheckoutSecuredCheckoutForm.prototype._placeOrderProcess = MagecheckoutSecuredCheckoutForm.prototype.placeOrderProcess;
        MagecheckoutSecuredCheckoutForm.prototype.placeOrderProcess = function ()
        {
            var self = this;

            stripe.placeOrder = function()
            {
                self._placeOrderProcess();
            };

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        if (typeof securedCheckoutForm != 'undefined')
        {
            securedCheckoutForm._placeOrderProcess = MagecheckoutSecuredCheckoutForm.prototype._placeOrderProcess;
            securedCheckoutForm.placeOrderProcess = MagecheckoutSecuredCheckoutForm.prototype.placeOrderProcess;
        }
        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    // Lotusbreath OneStepCheckout 4.2.0
    else if (typeof oscObserver != 'undefined' && typeof oscObserver.register != 'undefined')
    {
        window.validToken = false;

        stripe.placeOrder = function()
        {
            $('lbonepage-place-order-btn').click();
        };

        oscObserver.register('beforeSubmitOrder', function()
        {
            if (!stripe.isPaymentMethodSelected())
                return;

            if (window.validToken)
                return;

            oscObserver.stopSubmittingOrder = true;

            createStripeToken(function(err)
            {
                oscObserver.stopSubmittingOrder = false;

                if (err)
                {
                    window.validToken = false;
                    stripe.displayCardError(err, true);
                }
                else
                {
                    window.validToken = true;
                    stripe.placeOrder();
                }
            });

        });

        stripe.onWindowLoaded(function()
        {
            oscObserver.register('afterLoadingNewContent', function()
            {
                // afterLoadingNewContent is called prematurely, allow some time for the DOM to update and the ajax requests to finish
                setTimeout(function(){
                    stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
                }, 600);
            });
        });

        stripe.oscInitialized = true;
    }
    // FireCheckout 3.2.0
    else if ($('firecheckout-form'))
    {
        var fireCheckoutPlaceOrder = function()
        {
            var self = this;

            if (!stripe.isPaymentMethodSelected())
                return self.proceed();

            if (typeof checkout != "undefined" && typeof checkout.validate != "undefined" && !checkout.validate())
                return;

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err, true);
                else
                    self.proceed();
            });
        };

        window.addEventListener("load", function()
        {
            var btnCheckout = document.getElementsByClassName('btn-checkout');
            if (btnCheckout && btnCheckout.length)
            {
                for (var i = 0; i < btnCheckout.length; i++)
                {
                    var button = btnCheckout[i];
                    button.proceed = button.onclick;
                    button.onclick = fireCheckoutPlaceOrder;

                    stripe.placeOrder = function()
                    {
                        button.proceed();
                    };
                }
            }
        });

        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);

        stripe.oscInitialized = true;
    }
    else if (typeof MagegiantOneStepCheckoutForm != 'undefined')
    {
        // MageGiant OneStepCheckout 4.0.0
        MagegiantOneStepCheckoutForm.prototype.__placeOrderRequest = MagegiantOneStepCheckoutForm.prototype._placeOrderRequest;
        MagegiantOneStepCheckoutForm.prototype._placeOrderRequest = function()
        {
            var self = this;

            stripe.placeOrder = function()
            {
                self.__placeOrderRequest();
            };

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        stripe.oscInitialized = true;
    }
    else if (typeof oscPlaceOrder != 'undefined')
    {
        // Magestore OneStepCheckout 3.5.0
        var proceed = oscPlaceOrder;

        oscPlaceOrder = function(element)
        {
            var form = $('one-step-checkout-form');
            var payment_method = $RF(form, 'payment[method]');
            if (payment_method != 'stripe_payments')
                return stripe.placeOrder();

            var validator = new Validation('one-step-checkout-form');

            if (validator.validate())
            {
                createStripeToken(function(err)
                {
                    if (err)
                        stripe.displayCardError(err);
                    else
                        stripe.placeOrder();
                });
            }
        };

        stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);

        stripe.placeOrder = function()
        {
            proceed(document.getElementById('onestepcheckout-button-place-order'));
        };

        stripe.oscInitialized = true;
    }
    // GoMage LightCheckout 5.9
    else if (typeof checkout != 'undefined' && typeof checkout.LightcheckoutSubmit != 'undefined')
    {
        checkout._LightcheckoutSubmit = checkout.LightcheckoutSubmit;

        stripe.placeOrder = function()
        {
            checkout._LightcheckoutSubmit();
        };

        checkout.LightcheckoutSubmit = function()
        {

            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                {
                    stripe.displayCardError(err);
                    checkout.showLoadinfo();
                    location.reload();
                }
                else
                    stripe.placeOrder();
            });
        };

        var triggerModal = null;

        document.getElementsByTagName("BODY")[0].addEventListener('DOMNodeInserted', function(evt)
        {
            if (triggerModal)
                clearTimeout(triggerModal);

            triggerModal = setTimeout(function()
            {
                stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
            }, 100);

        }, false);

        stripe.oscInitialized = true;
    }
    // Amasty OneStepCheckout 3.0.5
    else if ($('amscheckout-submit') && typeof completeCheckout != 'undefined')
    {
        stripe.placeOrder = function()
        {
            completeCheckout();
        };

        $('amscheckout-submit').onclick = function(el)
        {
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            showLoading();
            createStripeToken(function(err)
            {
                hideLoading();
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        document.getElementById('amasty-scheckout-messagebox').addEventListener('DOMNodeInserted', function(evt) {
            stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
        }, false);

        stripe.oscInitialized = true;
    }
    else if ((typeof Review != 'undefined' && typeof Review.prototype.proceed == 'undefined') && (
        // Magesolution Athlete Ultimate Magento Theme v1.1.2
        $('oscheckout-form') ||
        // PlumRocket OneStepCheckout 1.3.4
        ($('submit-chackout') && $('submit-chackout-top')) ||
        // Apptha 1StepCheckout v1.9
        (typeof closeLink1 != 'undefined')
    ))
    {
        Review.prototype.proceed = Review.prototype.save;

        stripe.placeOrder = function()
        {
            review.proceed();
        };

        Review.prototype.save = function()
        {
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        if (typeof review != 'undefined')
            review.save = Review.prototype.save;

        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
    }
    else if (typeof OSCheckout != 'undefined' && typeof OSCheckout.prototype.proceed == 'undefined')
    {
        // AdvancedCheckout OSC 2.5.0
        OSCheckout.prototype.proceed = OSCheckout.prototype.placeOrder;
        OSCheckout.prototype.placeOrder = function()
        {
            var self = this;

            stripe.placeOrder = function()
            {
                self.proceed();
            };

            // Payment is not defined
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        if (typeof oscheckout != 'undefined')
        {
            oscheckout.proceed = OSCheckout.prototype.proceed;
            oscheckout.placeOrder = OSCheckout.prototype.placeOrder;
        }
        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    // Aitoc OnePageCheckout v1.4.17
    else if ($('aitcheckout-place-order') && typeof AitMagentoReview != "undefined" && typeof AitMagentoReview.prototype.proceed != "undefined")
    {
        AitMagentoReview.prototype.proceed = AitMagentoReview.prototype.save;

        stripe.placeOrder = function()
        {
            review.proceed();
        };

        AitMagentoReview.prototype.save = function()
        {
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            var validator = new Validation(aitCheckout.getForm());
            if (validator && validator.validate())
            {
                createStripeToken(function(err)
                {
                    if (err)
                        stripe.displayCardError(err);
                    else
                        stripe.placeOrder();
                });
            }
            else
            {
                if (0 < Ajax.activeRequestCount)
                {
                    aitCheckout.valid = false;
                }
            }
        };

        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    // Magebees One Page Checkout v1.1.1
    else if ($$('.magebeesOscFull').length > 0 && typeof Review != 'undefined' && typeof Review.prototype.proceed == 'undefined')
    {
        Review.prototype.proceed = Review.prototype.submit;

        stripe.placeOrder = function()
        {
            review.proceed();
        };

        Review.prototype.submit = function()
        {
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            if (!checkout || !checkout.validateReview(true))
                return;

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        Event.stopObserving($('order_submit_button'));
        review.firsttimeinitialize();
    }
    // EcommerceTeam Tcheckout 1.0
    else if ($('tcheckout-form') && $('tcheckout-save-btn'))
    {
        $('tcheckout-form').proceed = $('tcheckout-form').submit;

        stripe.placeOrder = function()
        {
            $('tcheckout-form').proceed();
        };

        $('tcheckout-form').onsubmit = function(e)
        {
            if (!stripe.isPaymentMethodSelected())
                return true;

            e.preventDefault();

            createStripeToken(function(err)
            {
                if (err)
                {
                    $('tcheckout-please-wait').style.display = 'none';
                    $('tcheckout-save-btn').disabled = '';
                    $('tcheckout-save-btn').removeClassName('disabled');
                    stripe.displayCardError(err);
                }
                else
                    stripe.placeOrder();
            });
        };

        stripe.searchForAuthenticationRequiredError(stripe.triggerCustomerAuthentication);
        stripe.oscInitialized = true;
    }
    else if (typeof Review != 'undefined' && typeof Review.prototype.proceed == 'undefined')
    {
        // Default Magento Onepage checkout
        // Awesome Checkout 1.5.0
        // PlumRocket OSC 1.3.4
        // Other OSC modules

        /* The Awesome Checkout 1.5.0 configuration whitelist files are:
         *   stripe_payments/js/stripe_payments.js
         *   stripe_payments/js/cctype.js
         *   stripe_payments/css/styles.css
         *   prototype/window.js
         *   prototype/windows/themes/default.css
        */

        Review.prototype.proceed = Review.prototype.save;

        stripe.placeOrder = function()
        {
            // Awesome Checkout && PlumRocket
            checkout.loadWaiting = false;

            // Others
            review.proceed();
        };

        Review.prototype.save = function()
        {
            if (!stripe.isPaymentMethodSelected())
                return stripe.placeOrder();

            createStripeToken(function(err)
            {
                if (err)
                    stripe.displayCardError(err);
                else
                    stripe.placeOrder();
            });
        };

        if (typeof review != 'undefined')
            review.save = Review.prototype.save;

        stripe.initAlertProxy(stripe.triggerCustomerAuthentication);
    }
};



var cardTypes = {
    visa: new RegExp('^4'),
    mastercard: new RegExp('^5[1-5]'),
    amex: new RegExp('^3[47]'),
    discover: new RegExp('^6(?:011|5[0-9]{2})'),
    jcb: new RegExp('^(?:2131|1800|35[0-9]{3})'),
    diners: new RegExp('^3(?:0[0-5]|[68][0-9])')
};

function getCardType(cardNumber)
{
    for (var type in cardTypes)
        if (cardTypes.hasOwnProperty(type))
            if (cardTypes[type].test(cardNumber))
                return type;
}

var iconsContainer;

function resetIconsFade()
{
    iconsContainer.className = 'input-box';
    var children = iconsContainer.getElementsByTagName('img');
    for (var i = 0; i < children.length; i++)
        children[i].className = '';
}

var onCardNumberChangedFade = function(input)
{
    if (!iconsContainer) iconsContainer = document.getElementById('stripe-payments-accepted-cards');
    if (!iconsContainer) return;

    resetIconsFade();

    var cardNumber = input.value;
    if (!cardNumber || cardNumber.length === 0) return;

    var cardType = getCardType(cardNumber);
    if (!cardType) return;

    var img = document.getElementById('stripe_payments_' + cardType + '_type');
    if (!img) return;

    img.className = 'active';
    iconsContainer.className = 'input-box stripe-payments-detected';
};

function resetIconsSlide(input)
{
    input.className = input.className.replace(/ ?cctype-detected cctype-[a-z]+/, '');
}

var onCardNumberChangedSlide = function(input)
{
    var cardNumber = input.value;
    if (!cardNumber || cardNumber.length === 0) return resetIconsSlide(input);

    var cardType = getCardType(cardNumber);
    if (!cardType) return resetIconsSlide(input);

    var ccTypeClass = 'cctype-detected cctype-' + cardType;
    if (input.className.indexOf(ccTypeClass) > 0) return;

    resetIconsSlide(input);
    input.className = input.className + ' ' + ccTypeClass;
};

!function(t,n,i){var e=n.matchMedia;"undefined"!=typeof module&&module.exports?module.exports=i(e):"function"==typeof define&&define.amd?define(function(){return n[t]=i(e)}):n[t]=i(e)}("enquire",this,function(e){"use strict";function o(t,n){for(var i=0,e=t.length;i<e&&!1!==n(t[i],i);i++);}function i(t){(this.options=t).deferSetup||this.setup()}function r(t,n){this.query=t,this.isUnconditional=n,this.handlers=[],this.mql=e(t);var i=this;this.listener=function(t){i.mql=t,i.assess()},this.mql.addListener(this.listener)}function t(){if(!e)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!e("only all").matches}return i.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){this.initialised||this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(t){return this.options===t||this.options.match===t}},r.prototype={addHandler:function(t){var n=new i(t);this.handlers.push(n),this.matches()&&n.on()},removeHandler:function(i){var e=this.handlers;o(e,function(t,n){if(t.equals(i))return t.destroy(),!e.splice(n,1)})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){o(this.handlers,function(t){t.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var n=this.matches()?"on":"off";o(this.handlers,function(t){t[n]()})}},t.prototype={register:function(n,t,i){var e=this.queries,s=i&&this.browserIsIncapable;return e[n]||(e[n]=new r(n,s)),function(t){return"function"==typeof t}(t)&&(t={match:t}),function(t){return"[object Array]"===Object.prototype.toString.apply(t)}(t)||(t=[t]),o(t,function(t){e[n].addHandler(t)}),this},unregister:function(t,n){var i=this.queries[t];return i&&(n?i.removeHandler(n):(i.clear(),delete this.queries[t])),this}},new t});
!function(e){var t=function(c,D){"use strict";if(D.getElementsByClassName){var k,H,O=D.documentElement,d=c.Date,a=c.HTMLPictureElement,P="addEventListener",$="getAttribute",I=c[P],q=c.setTimeout,o=c.requestAnimationFrame||q,l=c.requestIdleCallback,U=/^picture$/i,i=["load","error","lazyincluded","_lazyloaded"],n={},j=Array.prototype.forEach,G=function(e,t){return n[t]||(n[t]=new RegExp("(\\s|^)"+t+"(\\s|$)")),n[t].test(e[$]("class")||"")&&n[t]},J=function(e,t){G(e,t)||e.setAttribute("class",(e[$]("class")||"").trim()+" "+t)},K=function(e,t){var n;(n=G(e,t))&&e.setAttribute("class",(e[$]("class")||"").replace(n," "))},Q=function(t,n,e){var a=e?P:"removeEventListener";e&&Q(t,n),i.forEach(function(e){t[a](e,n)})},V=function(e,t,n,a,i){var r=D.createEvent("Event");return n||(n={}),n.instance=k,r.initEvent(t,!a,!i),r.detail=n,e.dispatchEvent(r),r},X=function(e,t){var n;!a&&(n=c.picturefill||H.pf)?(t&&t.src&&!e[$]("srcset")&&e.setAttribute("srcset",t.src),n({reevaluate:!0,elements:[e]})):t&&t.src&&(e.src=t.src)},Y=function(e,t){return(getComputedStyle(e,null)||{})[t]},s=function(e,t,n){for(n=n||e.offsetWidth;n<H.minSize&&t&&!e._lazysizesWidth;)n=t.offsetWidth,t=t.parentNode;return n},Z=function(){var n,a,t=[],i=[],r=t,s=function(){var e=r;for(r=t.length?i:t,n=!0,a=!1;e.length;)e.shift()();n=!1},e=function(e,t){n&&!t?e.apply(this,arguments):(r.push(e),a||(a=!0,(D.hidden?q:o)(s)))};return e._lsFlush=s,e}(),ee=function(n,e){return e?function(){Z(n)}:function(){var e=this,t=arguments;Z(function(){n.apply(e,t)})}},te=function(e){var n,a=0,i=H.throttleDelay,r=H.ricTimeout,t=function(){n=!1,a=d.now(),e()},s=l&&r>49?function(){l(t,{timeout:r}),r!==H.ricTimeout&&(r=H.ricTimeout)}:ee(function(){q(t)},!0);return function(e){var t;(e=!0===e)&&(r=33),n||(n=!0,t=i-(d.now()-a),t<0&&(t=0),e||t<9?s():q(s,t))}},ne=function(e){var t,n,a=99,i=function(){t=null,e()},r=function(){var e=d.now()-n;e<a?q(r,a-e):(l||i)(i)};return function(){n=d.now(),t||(t=q(r,a))}};!function(){var e,t={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};H=c.lazySizesConfig||c.lazysizesConfig||{};for(e in t)e in H||(H[e]=t[e]);q(function(){H.init&&r()})}();var e=function(){var m,z,u,y,e,v,h,g,p,C,b,A,r=/^img$/i,f=/^iframe$/i,E="onscroll"in c&&!/(gle|ing)bot/.test(navigator.userAgent),_=0,M=0,N=0,w=-1,x=function(e){N--,(!e||N<0||!e.target)&&(N=0)},W=function(e){return null==A&&(A="hidden"==Y(D.body,"visibility")),A||"hidden"!=Y(e.parentNode,"visibility")&&"hidden"!=Y(e,"visibility")},L=function(e,t){var n,a=e,i=W(e);for(g-=t,b+=t,p-=t,C+=t;i&&(a=a.offsetParent)&&a!=D.body&&a!=O;)(i=(Y(a,"opacity")||1)>0)&&"visible"!=Y(a,"overflow")&&(n=a.getBoundingClientRect(),i=C>n.left&&p<n.right&&b>n.top-1&&g<n.bottom+1);return i},t=function(){var e,t,n,a,i,r,s,o,l,c,d,u,f=k.elements;if((y=H.loadMode)&&N<8&&(e=f.length)){for(t=0,w++;t<e;t++)if(f[t]&&!f[t]._lazyRace)if(!E||k.prematureUnveil&&k.prematureUnveil(f[t]))S(f[t]);else if((o=f[t][$]("data-expand"))&&(r=1*o)||(r=M),c||(c=!H.expand||H.expand<1?O.clientHeight>500&&O.clientWidth>500?500:370:H.expand,k._defEx=c,d=c*H.expFactor,u=H.hFac,A=null,M<d&&N<1&&w>2&&y>2&&!D.hidden?(M=d,w=0):M=y>1&&w>1&&N<6?c:_),l!==r&&(v=innerWidth+r*u,h=innerHeight+r,s=-1*r,l=r),n=f[t].getBoundingClientRect(),(b=n.bottom)>=s&&(g=n.top)<=h&&(C=n.right)>=s*u&&(p=n.left)<=v&&(b||C||p||g)&&(H.loadHidden||W(f[t]))&&(z&&N<3&&!o&&(y<3||w<4)||L(f[t],r))){if(S(f[t]),i=!0,N>9)break}else!i&&z&&!a&&N<4&&w<4&&y>2&&(m[0]||H.preloadAfterLoad)&&(m[0]||!o&&(b||C||p||g||"auto"!=f[t][$](H.sizesAttr)))&&(a=m[0]||f[t]);a&&!i&&S(a)}},n=te(t),T=function(e){var t=e.target;if(t._lazyCache)return void delete t._lazyCache;x(e),J(t,H.loadedClass),K(t,H.loadingClass),Q(t,B),V(t,"lazyloaded")},a=ee(T),B=function(e){a({target:e.target})},F=function(t,n){try{t.contentWindow.location.replace(n)}catch(e){t.src=n}},R=function(e){var t,n=e[$](H.srcsetAttr);(t=H.customMedia[e[$]("data-media")||e[$]("media")])&&e.setAttribute("media",t),n&&e.setAttribute("srcset",n)},s=ee(function(t,e,n,a,i){var r,s,o,l,c,d;(c=V(t,"lazybeforeunveil",e)).defaultPrevented||(a&&(n?J(t,H.autosizesClass):t.setAttribute("sizes",a)),s=t[$](H.srcsetAttr),r=t[$](H.srcAttr),i&&(o=t.parentNode,l=o&&U.test(o.nodeName||"")),d=e.firesLoad||"src"in t&&(s||r||l),c={target:t},J(t,H.loadingClass),d&&(clearTimeout(u),u=q(x,2500),Q(t,B,!0)),l&&j.call(o.getElementsByTagName("source"),R),s?t.setAttribute("srcset",s):r&&!l&&(f.test(t.nodeName)?F(t,r):t.src=r),i&&(s||l)&&X(t,{src:r})),t._lazyRace&&delete t._lazyRace,K(t,H.lazyClass),Z(function(){var e=t.complete&&t.naturalWidth>1;d&&!e||(e&&J(t,"ls-is-cached"),T(c),t._lazyCache=!0,q(function(){"_lazyCache"in t&&delete t._lazyCache},9)),"lazy"==t.loading&&N--},!0)}),S=function(e){if(!e._lazyRace){var t,n=r.test(e.nodeName),a=n&&(e[$](H.sizesAttr)||e[$]("sizes")),i="auto"==a;(!i&&z||!n||!e[$]("src")&&!e.srcset||e.complete||G(e,H.errorClass)||!G(e,H.lazyClass))&&(t=V(e,"lazyunveilread").detail,i&&ae.updateElem(e,!0,e.offsetWidth),e._lazyRace=!0,N++,s(e,t,i,a,n))}},i=ne(function(){H.loadMode=3,n()}),o=function(){3==H.loadMode&&(H.loadMode=2),i()},l=function(){if(!z){if(d.now()-e<999)return void q(l,999);z=!0,H.loadMode=3,n(),I("scroll",o,!0)}};return{_:function(){e=d.now(),k.elements=D.getElementsByClassName(H.lazyClass),m=D.getElementsByClassName(H.lazyClass+" "+H.preloadClass),I("scroll",n,!0),I("resize",n,!0),c.MutationObserver?new MutationObserver(n).observe(O,{childList:!0,subtree:!0,attributes:!0}):(O[P]("DOMNodeInserted",n,!0),O[P]("DOMAttrModified",n,!0),setInterval(n,999)),I("hashchange",n,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(e){D[P](e,n,!0)}),/d$|^c/.test(D.readyState)?l():(I("load",l),D[P]("DOMContentLoaded",n),q(l,2e4)),k.elements.length?(t(),Z._lsFlush()):n()},checkElems:n,unveil:S,_aLSL:o}}(),ae=function(){var n,r=ee(function(e,t,n,a){var i,r,s;if(e._lazysizesWidth=a,a+="px",e.setAttribute("sizes",a),U.test(t.nodeName||""))for(i=t.getElementsByTagName("source"),r=0,s=i.length;r<s;r++)i[r].setAttribute("sizes",a);n.detail.dataAttr||X(e,n.detail)}),a=function(e,t,n){var a,i=e.parentNode;i&&(n=s(e,i,n),a=V(e,"lazybeforesizes",{width:n,dataAttr:!!t}),a.defaultPrevented||(n=a.detail.width)&&n!==e._lazysizesWidth&&r(e,i,a,n))},e=function(){var e,t=n.length;if(t)for(e=0;e<t;e++)a(n[e])},t=ne(e);return{_:function(){n=D.getElementsByClassName(H.autosizesClass),I("resize",t)},checkElems:t,updateElem:a}}(),r=function(){r.i||(r.i=!0,ae._(),e._())};return k={cfg:H,autoSizer:ae,loader:e,init:r,uP:X,aC:J,rC:K,hC:G,fire:V,gW:s,rAF:Z}}}(e,e.document);e.lazySizes=t,"object"==typeof module&&module.exports&&(module.exports=t)}(window);
"use strict";var ENotificationType;!function(t){t[t.Success=0]="Success",t[t.Info=1]="Info",t[t.Warning=2]="Warning",t[t.Error=3]="Error"}(ENotificationType=ENotificationType||{});var NotificationCenter=function(){function n(){}return n.notify=function(t){var e,i=t.fadeOutMilisecs?t.fadeOutMilisecs:5e3;switch(t.type){case ENotificationType.Success:n._successNode||(n._successNode=jQuery(n._notificationTemplate).insertAfter("body").addClass("success-msg")),e=n._successNode;break;case ENotificationType.Error:n._errorNode||(n._errorNode=jQuery(n._notificationTemplate).insertAfter("body").addClass("error-msg")),e=n._errorNode}e.find(".notification-center-msg__txt").text(t.message),e.show(),e.find(".notification-center-msg__btn-close").on("click",function(){e.stop().fadeOut()}),i&&e.delay(i).fadeOut()},n._notificationTemplate='<div class="notification-center-msg">\n                                                <span class="notification-center-msg__txt"></span> \n                                                <button class="notification-center-msg__btn-close" type="button">\n                                                    <i class="icon-close"></i>\n                                                </button>\n                                            </div>',n}();
"use strict";var MiniCart=function(){function e(){var a=this;jQuery(document).ready(function(){var e=EventManager.getInstance();e.subscribe(EmmaEventName.DISCOUNT_COUPON_APPLIED,a),e.subscribe(EmmaEventName.DISCOUNT_BEFORE_COUPON_APPLIED,a),e.subscribe(EmmaEventName.MINICART_HTML_UPDATED,a),e.subscribe(EmmaEventName.UPSELLS__PRODUCT_ADDED,a)})}return e.prototype.onEvent=function(e){switch(e.name){case EmmaEventName.DISCOUNT_BEFORE_COUPON_APPLIED:if(!jQuery("#cart.is-open").length)return;this._preloader=new Preloader({container:"#cart.is-open"}),this._preloader.show();break;case EmmaEventName.DISCOUNT_COUPON_APPLIED:case EmmaEventName.UPSELLS__PRODUCT_ADDED:e.payload.minicart_content?this.reloadHtml(e.payload.minicart_content):this.reload();break;case EmmaEventName.MINICART_HTML_UPDATED:if(!e.payload)return;window.aplazameInstallmentsCart&&aplazameInstallmentsCart.formatPrice(e.payload);var a=Math.trunc(100*e.payload);jQuery("#aplazame-rate-calculator").attr("data-amount",a);var t=new Foundation.Reveal(jQuery("#aplazame-rate-calc-modal"));jQuery(".aplazame-rate-calc__cta").click(function(){t.open()})}},e.prototype.reload=function(){var t=this;this._preloader=new Preloader({container:"#cart.is-open"}),this._preloader.show(),jQuery.get(getUrl("")+"emma/checkout_cart/reloadMinicart/",function(e){var a=JSON.parse(e);registry("mini_cart",a.minicart_content,!1),jQuery("#cart").length&&jQuery("#cart").html(a.minicart_content),t._preloader&&t._preloader.hide()})},e.prototype.reloadHtml=function(e){e&&(this._preloader=new Preloader({container:"#cart.is-open"}),this._preloader.show(),registry("mini_cart",e,!1),jQuery("#cart").length&&jQuery("#cart").html(e),this._preloader&&this._preloader.hide())},e}();new MiniCart;
"use strict";var EmmaEventName=function(){function _(){}return _.DISCOUNT_COUPON_APPLIED="DISCOUNT_COUPON_APPLIED",_.DISCOUNT_BEFORE_COUPON_APPLIED="DISCOUNT_BEFORE_COUPON_APPLIED",_.FORTUNE_WHEEL_OPENED="FORTUNE_WHEEL_OPENED",_.FORTUNE_WHEEL_CLOSED="FORTUNE_WHEEL_CLOSED",_.CONFIGURABLE_PRODUCT__EXT_SHOP_CHANGED="CONFIGURABLE_PRODUCT__EXT_SHOP_CHANGED",_.MINICART_HTML_UPDATED="MINICART_HTML_UPDATED",_.PRODUCT_PRICING_CHANGED="PRODUCT_PRICING_CHANGED",_.PRODUCT_PAGE___HARDNESS_CHANGED="PRODUCT_PAGE___HARDNESS_SC_CHANGED",_.PRODUCT_PAGE___DYNAMIC_BEDBOX_BASE_CHANGED="PRODUCT_PAGE___DYNAMIC_BEDBOX_BASE_CHANGED",_.PRODUCT_PAGE___ATTRIBUTE_GROUP_READY="PRODUCT_PAGE___ATTRIBUTE_GROUP_READY",_.BOXBED_V3_COMPONENT_LOADED="BOXBED_V3_COMPONENT_LOADED",_.BOXBED_V3_DEPENDENT_SELECTIONS_READY="BOXBED_V3_DEPENDENT_SELECTIONS_READY",_.BOXBED_V3_OPTIONS_UPDATE="BOXBED_V3_OPTIONS_UPDATE",_.UPSELLS__PRODUCT_ADDED="UPSELLS__PRODUCT_ADDED",_}(),EventManager=function(){function _(){this._subscribers={}}return _.getInstance=function(){return _._eventManagerInstance||(_._eventManagerInstance=new _),_._eventManagerInstance},_.prototype.subscribe=function(_,E){this._subscribers[_]||(this._subscribers[_]=[]),this._subscribers[_].push(E)},_.prototype.unsubscribe=function(_,E){},_.prototype.notify=function(_){if(this._subscribers[_.name]){for(var E=[],D=0,O=this._subscribers[_.name];D<O.length;D++){var P=O[D];E.push(P.onEvent(_))}return E}},_}();
var TWO_THREE_ISO_COUNTRY_CODE={BD:"BGD",BE:"BEL",BF:"BFA",BG:"BGR",BA:"BIH",BB:"BRB",WF:"WLF",BL:"BLM",BM:"BMU",BN:"BRN",BO:"BOL",BH:"BHR",BI:"BDI",BJ:"BEN",BT:"BTN",JM:"JAM",BV:"BVT",BW:"BWA",WS:"WSM",BQ:"BES",BR:"BRA",BS:"BHS",JE:"JEY",BY:"BLR",BZ:"BLZ",RU:"RUS",RW:"RWA",RS:"SRB",TL:"TLS",RE:"REU",TM:"TKM",TJ:"TJK",RO:"ROU",TK:"TKL",GW:"GNB",GU:"GUM",GT:"GTM",GS:"SGS",GR:"GRC",GQ:"GNQ",GP:"GLP",JP:"JPN",GY:"GUY",GG:"GGY",GF:"GUF",GE:"GEO",GD:"GRD",GB:"GBR",GA:"GAB",SV:"SLV",GN:"GIN",GM:"GMB",GL:"GRL",GI:"GIB",GH:"GHA",OM:"OMN",TN:"TUN",JO:"JOR",HR:"HRV",HT:"HTI",HU:"HUN",HK:"HKG",HN:"HND",HM:"HMD",VE:"VEN",PR:"PRI",PS:"PSE",PW:"PLW",PT:"PRT",SJ:"SJM",PY:"PRY",IQ:"IRQ",PA:"PAN",PF:"PYF",PG:"PNG",PE:"PER",PK:"PAK",PH:"PHL",PN:"PCN",PL:"POL",PM:"SPM",ZM:"ZMB",EH:"ESH",EE:"EST",EG:"EGY",ZA:"ZAF",EC:"ECU",IT:"ITA",VN:"VNM",SB:"SLB",ET:"ETH",SO:"SOM",ZW:"ZWE",SA:"SAU",ES:"ESP",ER:"ERI",ME:"MNE",MD:"MDA",MG:"MDG",MF:"MAF",MA:"MAR",MC:"MCO",UZ:"UZB",MM:"MMR",ML:"MLI",MO:"MAC",MN:"MNG",MH:"MHL",MK:"MKD",MU:"MUS",MT:"MLT",MW:"MWI",MV:"MDV",MQ:"MTQ",MP:"MNP",MS:"MSR",MR:"MRT",IM:"IMN",UG:"UGA",TZ:"TZA",MY:"MYS",MX:"MEX",IL:"ISR",FR:"FRA",IO:"IOT",SH:"SHN",FI:"FIN",FJ:"FJI",FK:"FLK",FM:"FSM",FO:"FRO",NI:"NIC",NL:"NLD",NO:"NOR",NA:"NAM",VU:"VUT",NC:"NCL",NE:"NER",NF:"NFK",NG:"NGA",NZ:"NZL",NP:"NPL",NR:"NRU",NU:"NIU",CK:"COK",XK:"XKX",CI:"CIV",CH:"CHE",CO:"COL",CN:"CHN",CM:"CMR",CL:"CHL",CC:"CCK",CA:"CAN",CG:"COG",CF:"CAF",CD:"COD",CZ:"CZE",CY:"CYP",CX:"CXR",CR:"CRI",CW:"CUW",CV:"CPV",CU:"CUB",SZ:"SWZ",SY:"SYR",SX:"SXM",KG:"KGZ",KE:"KEN",SS:"SSD",SR:"SUR",KI:"KIR",KH:"KHM",KN:"KNA",KM:"COM",ST:"STP",SK:"SVK",KR:"KOR",SI:"SVN",KP:"PRK",KW:"KWT",SN:"SEN",SM:"SMR",SL:"SLE",SC:"SYC",KZ:"KAZ",KY:"CYM",SG:"SGP",SE:"SWE",SD:"SDN",DO:"DOM",DM:"DMA",DJ:"DJI",DK:"DNK",VG:"VGB",DE:"DEU",YE:"YEM",DZ:"DZA",US:"USA",UY:"URY",YT:"MYT",UM:"UMI",LB:"LBN",LC:"LCA",LA:"LAO",TV:"TUV",TW:"TWN",TT:"TTO",TR:"TUR",LK:"LKA",LI:"LIE",LV:"LVA",TO:"TON",LT:"LTU",LU:"LUX",LR:"LBR",LS:"LSO",TH:"THA",TF:"ATF",TG:"TGO",TD:"TCD",TC:"TCA",LY:"LBY",VA:"VAT",VC:"VCT",AE:"ARE",AD:"AND",AG:"ATG",AF:"AFG",AI:"AIA",VI:"VIR",IS:"ISL",IR:"IRN",AM:"ARM",AL:"ALB",AO:"AGO",AQ:"ATA",AS:"ASM",AR:"ARG",AU:"AUS",AT:"AUT",AW:"ABW",IN:"IND",AX:"ALA",AZ:"AZE",IE:"IRL",ID:"IDN",UA:"UKR",QA:"QAT",MZ:"MOZ"};
var TELEPHONE_MASK={fr:[{mask:"00 00 00 00 0"}],br:[],in:[]};
"use strict";var HereMapApiKeys=function(){function e(){}return e.getApiKey=function(){return-1!==e._devNTestingDomains.indexOf(window.location.hostname)?e._devNTestingApiKey:e._liveApiKey},e._liveApiKey="89jQfbTaPss4HbLpghARPZY9eM67GZF3TqZ1xUtsIrw",e._devNTestingApiKey="YIUukEYLNTgMZSvAbl4vXGEipwSORJy8PGaDFIo4zWU",e._devNTestingDomains=["deployment.emma.fr","deployment.emma-matratze.de","deployment.emma-colchon.es","deployment.emma-materasso.it"],e}();
"use strict";var DiscountBanner=function(){function t(){this.applyDiscountCodeAutomatically(),this.fetchDiscountBannerHtml()}return t.applyDiscountCode=function(e,t){void 0===t&&(t=!1);var n=EventManager.getInstance().notify({name:EmmaEventName.DISCOUNT_BEFORE_COUPON_APPLIED,payload:e});if(n)for(var o=0,a=n;o<a.length;o++){var r=a[o];if(r&&r.cancelFurtherAction)return}jQuery.post(getUrl("")+"emma/checkout_cart/ajaxCouponPost",{coupon_code:e}).done(function(e){var n=e;(EventManager.getInstance().notify({name:EmmaEventName.DISCOUNT_COUPON_APPLIED,payload:{minicart_content:n.content}}),n.message)?jQuery("#black-friday-modal").length&&t?(new Foundation.Reveal(jQuery("#black-friday-modal")).open(),registry("couponApplied","true")):NotificationCenter.notify({message:n.message,type:ENotificationType.Success}):NotificationCenter.notify({message:n.error,type:ENotificationType.Error})})},t.prototype.applyDiscountCodeAutomatically=function(){var e=/utm_code=([^&#=]*)/.exec(window.location.search),n=e&&e[1];n&&t.applyDiscountCode(n.toString())},t.prototype.fetchDiscountBannerHtml=function(){window.addEventListener("load",function(){var n="cb_storage";if("undefined"!=jsUrls.storeCode&&(n="cb_storage_"+jsUrls.storeCode),0!==parseInt(getCookie("display_coupon_banner"))&&!t.loadDiscountBanner(n)){var e=getUrl("bettzeit_couponBanner/couponBanner/content/");null!==/#t5/.exec(window.location.hash)&&(e+="?t5=true"),jQuery.get({url:e,success:function(e){(e=JSON.parse(e)).html&&(registry(n,e,!1),t.loadDiscountBanner(n))}})}})},t.loadDiscountBanner=function(e){var n=Date.now(),t=registry(e);return!!t&&(t.expire<n?(registry(e,null,!1),!1):("new"==t.type&&parseInt(getCookie("pnc_timestamp"))<n||(t.html&&(jQuery("#discount-banner-wrapper").append(t.html),jQuery(".checkout-header").after(t.html),jQuery("#coupon_banner_tooltip").length&&new Foundation.Tooltip(jQuery("#coupon_banner_tooltip"))),widgetBadgesAnimation(".sticky-container .header","slider-header"),jQuery(document).ready(function(){setTimeout(function(){var e=jQuery(".discount-banner");0!=e.length&&e.addClass("shown")},2e3)})),!0))},t}();new DiscountBanner;
function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}
function partnerSetCookie(value) {
    var date = new Date();
    date.setTime(date.getTime() + (40*24*60*60*1000));
    var expires = "; expires=" + date.toUTCString();
    document.cookie = "partner=" + (value || "")  + expires + "; path=/";
}
function partnerGetCookie() {
    var nameEQ = "partner=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
(function(){
    var partnerCookie = partnerGetCookie(),
        pacid = findGetParameter('pacid'),
        partnerId = findGetParameter('pa-partnerid');
    if ((typeof partnerCookie === 'undefined' || partnerCookie === null) &&
        (typeof pacid === 'string' || typeof pacid === 'number') &&
        (typeof partnerId === 'string' || typeof partnerId === 'number')
    ) {
        partnerSetCookie(btoa(partnerId + '&' + pacid));
    }
})();

!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(a){"use strict";var s,r=window.Slick||{};(s=0,r=function(i,e){var t,o=this;o.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:a(i),appendDots:a(i),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(i,e){return a('<button type="button" />').text(e+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},o.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},a.extend(o,o.initials),o.activeBreakpoint=null,o.animType=null,o.animProp=null,o.breakpoints=[],o.breakpointSettings=[],o.cssTransitions=!1,o.focussed=!1,o.interrupted=!1,o.hidden="hidden",o.paused=!0,o.positionProp=null,o.respondTo=null,o.rowCount=1,o.shouldClick=!0,o.$slider=a(i),o.$slidesCache=null,o.transformType=null,o.transitionType=null,o.visibilityChange="visibilitychange",o.windowWidth=0,o.windowTimer=null,t=a(i).data("slick")||{},o.options=a.extend({},o.defaults,e,t),o.currentSlide=o.options.initialSlide,o.originalSettings=o.options,void 0!==document.mozHidden?(o.hidden="mozHidden",o.visibilityChange="mozvisibilitychange"):void 0!==document.webkitHidden&&(o.hidden="webkitHidden",o.visibilityChange="webkitvisibilitychange"),o.autoPlay=a.proxy(o.autoPlay,o),o.autoPlayClear=a.proxy(o.autoPlayClear,o),o.autoPlayIterator=a.proxy(o.autoPlayIterator,o),o.changeSlide=a.proxy(o.changeSlide,o),o.clickHandler=a.proxy(o.clickHandler,o),o.selectHandler=a.proxy(o.selectHandler,o),o.setPosition=a.proxy(o.setPosition,o),o.swipeHandler=a.proxy(o.swipeHandler,o),o.dragHandler=a.proxy(o.dragHandler,o),o.keyHandler=a.proxy(o.keyHandler,o),o.instanceUid=s++,o.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,o.registerBreakpoints(),o.init(!0)}).prototype.activateADA=function(){this.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},r.prototype.addSlide=r.prototype.slickAdd=function(i,e,t){var o=this;if("boolean"==typeof e)t=e,e=null;else if(e<0||e>=o.slideCount)return!1;o.unload(),"number"==typeof e?0===e&&0===o.$slides.length?a(i).appendTo(o.$slideTrack):t?a(i).insertBefore(o.$slides.eq(e)):a(i).insertAfter(o.$slides.eq(e)):!0===t?a(i).prependTo(o.$slideTrack):a(i).appendTo(o.$slideTrack),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slides.each(function(i,e){a(e).attr("data-slick-index",i)}),o.$slidesCache=o.$slides,o.reinit()},r.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},r.prototype.animateSlide=function(i,e){var t={},o=this;o.animateHeight(),!0===o.options.rtl&&!1===o.options.vertical&&(i=-i),!1===o.transformsEnabled?!1===o.options.vertical?o.$slideTrack.animate({left:i},o.options.speed,o.options.easing,e):o.$slideTrack.animate({top:i},o.options.speed,o.options.easing,e):!1===o.cssTransitions?(!0===o.options.rtl&&(o.currentLeft=-o.currentLeft),a({animStart:o.currentLeft}).animate({animStart:i},{duration:o.options.speed,easing:o.options.easing,step:function(i){i=Math.ceil(i),!1===o.options.vertical?t[o.animType]="translate("+i+"px, 0px)":t[o.animType]="translate(0px,"+i+"px)",o.$slideTrack.css(t)},complete:function(){e&&e.call()}})):(o.applyTransition(),i=Math.ceil(i),!1===o.options.vertical?t[o.animType]="translate3d("+i+"px, 0px, 0px)":t[o.animType]="translate3d(0px,"+i+"px, 0px)",o.$slideTrack.css(t),e&&setTimeout(function(){o.disableTransition(),e.call()},o.options.speed))},r.prototype.getNavTarget=function(){var i=this.options.asNavFor;return i&&null!==i&&(i=a(i).not(this.$slider)),i},r.prototype.asNavFor=function(e){var i=this.getNavTarget();null!==i&&"object"==typeof i&&i.each(function(){var i=a(this).slick("getSlick");i.unslicked||i.slideHandler(e,!0)})},r.prototype.applyTransition=function(i){var e=this,t={};!1===e.options.fade?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},r.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},r.prototype.autoPlayClear=function(){this.autoPlayTimer&&clearInterval(this.autoPlayTimer)},r.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(!1===i.options.infinite&&(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))},r.prototype.buildArrows=function(){var i=this;!0===i.options.arrows&&(i.$prevArrow=a(i.options.prevArrow).addClass("slick-arrow"),i.$nextArrow=a(i.options.nextArrow).addClass("slick-arrow"),i.slideCount>i.options.slidesToShow?(i.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),i.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),i.htmlExpr.test(i.options.prevArrow)&&i.$prevArrow.prependTo(i.options.appendArrows),i.htmlExpr.test(i.options.nextArrow)&&i.$nextArrow.appendTo(i.options.appendArrows),!0!==i.options.infinite&&i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):i.$prevArrow.add(i.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},r.prototype.buildDots=function(){var i,e,t=this;if(!0===t.options.dots){for(t.$slider.addClass("slick-dotted"),e=a("<ul />").addClass(t.options.dotsClass),i=0;i<=t.getDotCount();i+=1)e.append(a("<li />").append(t.options.customPaging.call(this,t,i)));t.$dots=e.appendTo(t.options.appendDots),t.$dots.find("li").first().addClass("slick-active")}},r.prototype.buildOut=function(){var i=this;i.$slides=i.$slider.children(i.options.slide+":not(.slick-cloned)").addClass("slick-slide"),i.slideCount=i.$slides.length,i.$slides.each(function(i,e){a(e).attr("data-slick-index",i).data("originalStyling",a(e).attr("style")||"")}),i.$slider.addClass("slick-slider"),i.$slideTrack=0===i.slideCount?a('<div class="slick-track"/>').appendTo(i.$slider):i.$slides.wrapAll('<div class="slick-track"/>').parent(),i.$list=i.$slideTrack.wrap('<div class="slick-list"/>').parent(),i.$slideTrack.css("opacity",0),!0!==i.options.centerMode&&!0!==i.options.swipeToSlide||(i.options.slidesToScroll=1),a("img[data-lazy]",i.$slider).not("[src]").addClass("slick-loading"),i.setupInfinite(),i.buildArrows(),i.buildDots(),i.updateDots(),i.setSlideClasses("number"==typeof i.currentSlide?i.currentSlide:0),!0===i.options.draggable&&i.$list.addClass("draggable")},r.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),1<l.options.rows){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"})}},r.prototype.checkResponsive=function(i,e){var t,o,s,n=this,r=!1,l=n.$slider.width(),d=window.innerWidth||a(window).width();if("window"===n.respondTo?s=d:"slider"===n.respondTo?s=l:"min"===n.respondTo&&(s=Math.min(d,l)),n.options.responsive&&n.options.responsive.length&&null!==n.options.responsive){for(t in o=null,n.breakpoints)n.breakpoints.hasOwnProperty(t)&&(!1===n.originalSettings.mobileFirst?s<n.breakpoints[t]&&(o=n.breakpoints[t]):s>n.breakpoints[t]&&(o=n.breakpoints[t]));null!==o?null!==n.activeBreakpoint?o===n.activeBreakpoint&&!e||(n.activeBreakpoint=o,"unslick"===n.breakpointSettings[o]?n.unslick(o):(n.options=a.extend({},n.originalSettings,n.breakpointSettings[o]),!0===i&&(n.currentSlide=n.options.initialSlide),n.refresh(i)),r=o):(n.activeBreakpoint=o,"unslick"===n.breakpointSettings[o]?n.unslick(o):(n.options=a.extend({},n.originalSettings,n.breakpointSettings[o]),!0===i&&(n.currentSlide=n.options.initialSlide),n.refresh(i)),r=o):null!==n.activeBreakpoint&&(n.activeBreakpoint=null,n.options=n.originalSettings,!0===i&&(n.currentSlide=n.options.initialSlide),n.refresh(i),r=o),i||!1===r||n.$slider.trigger("breakpoint",[n,r])}},r.prototype.changeSlide=function(i,e){var t,o,s=this,n=a(i.currentTarget);switch(n.is("a")&&i.preventDefault(),n.is("li")||(n=n.closest("li")),t=s.slideCount%s.options.slidesToScroll!=0?0:(s.slideCount-s.currentSlide)%s.options.slidesToScroll,i.data.message){case"previous":o=0==t?s.options.slidesToScroll:s.options.slidesToShow-t,s.slideCount>s.options.slidesToShow&&s.slideHandler(s.currentSlide-o,!1,e);break;case"next":o=0==t?s.options.slidesToScroll:t,s.slideCount>s.options.slidesToShow&&s.slideHandler(s.currentSlide+o,!1,e);break;case"index":var r=0===i.data.index?0:i.data.index||n.index()*s.options.slidesToScroll;s.slideHandler(s.checkNavigable(r),!1,e),n.children().trigger("focus");break;default:return}},r.prototype.checkNavigable=function(i){var e,t;if(t=0,i>(e=this.getNavigableIndexes())[e.length-1])i=e[e.length-1];else for(var o in e){if(i<e[o]){i=t;break}t=e[o]}return i},r.prototype.cleanUpEvents=function(){var i=this;i.options.dots&&null!==i.$dots&&(a("li",i.$dots).off("click.slick",i.changeSlide).off("mouseenter.slick",a.proxy(i.interrupt,i,!0)).off("mouseleave.slick",a.proxy(i.interrupt,i,!1)),!0===i.options.accessibility&&i.$dots.off("keydown.slick",i.keyHandler)),i.$slider.off("focus.slick blur.slick"),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow&&i.$prevArrow.off("click.slick",i.changeSlide),i.$nextArrow&&i.$nextArrow.off("click.slick",i.changeSlide),!0===i.options.accessibility&&(i.$prevArrow&&i.$prevArrow.off("keydown.slick",i.keyHandler),i.$nextArrow&&i.$nextArrow.off("keydown.slick",i.keyHandler))),i.$list.off("touchstart.slick mousedown.slick",i.swipeHandler),i.$list.off("touchmove.slick mousemove.slick",i.swipeHandler),i.$list.off("touchend.slick mouseup.slick",i.swipeHandler),i.$list.off("touchcancel.slick mouseleave.slick",i.swipeHandler),i.$list.off("click.slick",i.clickHandler),a(document).off(i.visibilityChange,i.visibility),i.cleanUpSlideEvents(),!0===i.options.accessibility&&i.$list.off("keydown.slick",i.keyHandler),!0===i.options.focusOnSelect&&a(i.$slideTrack).children().off("click.slick",i.selectHandler),a(window).off("orientationchange.slick.slick-"+i.instanceUid,i.orientationChange),a(window).off("resize.slick.slick-"+i.instanceUid,i.resize),a("[draggable!=true]",i.$slideTrack).off("dragstart",i.preventDefault),a(window).off("load.slick.slick-"+i.instanceUid,i.setPosition)},r.prototype.cleanUpSlideEvents=function(){var i=this;i.$list.off("mouseenter.slick",a.proxy(i.interrupt,i,!0)),i.$list.off("mouseleave.slick",a.proxy(i.interrupt,i,!1))},r.prototype.cleanUpRows=function(){var i;1<this.options.rows&&((i=this.$slides.children().children()).removeAttr("style"),this.$slider.empty().append(i))},r.prototype.clickHandler=function(i){!1===this.shouldClick&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},r.prototype.destroy=function(i){var e=this;e.autoPlayClear(),e.touchObject={},e.cleanUpEvents(),a(".slick-cloned",e.$slider).detach(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.$prevArrow.length&&(e.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove()),e.$nextArrow&&e.$nextArrow.length&&(e.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove()),e.$slides&&(e.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){a(this).attr("style",a(this).data("originalStyling"))}),e.$slideTrack.children(this.options.slide).detach(),e.$slideTrack.detach(),e.$list.detach(),e.$slider.append(e.$slides)),e.cleanUpRows(),e.$slider.removeClass("slick-slider"),e.$slider.removeClass("slick-initialized"),e.$slider.removeClass("slick-dotted"),e.unslicked=!0,i||e.$slider.trigger("destroy",[e])},r.prototype.disableTransition=function(i){var e={};e[this.transitionType]="",!1===this.options.fade?this.$slideTrack.css(e):this.$slides.eq(i).css(e)},r.prototype.fadeSlide=function(i,e){var t=this;!1===t.cssTransitions?(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))},r.prototype.fadeSlideOut=function(i){var e=this;!1===e.cssTransitions?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}))},r.prototype.filterSlides=r.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())},r.prototype.focusHandler=function(){var t=this;t.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(i){i.stopImmediatePropagation();var e=a(this);setTimeout(function(){t.options.pauseOnFocus&&(t.focussed=e.is(":focus"),t.autoPlay())},0)})},r.prototype.getCurrent=r.prototype.slickCurrentSlide=function(){return this.currentSlide},r.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(!0===i.options.infinite)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(!0===i.options.centerMode)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},r.prototype.getLeft=function(i){var e,t,o,s,n=this,r=0;return n.slideOffset=0,t=n.$slides.first().outerHeight(!0),!0===n.options.infinite?(n.slideCount>n.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,!0===n.options.vertical&&!0===n.options.centerMode&&(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&&(r=i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,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&&(r=n.slideOffset=0),!0===n.options.centerMode&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:!0===n.options.centerMode&&!0===n.options.infinite?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:!0===n.options.centerMode&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=!1===n.options.vertical?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,!0===n.options.variableWidth&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,!0===n.options.centerMode&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(n.$list.width()-o.outerWidth())/2)),e},r.prototype.getOption=r.prototype.slickGetOption=function(i){return this.options[i]},r.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(i=!1===e.options.infinite?e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,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},r.prototype.getSlick=function(){return this},r.prototype.getSlideCount=function(){var t,o,s=this;return o=!0===s.options.centerMode?s.slideWidth*Math.floor(s.options.slidesToShow/2):0,!0===s.options.swipeToSlide?(s.$slideTrack.find(".slick-slide").each(function(i,e){if(e.offsetLeft-o+a(e).outerWidth()/2>-1*s.swipeLeft)return t=e,!1}),Math.abs(a(t).attr("data-slick-index")-s.currentSlide)||1):s.options.slidesToScroll},r.prototype.goTo=r.prototype.slickGoTo=function(i,e){this.changeSlide({data:{message:"index",index:parseInt(i)}},e)},r.prototype.init=function(i){var e=this;a(e.$slider).hasClass("slick-initialized")||(a(e.$slider).addClass("slick-initialized"),e.buildRows(),e.buildOut(),e.setProps(),e.startLoad(),e.loadSlider(),e.initializeEvents(),e.updateArrows(),e.updateDots(),e.checkResponsive(!0),e.focusHandler()),i&&e.$slider.trigger("init",[e]),!0===e.options.accessibility&&e.initADA(),e.options.autoplay&&(e.paused=!1,e.autoPlay())},r.prototype.initADA=function(){var t=this,o=Math.ceil(t.slideCount/t.options.slidesToShow),s=t.getNavigableIndexes().filter(function(i){return 0<=i&&i<t.slideCount});t.$slides.add(t.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==t.$dots&&(t.$slides.not(t.$slideTrack.find(".slick-cloned")).each(function(i){var e=s.indexOf(i);a(this).attr({role:"tabpanel",id:"slick-slide"+t.instanceUid+i,tabindex:-1}),-1!==e&&a(this).attr({"aria-describedby":"slick-slide-control"+t.instanceUid+e})}),t.$dots.attr("role","tablist").find("li").each(function(i){var e=s[i];a(this).attr({role:"presentation"}),a(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+t.instanceUid+i,"aria-controls":"slick-slide"+t.instanceUid+e,"aria-label":i+1+" of "+o,"aria-selected":null,tabindex:"-1"})}).eq(t.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end());for(var i=t.currentSlide,e=i+t.options.slidesToShow;i<e;i++)t.$slides.eq(i).attr("tabindex",0);t.activateADA()},r.prototype.initArrowEvents=function(){var i=this;!0===i.options.arrows&&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),!0===i.options.accessibility&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},r.prototype.initDotEvents=function(){var i=this;!0===i.options.dots&&(a("li",i.$dots).on("click.slick",{message:"index"},i.changeSlide),!0===i.options.accessibility&&i.$dots.on("keydown.slick",i.keyHandler)),!0===i.options.dots&&!0===i.options.pauseOnDotsHover&&a("li",i.$dots).on("mouseenter.slick",a.proxy(i.interrupt,i,!0)).on("mouseleave.slick",a.proxy(i.interrupt,i,!1))},r.prototype.initSlideEvents=function(){var i=this;i.options.pauseOnHover&&(i.$list.on("mouseenter.slick",a.proxy(i.interrupt,i,!0)),i.$list.on("mouseleave.slick",a.proxy(i.interrupt,i,!1)))},r.prototype.initializeEvents=function(){var i=this;i.initArrowEvents(),i.initDotEvents(),i.initSlideEvents(),i.$list.on("touchstart.slick mousedown.slick",{action:"start"},i.swipeHandler),i.$list.on("touchmove.slick mousemove.slick",{action:"move"},i.swipeHandler),i.$list.on("touchend.slick mouseup.slick",{action:"end"},i.swipeHandler),i.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},i.swipeHandler),i.$list.on("click.slick",i.clickHandler),a(document).on(i.visibilityChange,a.proxy(i.visibility,i)),!0===i.options.accessibility&&i.$list.on("keydown.slick",i.keyHandler),!0===i.options.focusOnSelect&&a(i.$slideTrack).children().on("click.slick",i.selectHandler),a(window).on("orientationchange.slick.slick-"+i.instanceUid,a.proxy(i.orientationChange,i)),a(window).on("resize.slick.slick-"+i.instanceUid,a.proxy(i.resize,i)),a("[draggable!=true]",i.$slideTrack).on("dragstart",i.preventDefault),a(window).on("load.slick.slick-"+i.instanceUid,i.setPosition),a(i.setPosition)},r.prototype.initUI=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},r.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&!0===e.options.accessibility?e.changeSlide({data:{message:!0===e.options.rtl?"next":"previous"}}):39===i.keyCode&&!0===e.options.accessibility&&e.changeSlide({data:{message:!0===e.options.rtl?"previous":"next"}}))},r.prototype.lazyLoad=function(){function i(i){a("img[data-lazy]",i).each(function(){var i=a(this),e=a(this).attr("data-lazy"),t=a(this).attr("data-srcset"),o=a(this).attr("data-sizes")||n.$slider.attr("data-sizes"),s=document.createElement("img");s.onload=function(){i.animate({opacity:0},100,function(){t&&(i.attr("srcset",t),o&&i.attr("sizes",o)),i.attr("src",e).animate({opacity:1},200,function(){i.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),n.$slider.trigger("lazyLoaded",[n,i,e])})},s.onerror=function(){i.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,i,e])},s.src=e})}var e,t,o,n=this;if(!0===n.options.centerMode?o=!0===n.options.infinite?(t=n.currentSlide+(n.options.slidesToShow/2+1))+n.options.slidesToShow+2:(t=Math.max(0,n.currentSlide-(n.options.slidesToShow/2+1)),n.options.slidesToShow/2+1+2+n.currentSlide):(t=n.options.infinite?n.options.slidesToShow+n.currentSlide:n.currentSlide,o=Math.ceil(t+n.options.slidesToShow),!0===n.options.fade&&(0<t&&t--,o<=n.slideCount&&o++)),e=n.$slider.find(".slick-slide").slice(t,o),"anticipated"===n.options.lazyLoad)for(var s=t-1,r=o,l=n.$slider.find(".slick-slide"),d=0;d<n.options.slidesToScroll;d++)s<0&&(s=n.slideCount-1),e=(e=e.add(l.eq(s))).add(l.eq(r)),s--,r++;i(e),n.slideCount<=n.options.slidesToShow?i(n.$slider.find(".slick-slide")):n.currentSlide>=n.slideCount-n.options.slidesToShow?i(n.$slider.find(".slick-cloned").slice(0,n.options.slidesToShow)):0===n.currentSlide&&i(n.$slider.find(".slick-cloned").slice(-1*n.options.slidesToShow))},r.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()},r.prototype.next=r.prototype.slickNext=function(){this.changeSlide({data:{message:"next"}})},r.prototype.orientationChange=function(){this.checkResponsive(),this.setPosition()},r.prototype.pause=r.prototype.slickPause=function(){this.autoPlayClear(),this.paused=!0},r.prototype.play=r.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},r.prototype.postSlide=function(i){var e=this;e.unslicked||(e.$slider.trigger("afterChange",[e,i]),e.animating=!1,e.slideCount>e.options.slidesToShow&&e.setPosition(),e.swipeLeft=null,e.options.autoplay&&e.autoPlay(),!0===e.options.accessibility&&(e.initADA(),e.options.focusOnChange&&a(e.$slides.get(e.currentSlide)).attr("tabindex",0).focus()))},r.prototype.prev=r.prototype.slickPrev=function(){this.changeSlide({data:{message:"previous"}})},r.prototype.preventDefault=function(i){i.preventDefault()},r.prototype.progressiveLazyLoad=function(i){i=i||1;var e,t,o,s,n,r=this,l=a("img[data-lazy]",r.$slider);l.length?(e=l.first(),t=e.attr("data-lazy"),o=e.attr("data-srcset"),s=e.attr("data-sizes")||r.$slider.attr("data-sizes"),(n=document.createElement("img")).onload=function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),!0===r.options.adaptiveHeight&&r.setPosition(),r.$slider.trigger("lazyLoaded",[r,e,t]),r.progressiveLazyLoad()},n.onerror=function(){i<3?setTimeout(function(){r.progressiveLazyLoad(i+1)},500):(e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),r.$slider.trigger("lazyLoadError",[r,e,t]),r.progressiveLazyLoad())},n.src=t):r.$slider.trigger("allImagesLoaded",[r])},r.prototype.refresh=function(i){var e,t,o=this;t=o.slideCount-o.options.slidesToShow,!o.options.infinite&&o.currentSlide>t&&(o.currentSlide=t),o.slideCount<=o.options.slidesToShow&&(o.currentSlide=0),e=o.currentSlide,o.destroy(!0),a.extend(o,o.initials,{currentSlide:e}),o.init(),i||o.changeSlide({data:{message:"index",index:e}},!1)},r.prototype.registerBreakpoints=function(){var i,e,t,o=this,s=o.options.responsive||null;if("array"===a.type(s)&&s.length){for(i in o.respondTo=o.options.respondTo||"window",s)if(t=o.breakpoints.length-1,s.hasOwnProperty(i)){for(e=s[i].breakpoint;0<=t;)o.breakpoints[t]&&o.breakpoints[t]===e&&o.breakpoints.splice(t,1),t--;o.breakpoints.push(e),o.breakpointSettings[e]=s[i].settings}o.breakpoints.sort(function(i,e){return o.options.mobileFirst?i-e:e-i})}},r.prototype.reinit=function(){var i=this;i.$slides=i.$slideTrack.children(i.options.slide).addClass("slick-slide"),i.slideCount=i.$slides.length,i.currentSlide>=i.slideCount&&0!==i.currentSlide&&(i.currentSlide=i.currentSlide-i.options.slidesToScroll),i.slideCount<=i.options.slidesToShow&&(i.currentSlide=0),i.registerBreakpoints(),i.setProps(),i.setupInfinite(),i.buildArrows(),i.updateArrows(),i.initArrowEvents(),i.buildDots(),i.updateDots(),i.initDotEvents(),i.cleanUpSlideEvents(),i.initSlideEvents(),i.checkResponsive(!1,!0),!0===i.options.focusOnSelect&&a(i.$slideTrack).children().on("click.slick",i.selectHandler),i.setSlideClasses("number"==typeof i.currentSlide?i.currentSlide:0),i.setPosition(),i.focusHandler(),i.paused=!i.options.autoplay,i.autoPlay(),i.$slider.trigger("reInit",[i])},r.prototype.resize=function(){var i=this;a(window).width()!==i.windowWidth&&(clearTimeout(i.windowDelay),i.windowDelay=window.setTimeout(function(){i.windowWidth=a(window).width(),i.checkResponsive(),i.unslicked||i.setPosition()},50))},r.prototype.removeSlide=r.prototype.slickRemove=function(i,e,t){var o=this;if(i="boolean"==typeof i?!0===(e=i)?0:o.slideCount-1:!0===e?--i:i,o.slideCount<1||i<0||i>o.slideCount-1)return!1;o.unload(),!0===t?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,o.reinit()},r.prototype.setCSS=function(i){var e,t,o=this,s={};!0===o.options.rtl&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,!1===o.transformsEnabled||(!(s={})===o.cssTransitions?s[o.animType]="translate("+e+", "+t+")":s[o.animType]="translate3d("+e+", "+t+", 0px)"),o.$slideTrack.css(s)},r.prototype.setDimensions=function(){var i=this;!1===i.options.vertical?!0===i.options.centerMode&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),!0===i.options.centerMode&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),!1===i.options.vertical&&!1===i.options.variableWidth?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):!0===i.options.variableWidth?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();!1===i.options.variableWidth&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},r.prototype.setFade=function(){var t,o=this;o.$slides.each(function(i,e){t=o.slideWidth*i*-1,!0===o.options.rtl?a(e).css({position:"relative",right:t,top:0,zIndex:o.options.zIndex-2,opacity:0}):a(e).css({position:"relative",left:t,top:0,zIndex:o.options.zIndex-2,opacity:0})}),o.$slides.eq(o.currentSlide).css({zIndex:o.options.zIndex-1,opacity:1})},r.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},r.prototype.setOption=r.prototype.slickSetOption=function(){var i,e,t,o,s,n=this,r=!1;if("object"===a.type(arguments[0])?(t=arguments[0],r=arguments[1],s="multiple"):"string"===a.type(arguments[0])&&(o=arguments[1],r=arguments[2],"responsive"===(t=arguments[0])&&"array"===a.type(arguments[1])?s="responsive":void 0!==arguments[1]&&(s="single")),"single"===s)n.options[t]=o;else if("multiple"===s)a.each(t,function(i,e){n.options[i]=e});else if("responsive"===s)for(e in o)if("array"!==a.type(n.options.responsive))n.options.responsive=[o[e]];else{for(i=n.options.responsive.length-1;0<=i;)n.options.responsive[i].breakpoint===o[e].breakpoint&&n.options.responsive.splice(i,1),i--;n.options.responsive.push(o[e])}r&&(n.unload(),n.reinit())},r.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),!1===i.options.fade?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},r.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=!0===i.options.vertical?"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||!0===i.options.useCSS&&(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&&!1!==i.animType&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&!1!==i.animType},r.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"),!0===n.options.centerMode){var r=n.options.slidesToShow%2==0?1:0;e=Math.floor(n.options.slidesToShow/2),!0===n.options.infinite&&(e<=i&&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 0<=i&&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=!0===n.options.infinite?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()},r.prototype.setupInfinite=function(){var i,e,t,o=this;if(!0===o.options.fade&&(o.options.centerMode=!1),!0===o.options.infinite&&!1===o.options.fade&&(e=null,o.slideCount>o.options.slidesToShow)){for(t=!0===o.options.centerMode?o.options.slidesToShow+1:o.options.slidesToShow,i=o.slideCount;i>o.slideCount-t;i-=1)e=i-1,a(o.$slides[e]).clone(!0).attr("id","").attr("data-slick-index",e-o.slideCount).prependTo(o.$slideTrack).addClass("slick-cloned");for(i=0;i<t+o.slideCount;i+=1)e=i,a(o.$slides[e]).clone(!0).attr("id","").attr("data-slick-index",e+o.slideCount).appendTo(o.$slideTrack).addClass("slick-cloned");o.$slideTrack.find(".slick-cloned").find("[id]").each(function(){a(this).attr("id","")})}},r.prototype.interrupt=function(i){i||this.autoPlay(),this.interrupted=i},r.prototype.selectHandler=function(i){var e=a(i.target).is(".slick-slide")?a(i.target):a(i.target).parents(".slick-slide"),t=parseInt(e.attr("data-slick-index"));t=t||0,this.slideCount<=this.options.slidesToShow?this.slideHandler(t,!1,!0):this.slideHandler(t)},r.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,d=null,a=this;if(e=e||!1,!(!0===a.animating&&!0===a.options.waitForAnimate||!0===a.options.fade&&a.currentSlide===i))if(!1===e&&a.asNavFor(i),o=i,d=a.getLeft(o),r=a.getLeft(a.currentSlide),a.currentLeft=null===a.swipeLeft?r:a.swipeLeft,!1===a.options.infinite&&!1===a.options.centerMode&&(i<0||i>a.getDotCount()*a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else if(!1===a.options.infinite&&!0===a.options.centerMode&&(i<0||i>a.slideCount-a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else{if(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=(l=a.getNavTarget()).slick("getSlick")).slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide),a.updateDots(),a.updateArrows(),!0===a.options.fade)return!0!==t?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight();!0!==t?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)}},r.prototype.startLoad=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},r.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))<0&&(o=360-Math.abs(o)),o<=45&&0<=o?!1===s.options.rtl?"left":"right":o<=360&&315<=o?!1===s.options.rtl?"left":"right":135<=o&&o<=225?!1===s.options.rtl?"right":"left":!0===s.options.verticalSwiping?35<=o&&o<=135?"down":"up":"vertical"},r.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1;if(o.interrupted=!1,o.shouldClick=!(10<o.touchObject.swipeLength),void 0===o.touchObject.curX)return!1;if(!0===o.touchObject.edgeHit&&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={})},r.prototype.swipeHandler=function(i){var e=this;if(!(!1===e.options.swipe||"ontouchend"in document&&!1===e.options.swipe||!1===e.options.draggable&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,!0===e.options.verticalSwiping&&(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)}},r.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&&4<r?!(l.scrolling=!0):(!0===l.options.verticalSwiping&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&4<l.touchObject.swipeLength&&(l.swiping=!0,i.preventDefault()),s=(!1===l.options.rtl?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),!0===l.options.verticalSwiping&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,(l.touchObject.edgeHit=!1)===l.options.infinite&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),!1===l.options.vertical?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,!0===l.options.verticalSwiping&&(l.swipeLeft=e+o*s),!0!==l.options.fade&&!1!==l.options.touchMove&&(!0===l.animating?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},r.prototype.swipeStart=function(i){var e,t=this;if(t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow)return!(t.touchObject={});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,t.dragging=!0},r.prototype.unfilterSlides=r.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())},r.prototype.unload=function(){var i=this;a(".slick-cloned",i.$slider).remove(),i.$dots&&i.$dots.remove(),i.$prevArrow&&i.htmlExpr.test(i.options.prevArrow)&&i.$prevArrow.remove(),i.$nextArrow&&i.htmlExpr.test(i.options.nextArrow)&&i.$nextArrow.remove(),i.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},r.prototype.unslick=function(i){this.$slider.trigger("unslick",[this,i]),this.destroy()},r.prototype.updateArrows=function(){var i=this;Math.floor(i.options.slidesToShow/2),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&!i.options.infinite&&(i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===i.currentSlide?(i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-i.options.slidesToShow&&!1===i.options.centerMode?(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-1&&!0===i.options.centerMode&&(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},r.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"))},r.prototype.visibility=function(){this.options.autoplay&&(document[this.hidden]?this.interrupted=!0:this.interrupted=!1)},a.fn.slick=function(){var i,e,t=this,o=arguments[0],s=Array.prototype.slice.call(arguments,1),n=t.length;for(i=0;i<n;i++)if("object"==typeof o||void 0===o?t[i].slick=new r(t[i],o):e=t[i].slick[o].apply(t[i].slick,s),void 0!==e)return e;return t}});
if(void 0===Product)var Product={};Product.Zoom=Class.create(),Product.Zoom.prototype={initialize:function(i,t,e,s,o,n){if(this.containerEl=$(i).parentNode,this.imageEl=$(i),this.handleEl=$(e),this.trackEl=$(t),this.hintEl=$(n),this.containerDim=Element.getDimensions(this.containerEl),this.imageDim=Element.getDimensions(this.imageEl),this.imageDim.ratio=this.imageDim.width/this.imageDim.height,this.floorZoom=1,this.imageDim.width>this.imageDim.height?this.ceilingZoom=this.imageDim.width/this.containerDim.width:this.ceilingZoom=this.imageDim.height/this.containerDim.height,this.imageDim.width<=this.containerDim.width&&this.imageDim.height<=this.containerDim.height)return this.trackEl.up().hide(),this.hintEl.hide(),void this.containerEl.removeClassName("product-image-zoom");this.imageX=0,this.imageY=0,this.imageZoom=1,this.sliderSpeed=0,this.sliderAccel=0,this.zoomBtnPressed=!1,this.showFull=!1,this.selects=document.getElementsByTagName("select"),this.draggable=new Draggable(i,{starteffect:!1,reverteffect:!1,endeffect:!1,snap:this.contain.bind(this)}),this.slider=new Control.Slider(e,t,{axis:"horizontal",minimum:0,maximum:Element.getDimensions(this.trackEl).width,alignX:0,increment:1,sliderValue:0,onSlide:this.scale.bind(this),onChange:this.scale.bind(this)}),this.scale(0),Event.observe(this.imageEl,"dblclick",this.toggleFull.bind(this)),Event.observe($(s),"mousedown",this.startZoomIn.bind(this)),Event.observe($(s),"mouseup",this.stopZooming.bind(this)),Event.observe($(s),"mouseout",this.stopZooming.bind(this)),Event.observe($(o),"mousedown",this.startZoomOut.bind(this)),Event.observe($(o),"mouseup",this.stopZooming.bind(this)),Event.observe($(o),"mouseout",this.stopZooming.bind(this))},toggleFull:function(){if(this.showFull=!this.showFull,void 0===document.body.style.maxHeight)for(i=0;i<this.selects.length;i++)this.selects[i].style.visibility=this.showFull?"hidden":"visible";var t=this.showFull?1:this.slider.value;return this.scale(t),this.trackEl.style.visibility=this.showFull?"hidden":"visible",this.containerEl.style.overflow=this.showFull?"visible":"hidden",this.containerEl.style.zIndex=this.showFull?"1000":"9",this},scale:function(i){var t=(this.containerDim.width*(1-this.imageZoom)/2-this.imageX)/this.imageZoom,e=(this.containerDim.height*(1-this.imageZoom)/2-this.imageY)/this.imageZoom,s=this.imageDim.width>this.containerDim.width||this.imageDim.height>this.containerDim.height;return this.imageZoom=this.floorZoom+i*(this.ceilingZoom-this.floorZoom),s?(this.imageDim.width>this.imageDim.height?this.imageEl.style.width=this.imageZoom*this.containerDim.width+"px":this.imageEl.style.height=this.imageZoom*this.containerDim.height+"px",this.containerDim.ratio&&(this.imageDim.width>this.imageDim.height?this.imageEl.style.height=this.imageZoom*this.containerDim.width*this.containerDim.ratio+"px":this.imageEl.style.width=this.imageZoom*this.containerDim.height*this.containerDim.ratio+"px")):this.slider.setDisabled(),this.imageX=this.containerDim.width*(1-this.imageZoom)/2-t*this.imageZoom,this.imageY=this.containerDim.height*(1-this.imageZoom)/2-e*this.imageZoom,this.contain(this.imageX,this.imageY,this.draggable),!0},startZoomIn:function(){return this.slider.disabled||(this.zoomBtnPressed=!0,this.sliderAccel=.002,this.periodicalZoom(),this.zoomer=new PeriodicalExecuter(this.periodicalZoom.bind(this),.05)),this},startZoomOut:function(){return this.slider.disabled||(this.zoomBtnPressed=!0,this.sliderAccel=-.002,this.periodicalZoom(),this.zoomer=new PeriodicalExecuter(this.periodicalZoom.bind(this),.05)),this},stopZooming:function(){this.zoomer&&0!=this.sliderSpeed&&(this.zoomBtnPressed=!1,this.sliderAccel=0)},periodicalZoom:function(){return this.zoomer&&(this.zoomBtnPressed?this.sliderSpeed+=this.sliderAccel:(this.sliderSpeed/=1.5,Math.abs(this.sliderSpeed)<.001&&(this.sliderSpeed=0,this.zoomer.stop(),this.zoomer=null)),this.slider.value+=this.sliderSpeed,this.slider.setValue(this.slider.value),this.scale(this.slider.value)),this},contain:function(i,t,e){var s=Element.getDimensions(e.element),o=this.containerDim.width-s.width,n=this.containerDim.height-s.height;return i=(i=0<i?0:i)<o?o:i,t=(t=0<t?0:t)<n?n:t,this.containerDim.width>s.width&&(i=this.containerDim.width/2-s.width/2),this.containerDim.height>s.height&&(t=this.containerDim.height/2-s.height/2),this.imageX=i,this.imageY=t,this.imageEl.style.left=this.imageX+"px",this.imageEl.style.top=this.imageY+"px",[i,t]}},Product.Config=Class.create(),Product.Config.prototype={initialize:function(i){this.config=i,this.taxConfig=this.config.taxConfig,i.containerId?this.settings=$$("#"+i.containerId+" .super-attribute-select"):this.settings=$$(".super-attribute-select"),this.needReloadPrice=!0,this.optionsPrice=i.optionsPrice,this.qtyField=i.qtyField,this.state=new Hash,this.priceTemplate=new Template(this.config.template),this.prices=i.prices,this.productGroupLabel=i.productGroupLabel,this.productGroupId=i.productGroupId,i.defaultValues&&(this.values=i.defaultValues);var t=window.location.href.indexOf("#");if(-1!=t){var e=window.location.href.substr(t+1).toQueryParams();for(var s in this.values||(this.values={}),e)this.values[s]=e[s]}i.inputsInitialized&&(this.values={},this.settings.each(function(i){if(i.value){var t=i.id.replace(/[a-z]*/,"");this.values[t]=i.value}}.bind(this))),this.settings.each(function(i){Event.observe(i,"change",this.configure.bind(this))}.bind(this)),this.settings.each(function(i){var t=i.dataset.attribute.replace(/[a-z]*/,"");t&&this.config.attributes[t]&&(i.config=this.config.attributes[t],i.attributeId=t,this.state[t]=!1)}.bind(this));var o=[];for(s=this.settings.length-1;0<=s;s--){var n=!!this.settings[s-1]&&this.settings[s-1],r=!!this.settings[s+1]&&this.settings[s+1];0==s?this.fillSelect(this.settings[s]):this.settings[s].disabled=!0,$(this.settings[s]).childSettings=o.clone(),$(this.settings[s]).prevSetting=n,$(this.settings[s]).nextSetting=r,o.push(this.settings[s])}var h=this;$j(document).on("click","#delivery-postcode-button",function(i){i.preventDefault(),updateCode(h)}),this.configureForValues(),this.setAdditionalData(),this.initQtyListener(),document.observe("dom:loaded",this.configureForValues.bind(this))},initQtyListener:function(){this.qtyField&&(this.qty=this.qtyField.value,this.qtyField.addEventListener("change",function(i){i.qty=this.value,i.reloadPrice()}.bind(this.qtyField,this)),this.productType===this.productTypeSimple&&this.reloadPrice())},getQty:function(){return this.qty},configureForValues:function(){this.settings.each(function(i){var t=i.attributeId;this.values&&this.values[t]&&(i.value=this.values[t]),this.configureElement(i)}.bind(this))},configure:function(i){var t=Event.element(i);if(this.configureElement(t),this){var e=this.config.externalShopUrls[this.getSelectedProductId()];EventManager.getInstance().notify({name:EmmaEventName.CONFIGURABLE_PRODUCT__EXT_SHOP_CHANGED,payload:{externalUrl:e,productId:this.getSelectedProductId()}})}},configureElement:function(i){this.reloadOptionLabels(i);var t=this.getSelectedProductId(),e=this.config.itemsDelvery;if(t in e){var s=e[t];this.config.$deliveryTime.html(this.formatDeliveryTime(s)),this.needReloadPrice=!1}else this.needReloadPrice=!0;i.value?(this.state[i.config.id]=i.value,i.nextSetting&&(i.nextSetting.disabled=!1,this.fillSelect(i.nextSetting),this.resetChildren(i.nextSetting))):this.resetChildren(i),this.reloadPrice()},reloadOptionLabels:function(i){var t;t=i.options[i.selectedIndex].config&&!this.config.stablePrices?parseFloat(i.options[i.selectedIndex].config.price):0;for(var e=0;e<i.options.length;e++)i.options[e].config&&(i.options[e].text=this.getOptionLabel(i.options[e].config,i.options[e].config.price-t))},resetChildren:function(i){if(i.childSettings)for(var t=0;t<i.childSettings.length;t++)i.childSettings[t].selectedIndex=0,i.childSettings[t].disabled=!0,i.config&&(this.state[i.config.id]=!1)},fillSelect:function(i){var t=i.id.replace(/[a-z]*/,""),e=(t=i.dataset.attribute.replace(/[a-z]*/,""),this.getAttributeOptions(t));this.clearSelect(i),e.sort(function(i,t){var e=i.label.match(/\d+.*?/gim),s=t.label.match(/\d+.*?/gim);return e&&s?parseInt(e[0])-parseInt(s[0])||parseInt(e[1])-parseInt(s[1]):0});var s=!1;if(i.prevSetting&&(s=i.prevSetting.options[i.prevSetting.selectedIndex]),e)for(var o=0,n=0;n<e.length;n++){var r=[];if(s)for(var h=0;h<e[n].products.length;h++)s.config.allowedProducts&&-1<s.config.allowedProducts.indexOf(e[n].products[h])&&r.push(e[n].products[h]);else r=e[n].products.clone();0<r.size()&&(e[n].allowedProducts=r,i.options[o]=new Option(this.getOptionLabel(e[n],e[n].price),e[n].id),i.options[o].setAttribute("data-item-id",e[n].id),void 0!==e[n].price&&i.options[o].setAttribute("price",e[n].price),i.options[o].config=e[n],o++)}},getOptionLabel:function(i){return i.label},formatPrice:function(i,t){return""},clearSelect:function(i){for(var t=i.options.length-1;0<=t;t--)i.remove(t)},getAttributeOptions:function(i){if(this.config.attributes[i])return this.config.attributes[i].options},reloadPrice:function(){if(!this.config.disablePriceReload){for(var i=0,t=(i=parseFloat(this.config.basePrice),new Object),e=this.settings.length-1;0<=e;e--){var s=this.settings[e].options[this.settings[e].selectedIndex];if(s.config)if(this.config.scpConfig)for(var o=s.config.allowedProducts.length;0<=o;o--)void 0!==s.config.allowedProducts[o]&&void 0!==t[s.config.allowedProducts[o]]?t[s.config.allowedProducts[o]]=2:void 0!==s.config.allowedProducts[o]&&(t[s.config.allowedProducts[o]]=1);else i+=parseFloat(s.config.price),parseFloat(s.config.oldPrice)}if(s&&s.config&&0<s.config.discount&&(i-=i*(s.config.discount/100)),this.config.currentProductId){(0<i||this.displayZeroPrice)&&null!==this.qtyField&&(i*=parseInt(this.qtyField.value)||1);var n=this.config.currentProductId;$("product-price-"+n)&&($("product-price-"+n).innerHTML=i)}return this.reloadOldPrice(),i}},setAdditionalData:function(){for(var i in this.config.deliveryDaysByAttrId={},this.config.deliveryTimesByAttrId={},this.config.ecoContributionsByAttrId={},this.config.customDeliveryDays={},this.config.attrToProdIds={},this.config.attributes)if(this.config.attributes.hasOwnProperty(i))for(var t=this.config.attributes[i].options,e=0,s=t.length;e<s;e++){var o=t[e].allowedProducts&&t[e].allowedProducts[0],n=t[e].id;if(!o)return;if(this.config.attrToProdIds[n]=t[e].allowedProducts[0],this.config.deliveryDaysByAttrId[n]=this.config.deliveryDays[o],this.config.deliveryTimesByAttrId[n]=this.config.deliveryTimes[o],this.config.ecoContributionsByAttrId[n]=this.config.ecoContributions[o],void 0!==this.config.deliveryTimesCustom)for(var r in this.config.deliveryTimesCustom)r in this.config.customDeliveryDays||(this.config.customDeliveryDays[r]={}),this.config.customDeliveryDays[r][n]=this.config.deliveryTimesCustom[r][o]}},updateDeliveryTime:function(){if(this.needReloadPrice&&this.config.$deliveryTime){var i=0,t=null,e=this.config.deliveryDaysByAttrId;if(!e)return;for(var s in this.updateLastStockText(),this.state)this.state.hasOwnProperty(s)&&parseInt(e[this.state[s]])>i&&(t=this.state[s],i=parseInt(e[this.state[s]]));if(null!==t)if(void 0!==this.config.scpConfig&&void 0!==this.config.scpConfig.currentSimpleId&&this.config.scpConfig.currentSimpleId){void 0!==optionsPrice.curOptionId&&optionsPrice.curOptionId&&(customDeliveryDays=this.config.deliveryTimesCustom[optionsPrice.curOptionId]);var o=this.config.scpConfig.currentSimpleId;"undefined"!=typeof customDeliveryDays&&void 0!==customDeliveryDays[o]?this.config.$deliveryTime.html(this.formatDeliveryTime(customDeliveryDays[o])):this.config.$deliveryTime.html(this.formatDeliveryTime(this.config.deliveryTimes[o]))}else void 0!==optionsPrice.curOptionId&&optionsPrice.curOptionId&&(customDeliveryDays=this.config.customDeliveryDays[optionsPrice.curOptionId]),"undefined"!=typeof customDeliveryDays&&void 0!==customDeliveryDays[t]?this.config.$deliveryTime.html(this.formatDeliveryTime(customDeliveryDays[t])):this.config.$deliveryTime.html(this.formatDeliveryTime(this.config.deliveryTimesByAttrId[t]))}},updateLastStockText:function(){var e=jQuery(".last-sizes-available"),s=this;this.timeoutHack&&clearTimeout(this.timeoutHack),this.timeoutHack=setTimeout(function(){var i=s.config.lastStockConfigs[s.getSelectedProductId()];if(i&&i.is_last_stock_enabled){e.css("visibility","visible");var t=i&&null!=i.text?i.text:Translator.translate("⬤ Only a few left in stock");e.text(t)}else e.css("visibility","hidden")},50)},formatDeliveryTime:function(i){return"object"==typeof i&&(i=i.words),i},reloadOldPrice:function(){if(!this.config.disablePriceReload&&$("old-price-"+this.config.currentProductId)){for(var i=parseFloat(this.config.oldPrice),t=this.settings.length-1;0<=t;t--){var e=this.settings[t].options[this.settings[t].selectedIndex];e.config&&(i+=parseFloat(e.config.price))}i<0&&(i=0),(0<i||this.displayZeroPrice)&&null!==this.qtyField&&(i*=parseInt(this.qtyField.value)||1),i=this.formatPrice(i),$("old-price-"+this.config.currentProductId)&&($("old-price-"+this.config.currentProductId).innerHTML=i)}},getSelectedProductId:function(){for(var i={},t=this.settings.length,e=0;e<t;e++){var s=this.settings[e].options[this.settings[e].selectedIndex];if(s.config)for(var o=s.config.products.length,n=0;n<o;n++){var r=s.config.products[n];if(i[r]?i[r]++:i[r]=1,i[r]===this.settings.length)return r}}return null},formatPrice:function(i){return formatCurrency(i,this.config.priceFormat)}};
var AFFIRM_AFFIRM = AFFIRM_AFFIRM || {};

function payoneSwitchRateOrRuntime(e,t,n){"rate"==e?(document.getElementById(t+"_SwitchToTerm").className="ratepay-Active",document.getElementById(t+"_SwitchToRuntime").className="",document.getElementById(t+"_ContentTerm").style.display="block",document.getElementById(t+"_ContentRuntime").style.display="none"):"runtime"==e&&(document.getElementById(t+"_SwitchToRuntime").className="ratepay-Active",document.getElementById(t+"_SwitchToTerm").className="",document.getElementById(t+"_ContentRuntime").style.display="block",document.getElementById(t+"_ContentTerm").style.display="none")}function payoneRatepayRateCalculatorAction(e,t,n){var a,l,d,o,u,i,m,c=$("ajaxLoaderId"),y=$("cover");c.setStyle({display:"block"}),y.setStyle({display:"block"}),window.XMLHttpRequest?xmlhttp=new XMLHttpRequest:xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"),i=document.getElementById("amount").value,u=document.getElementById("ratePayShopId").value,m=document.getElementById("ratePayCurrency").value,"rate"==e?(a=document.getElementById(t+"-rate").value,l="calculation-by-rate",document.getElementById("debitSelect")?dueDate=document.getElementById("debitSelect").value:dueDate=""):"runtime"==e&&(a=document.getElementById(t+"-runtime").value,l="calculation-by-time",d=null==document.getElementById(t+"_Notification")?0:1,document.getElementById("debitSelectRuntime")?dueDate=document.getElementById("debitSelectRuntime").value:dueDate=""),xmlhttp.open("POST",n,!1),xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),xmlhttp.send("paymentMethod="+t+"&calcValue="+a+"&calcMethod="+l+"&dueDate="+dueDate+"&notification="+d+"&ratePayshopId="+u+"&ratePayCurrency="+m+"&amount="+i),null!=xmlhttp.responseText&&(o=xmlhttp.responseText,document.getElementById(t+"_ResultContainer").innerHTML=o,document.getElementById(t+"_ResultContainer").style.display="block",document.getElementById(t+"_ResultContainer").style.padding="3px 0 0 0",document.getElementById(t+"_SwitchToTerm").style.display="none",c.setStyle({display:"none"}),y.setStyle({display:"none"}))}function payoneSwitchPayRate(e){"RPS"===e.value?$("ratepay-main-cont").setStyle({display:"block"}):$("ratepay-main-cont").setStyle({display:"none"})}function payoneRatepayCustomerDobInput(e){var t=$(e+"_additional_fields_customer_dob_day"),n=$(e+"_additional_fields_customer_dob_month"),a=$(e+"_additional_fields_customer_dob_year"),l=$(e+"_additional_fields_customer_dob_full");null!=t&&null!=n&&null!=a&&null!=l&&(l.value=a.value+"-"+n.value+"-"+t.value)}var Translator=new Translate([]);Validation.add("validate-18-years",Translator.translate("You have to be at least 18 years old to use this payment type!"),function(e){var t=new Date(e);return!(new Date((new Date).setYear((new Date).getFullYear()-18))<t)}),Validation.add("validate-select-group",Translator.translate("This is a required field."),function(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)});
function displayPayolutionOverlay(e){document.getElementById(e+"_overlay").style.display=""}function removePayolutionOverlay(e){document.getElementById(e+"_overlay").style.display="none"}function switchVisibility(e,t){for(var a=0;a<e.length;a++){var i=$(e[a]);i&&(1==t?i.show():i.hide())}}function payoneSwitchPayolution(e,t){if(null!=e){if("PYV"==e.value){var a=[t+"_b2b_wrap",t+"_birthday_wrap",t+"_installment_wrap1",t+"_acceptance_wrap"];switchVisibility([t+"_debit_wrap",t+"_debit_wrap2",t+"_installment_wrap2"],!1),switchVisibility(a,!0),$(t+"_selected_installmentplan").value="0"}else if("PYD"==e.value){a=[t+"_debit_wrap",t+"_debit_wrap2",t+"_b2b_wrap",t+"_birthday_wrap",t+"_acceptance_wrap"];switchVisibility([t+"_installment_wrap1",t+"_installment_wrap2",t+"_debit_subwrap"],!1),switchVisibility(a,!0),$(t+"_selected_installmentplan").value="0"}else if("PYS"==e.value&&!$(t+"_installment_wrap2").visible()){a=[t+"_installment_wrap1"];switchVisibility([t+"_debit_wrap",t+"_debit_wrap2",t+"_debit_subwrap"],!1),switchVisibility(a,!0),$(t+"_selected_installmentplan").value=""}""==e.value?$(t+"_main_block").hide():$(t+"_main_block").show()}}function handleInstallmentAllowed(e){$(e.code+"_installment_wrap2").update(e.update_section.html);var t=[e.code+"_b2b_wrap",e.code+"_birthday_wrap",e.code+"_acceptance_wrap",e.code+"_installment_wrap1"],a=[e.code+"_installment_wrap2"];switchVisibility(t,!1),switchVisibility(a,!0)}function handleInstallment(t,e){if(0==checkout.loadWaiting){var a=new Validation(payment.form);if(payment.validate()&&a.validate()){checkout.setLoadWaiting("payment");var i=$(t+"_additional_fields_customer_dob_full").value,l=$(t+"_type_select").value,n=$(t+"_payment_method_id").value;new Ajax.Request(e,{method:"Post",parameters:{payone_payolution_type:l,payone_customer_dob:i,payone_config_payment_method_id:n,code:t},onComplete:function(e){if(checkout.setLoadWaiting(!1),e.responseText&&(response=JSON.parse(e.responseText),1==response.success))return $(t+"_installment_wrap1").hide(),void handleInstallmentAllowed(response);alert(Translator.translate("The installment calculation failed. Please choose another payment type."))}})}}}function switchInstallmentPlan(e,t,a){$$(".payolution_installmentplans").each(function(e){e.hide()}),$$(".payolution_installment_overview").each(function(e){e.hide()}),switchVisibility(["payolution_installmentplan_"+e,"payolution_installment_overview_"+e,t+"_debit_wrap",t+"_debit_subwrap"],!0),$(t+"_selected_installmentplan").value=a}