jQuery(document).ready(function ($) {


    // add payment method images to footer section for all pages
    addPaymentMethodImagesToFooter();

    if (isAvailableApplePay()) {
        disableApplePay();
        $(CONST.APPLEPAY_SELECTOR).removeClass(CONST.HIDE);
        if (typeof applePayEnabled !== 'undefined' && applePayEnabled
            && !dropInEnabled && ((isShoppingCartPage() && applePayExpressEnabled) || isMarkCheckoutPage())) {
            changeApplePayButtonShape(applePayShape);
        }
    } else {
        $(CONST.APPLEPAY_SELECTOR).remove();
    }

    // PayPal along with Hosted Fields checkout configuration
    if ((typeof paymentMethodsPage != 'undefined')) {
        //check if google pay supported display radio
        if (dropInEnabled) {
            initializeDropIn(createPayPalOptions());
        } else {
            checkVenmoPaymentMethods();
            createClientInstance(CONST.GLOBAL_MESSAGES, function () {
                if (googlePayEnabled) {
                    initialiseGooglePay();
                }
                configurePayPalAlongWithHostedFields();
            })
        }
    }

    if (typeof accountPaymentInfoPage != 'undefined') {
        enableShippingAddress = "false";
        configureAccountPaymentInfoPage();
    }

    if ((typeof addPaymentMethodsPage != 'undefined')) {
        enableShippingAddress = "false";
        if (dropInEnabled) {
            if(typeof accountPage !== 'undefined' && accountPage === 'accountAddPaymentMethodPage'){
                if ((document.getElementsByClassName(CONST.DROP_IN_ADD_PAYMENT_CONTAINER)[0]) !== undefined) {
                    initializeDropIn(createPayPalOptions());
                }
            } else {
                initializeDropIn(createPayPalOptions());
            }
        } else {
            checkVenmoPaymentMethods();
            createClientInstance(CONST.GLOBAL_MESSAGES, function () {
                if (googlePayEnabled) {
                    initialiseGooglePay();
                }
                configurePayPalAlongWithHostedFields();
            })
        }

        if (typeof isShowHostedFields !== 'undefined' && isShowHostedFields === "true") {

                      const currentSelectedOption = document.getElementById("billingAddressSelector")?.selectedOptions[0];
                      if (currentSelectedOption?.value === "newAddress") {
                        document.querySelector("#addressFormSelectorContainer").style.display = 'block';
                      }

                      if (currentSelectedOption?.value !== "newAddress" && currentSelectedOption?.value !== "noAddress") {
                        addSelectedAddressFieldToTheForm(currentSelectedOption?.value);
                      }

                      document.getElementById('billingAddressSelector')?.addEventListener('change', function (event) {
                        if (event.target.value === 'newAddress') {
                          document.querySelector("#addressFormSelectorContainer").style.display = 'block';
                          document.getElementById("selected-address").innerHTML = "";
                          for (const property of document.getElementById('braintree-payment-form').elements) {
                            property?.parentElement?.classList?.remove('has-error');
                            if (property.nextSibling?.classList?.contains("help-block")) {
                              property.nextSibling.remove();
                            }
                          }
                        } else {
                          document.querySelector("#addressFormSelectorContainer").style.display = 'none';
                          addSelectedAddressFieldToTheForm(event.target.value);
                        }
                      });
                    }
    }

    // PayPal Shopping Cart Shortcut checkout configuration
    if (typeof shoppingCart != 'undefined' && shoppingCart !== '') {
        configurePaypalShortcut(CONST.PAYPAL_BUTTON);
    }

    if (typeof isCreditMessagesEnabled != 'undefined' && typeof shoppingCart == 'undefined') {
        configurePageForCreditMessage();
    }
    //Render button for automatic PM adding
    if (typeof savePaymentInfoPage != 'undefined' && savePaymentInfoPage === 'savePaymentInfoPage'){
        ACC.loadingSpinner.showSpinner(CONST.LOGIN_SAVE_PAYMENT_INFO_BUTTONS_CONTAINER);
        $("#" + CONST.LOGIN_SAVE_PAYMENT_INFO_BUTTONS_CONTAINER).removeClass("disabledArea");
        addBrainTreeLibrary(function () {
            createClientInstance(CONST.GLOBAL_MESSAGES, function(){
                createPayPalPaymentMarkFlow(createPayPalOptions());
            })
        });
    }
});

function addSelectedAddressFieldToTheForm(addressId) {
  const selectedAddressInput = document.createElement("input");
  selectedAddressInput.setAttribute("type", "hidden");
  selectedAddressInput.setAttribute("name", "selectedAddressCode");
  selectedAddressInput.setAttribute("id", "selectedAddressCode");
  selectedAddressInput.setAttribute("value", addressId);

  document.getElementById("selected-address").innerHTML = "";
  document.getElementById("selected-address").appendChild(selectedAddressInput);
}

function handleValidationError(isValidationError) {
  if (typeof isValidationError !== 'undefined' && isValidationError === "true") {
    document.querySelector(PAYPAL_CONSTANTS.HOSTED_FIELDS.CARD_BUTTON_CONTAINER).style.display = 'block';
    if (document.querySelector(PAYPAL_CONSTANTS.HOSTED_FIELDS.PAYMENT_METHOD_BUTTON_CONTAINER) !== null) {
      document.querySelector(PAYPAL_CONSTANTS.HOSTED_FIELDS.PAYMENT_METHOD_BUTTON_CONTAINER).style.display = 'none';
    }
    if (document.getElementById('paypalCheckbox') !== null) {
      document.getElementById('paypalCheckbox').checked = false;
    }
    document.getElementById('cardCheckbox').checked = true;
  }
}

$(CONST.CREDIT_CARD_PAYMENT_METHOD_ID).change(function () {
    resetHostedFields();
    ACC.creditCard.createHostedFields();
});

$(CONST.PAYMENT_METHOD_PAYPAL).change(function () {
    createPayPalPaymentMarkFlow(createPayPalOptions());
});

$(CONST.PAYMENT_METHOD_APPLE_PAY).change(function () {
    createApplePay(createPayPalOptions(), CONST.APPLE_PAY_BUTTON_SELECTOR, function (payload) {
        processApplePayResponseExpressCheckout(payload);
    });
});

$(CONST.PAYMENT_METHOD_GOOGLE_PAY).change(function () {
    resetHostedFields();
    if ($(CONST.GOOGLE_PAY_BUTTON).length > !1 && $(CONST.GOOGLE_PAY_BUTTON).is(":empty")) {
        setupGooglePayButton();
    }
});


$(CONST.PAYMENT_METHOD_LOCAL_PAYMENT).change(function () {
    resetHostedFields();
    createLocalPayment();
});

$(CONST.PAYMENT_METHOD_SRC).change(function () {
    resetHostedFields();
    initializeSrc();
});

let isVenmoInitialized = false;
$(CONST.PAYMENT_METHOD_VENMO).change(function () {
    if(isVenmoInitialized){
        return;
    }
    resetHostedFields();
    renderVenmoButton();
    isVenmoInitialized = true;
});

$("form[id^='savedPaymentInfoForm']").on('submit', function (e) {
    $("button[id^='useSelectedPaymentMethod']").attr("disabled", true);
    ACC.threeDSecure.verifySavedPaymentBy3DSecure(e);
});

function addPaymentMethodImagesToFooter() {
    var paymentOptionsTextDiv = $(HTML.DIV).attr(HTML.CLASS, CONST.PAYMENT_OPTIONS);
    var br = $(HTML.BR);
    $(CONST.FOOTER).prepend(br);
    $(CONST.FOOTER).prepend(br);
    $(CONST.FOOTER).prepend(paymentOptionsTextDiv);
    var paymentOptionsImage = $(HTML.IMG);
    paymentOptionsImage
        .attr(
            HTML.SRC,
            CONST.FOOTER_IMG_SRC);
    paymentOptionsImage.attr(HTML.ALT, CONST.PAYMENT_OPTIONS_TEXT);
    $(HTML.FOOTER).children(CONST.CONTAINER_CLASS).append(paymentOptionsImage);
}

function activatePaypalStandardImage() {
    $(CONST.PAYPAL_CHECKOUT_IMAGE_SELECTOR).hover(function () {
        $(this).css('cursor', 'pointer');
    });
}

function selectIsSingleCheckbox() {
    if (JSON.parse(singleUse)) {
        $(CONST.SINGLE_USE_CHECKBOX_ID).prop(CONST.PROP_CHECKED, false);
        // initialize standard paypal by braintree
        initialisePaypal(CONST.PAYPAL_BUTTON);
    } else {
        $(CONST.SINGLE_USE_CHECKBOX_ID).prop(CONST.PROP_CHECKED, true);
        // initialize standard paypal by braintree
        initialisePaypal(CONST.PAYPAL_BUTTON);
    }
}

function showRemovePaymentDetailsConfirmation(paymentInfoID) {
    $.colorbox({
        href: "#popup_confirm_payment_removal_" + paymentInfoID,
        inline: true,
        maxWidth: "100%",
        opacity: 0.7,
        width: "320px",
        onComplete: function () {
            $(this).colorbox.resize();
        }
    });
}

function bindToColorboxClose() {
    $.colorbox.close();
}

function receiveNewAddressData(selectedAddressID) {
    $.ajax({
        url: ACC.config.encodedContextPath + '/my-account/receive-address',
        type: 'GET',
        data: { "selectedAddressCode": selectedAddressID },
        success: function (result) {
            var selectedAddress = $.parseJSON(result);
            $("#title").text(selectedAddress.title);
            $("#firstName").text(selectedAddress.firstName);
            $("#lastName").text(selectedAddress.lastName);
            $("#line1").text(selectedAddress.line1);
            $("#line2").text(selectedAddress.line2);
            $("#town").text(selectedAddress.town);
            $("#postalCode").text(selectedAddress.postalCode);
            $("#country-name").text(selectedAddress.country.name);
            if (selectedAddress.region != null) {
                $("#region-name").text(selectedAddress.region.name);
            } else {
                $("#region-name").text("");
            }
            $("#billingAddressId").val(selectedAddress.id);
        }
    });
    $.colorbox.close();
}
