ACC.creditCard = {

    _autoload: [['checkoutPaymentMethodCCOnClickEventHandler', $('#checkout-paymentmethod').length !== 0]],

    checkoutPaymentMethodCCOnClickEventHandler: function () {
        $(`#verify-cvv-cancel-button`).on(`click`, this.cancelCVVVerify);
    },

    createHostedFields: function () {

        braintree.hostedFields.create({
                client: client,
                styles: {
                    // Styling element state
                    ":focus": {
                        "color": "blue"
                    },
                    ".valid": {
                        "color": "green"
                    },
                    ".invalid": {
                        "color": "red"
                    }
                },
                fields: {
                    cardholderName: {
                      container: '#cardholderName'
                    },
                    number: {
                      container: CONST.NUMBER_ID
                    },
                    expirationDate: {
                      container: CONST.EXPIRATION_DATE_ID,
                      placeholder: "MM/YY"
                    },
                    cvv: {
                      container: CONST.CVV_ID
                    }
                }
            },
            function (hostedFieldsErr, hostedFieldsInstance) {
                if (hostedFieldsErr) {
                    $("#submit_silentOrderPostForm").removeAttr("disabled");
                    handleClientError(hostedFieldsErr);
                    return;
                }

                $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).unbind(EVENTS.CLICK);

                $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).click(function () {
                    const shouldSaveAddress = $(CONST.SAVE_ADDRESS_CHECKBOX).is(HTML.CHECKED);
                    $('#' + CONST.BRAINTREE_PAYMENT_FORM_ID).append(createHiddenParameter('shouldSaveAddress', shouldSaveAddress));
                    if (typeof addPaymentMethodsPage != 'undefined' && document.getElementById('selected-address').children.length === 0) {
                        deleteFieldErrorMessages();
                        $.ajax({
                            type: 'POST',
                            url: contextPath + '/my-account/add-payment-method/validate',
                            data: prepareAddressData(),
                            contentType: "application/json",
                            success: function () {
                                ACC.creditCard.tokenizeHostedFields(hostedFieldsInstance);
                            },
                            error: function (err) {
                                handleAddressValidationErrors(err);
                            }
                        });
                    } else {
                        ACC.creditCard.tokenizeHostedFields(hostedFieldsInstance);
                    }
                });
            }
        );

    },

    tokenizeHostedFields: function (hostedFieldsInstance) {
        tokenizeOptions = {
            authenticationInsight: {
                merchantAccountId: currencyMerchantAccountId
            }
        };
        // initialize paypal authorization
        $("#submit_silentOrderPostForm").attr("disabled", true);
        hostedFieldsInstance.tokenize(tokenizeOptions, function (tokenizeErr, payload) {
            if (tokenizeErr) {
                $("#submit_silentOrderPostForm").removeAttr("disabled");
                handleClientError(tokenizeErr)
            } else {
                if (ACC.threeDSecure.is3DSecureEnabledForHostedFields(payload)) {
                    ACC.threeDSecure.verifyHostedFieldsBy3DSecure(client, payload);
                } else {
                    processResponse(payload);
                }
            }
        });
    },

    verifyCVV: function(e) {
        var containerId = ACC.threeDSecure.inferContainerIdByPage();

        if (ACC.loadingSpinner.isSpinnerActivated(containerId)) {
            ACC.loadingSpinner.hideSpinner(containerId);
        }

        //Closing box with saved payment methods
        const boxWithSavedPaymentMethods = $("#cboxClose")[0];
        boxWithSavedPaymentMethods.dispatchEvent(new CustomEvent('click'));

        //Hide all elements into Payment & Billing Address step
        const checkoutIndentElement = $(".checkout-indent")[0];
        checkoutIndentElement.style.display = 'none';

        //Show block for verifying cvv for hosted fields
        const verifyingCvvElement = $("#verifying-cvv")[0];
        verifyingCvvElement.classList.remove('bt-display-none');

        //Show selected payment method for CVV verification
        const paymentMethodId = $(e.target).find('input[name="selectedPaymentMethodId"]').val();
        const selectedPaymentMethodForCVVVerification = $("#paymentMethodVerification" + paymentMethodId)[0];
        selectedPaymentMethodForCVVVerification.classList.remove('bt-display-none');

        braintree.hostedFields.create({
            client: client,
            fields: {
                cvv: {
                    selector: '#verify-cvv'
                }
            }
        }, function (err, hostedFieldsInstance) {

            if (err) {
                console.error(err);
                return;
            }

            const verifyCvvButton = $("#verify-cvv-button")[0];
            verifyCvvButton.addEventListener('click', function () {

                hostedFieldsInstance.tokenize(function (err, payload) {

                    if (err) {
                        console.error(err);
                        showCustomAbsoluteErrorMessage(ACC.addons.braintreeaddon['braintree.message.invalid.cvv.card']);
                        return;
                    }

                    ACC.creditCard.disableVerifyCVVButtons();
                    $(e.target).find('input[name="selectedPaymentMethodCvvNonce"]').val(payload.nonce);
                    e.currentTarget.submit();
                });
            });
        });
    },

    cancelCVVVerify: function() {
        ACC.creditCard.disableVerifyCVVButtons();
        window.location = ACC.config.encodedContextPath + '/checkout/multi/payment-method/add';
    },

    disableVerifyCVVButtons: function() {
        document.getElementById(CONST.VERIFY_CVV_BUTTON).disabled = true;
        document.getElementById(CONST.VERIFY_CVV_CANCEL_BUTTON).disabled = true;
    }

}