function checkIntentOption(paypalIntent) {
    var isIntentValid = true;
    if (paypalIntent !== CONST.INTENT_SALE
        && paypalIntent !== CONST.INTENT_AUTHORIZE && paypalIntent !== CONST.INTENT_CAPTURE) {
        isIntentValid = false;
        return isIntentValid;
    } else {
        return isIntentValid;
    }
}

function processExpressCheckoutForm(paypalResponse, forceVault, deviceDataValue, isMiniCartCheckout) {
    var payPalForm;
    var isSavePaymentInfo;

    if ((typeof addPaymentMethodsPage != 'undefined') && (typeof isMiniCartCheckout == 'undefined')) {
        payPalForm = createForm(CONST.PAYPAL_EXPRESS_FORM_NAME, ACC.config.encodedContextPath + "/braintree/paypal/checkout/add-payment-method");
    }else if ((typeof returnUrlAfterSave != 'undefined')) {
        payPalForm = createForm(CONST.PAYPAL_EXPRESS_FORM_NAME, ACC.config.encodedContextPath + "/" + returnUrlAfterSave);
    }
    else {
        payPalForm = createForm(CONST.PAYPAL_EXPRESS_FORM_NAME, ACC.config.encodedContextPath + "/braintree/paypal/checkout/express");
    }

    if ($(CONST.SAVE_PAYMENT_INFO_ID + ':' + CONST.PROP_CHECKED).val() === CONST.TRUE || forceVault === true) {
        isSavePaymentInfo = createHiddenParameter("isSaved", CONST.TRUE);
    } else {
        isSavePaymentInfo = createHiddenParameter("isSaved", CONST.FALSE);
    }

    var paymentType = createHiddenParameter("payPalData", JSON.stringify(paypalResponse));
    var realToken = createHiddenParameter("CSRFToken", ACC.config.CSRFToken);

    // collect device data for advanced fraud tools
    var collectDeviceData;
    if (typeof deviceDataValue != 'undefined') {
        collectDeviceData = createHiddenParameter("device_data", deviceDataValue);
    } else {
        collectDeviceData = createHiddenParameter("device_data", this.deviceData);
    }
    payPalForm.append($(isSavePaymentInfo));
    payPalForm.append($(collectDeviceData));
    payPalForm.append($(paymentType));
    payPalForm.append($(realToken));
    payPalForm.appendTo('body');

    payPalForm.submit();
}

function processResponse(response, deviceDataValue) {

  var submitForm = $('#' + CONST.BRAINTREE_PAYMENT_FORM_ID);

  var useDeliveryAddress = $(CONST.USE_DELIVERY_ADDRESS_ID).is(HTML.CHECKED);
  var useDelivery = createHiddenParameter("use_delivery_address", useDeliveryAddress);

  var paymentNonce = createHiddenParameter("nonce", response.nonce);
  submitForm.append($(paymentNonce));

  // collect device data for advanced fraud tools
  var deviceData;
  if (typeof deviceDataValue != 'undefined') {
      deviceData = createHiddenParameter("deviceData", deviceDataValue);
  } else {
      deviceData = createHiddenParameter("deviceData", this.deviceData);
  }

    var cardholder = createHiddenParameter(CONST.CARDHOLDER, response.details.cardholderName);

    let token = ACC.config.CSRFToken;
    let realToken = createHiddenParameter("CSRFToken", token);

    submitForm.append($(deviceData));
    submitForm.append($(useDelivery));
    submitForm.append($(cardholder));
    submitForm.append($(realToken));

    submitForm.submit();
}

function createForm(name, action) {
    var form = $(HTML.FORM).attr(CONST.ATTR_ACTION, action)
        .attr(CONST.ATTR_NAME, name).attr(CONST.ATTR_METHOD, CONST.FORM_METHOD_POST);
    return form;
}

function createHiddenParameter(name, value) {
    var input = $(HTML.INPUT).attr(HTML.TYPE, "hidden").attr(CONST.ATTR_NAME, name).val(
        value);
    return input;
}

function disablePlaceOrderButton() {
    document.getElementById('placeOrder').disabled = true;
}

function checkSavedPaymentMethods(paymentType, isAvailable) {
    const payments =  $('.paymentType');
    var  isEnabledPayment = isPaymentEnabled(paymentType);

    payments.each(function () {
        if (($(this).val() === paymentType) && (!isAvailable || !isEnabledPayment)) {
            $(this).next().remove();
            $(this).remove();
        } else {
            if (canRemoveHide($(this).val(), paymentType)) {
                $(this).next().removeClass(CONST.HIDE);
            }
        }
    });

    if (typeof paymentMethodsPage != 'undefined') {
        if (!anotherPaymentPresent(payments, paymentType) && (!isAvailable || !isEnabledPayment)) {
            $('#savePaymentButton').remove();
        } else {
            $('#savePaymentButton').removeClass(CONST.HIDE);
        }
    }
}

function canRemoveHide(elem, type){
    if (elem===CONST.VENMO_ACCOUNT && type !== CONST.VENMO_ACCOUNT){
        return false;
    }

    if (elem===CONST.GOOGLE_PAY_ACCOUNT && type !== CONST.GOOGLE_PAY_ACCOUNT){
        return false;
    }
    return true;
}

function anotherPaymentPresent(payments, paymentType){
    return payments.toArray().some(value => value['value']!==paymentType);
}

function isPaymentEnabled(paymentType){
    if (paymentType===CONST.VENMO_ACCOUNT){
        return  venmoEnabled;
    }else if (paymentType===CONST.GOOGLE_PAY_ACCOUNT){
        return googlePayEnabled;
    }

    return false;
}

function configurePayPalAlongWithHostedFields() {

    // remove paypal validation messages
    $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();

    // add select payment method event
    $(CONST.PAYMENT_METHOD_SECTION).change(function () {
        paymentMethod();
    });

    // render appropriate payment method
        selectPaymentMethod();
}



function selectPaymentMethod() {
    if (typeof isCreditCardSelect != 'undefined' && isCreditCardSelect !== '' && isCreditCardSelect === "true") {
        $(CONST.CREDIT_CARD_PAYMENT_METHOD_ID).prop(CONST.PROP_CHECKED, true);
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).attr('type', 'submit');
    } else if (typeof isSingleUseSelect != 'undefined' && isSingleUseSelect !== '') {
        $(CONST.PAYMENT_METHOD_PAYPAL).prop(CONST.PROP_CHECKED, true);
        // select paypal as default
    } else {
        $(CONST.PAYMENT_METHOD_PAYPAL).prop(CONST.PROP_CHECKED, true);
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).attr('type', 'button');
        if(isAvailableVenmo()){
            $(CONST.VENMO_SELECTOR).removeClass(CONST.HIDE);
        } else {
            $(CONST.VENMO_SELECTOR).remove();
        }

        disableRadioButton();
    }

    if (isAccountPage()) {
        handleMyAccountSelectWithLimitation();
    }

    triggerCheckedPaymentMethod();
}

function handleMyAccountSelectWithLimitation() {
    if (isPayPalOnLimit) {
        $(CONST.PAYMENT_METHOD_PAYPAL).prop(CONST.PROP_CHECKED, false);
    }

    if (isCardOnLimit) {
        $(CONST.CREDIT_CARD_PAYMENT_METHOD_ID).prop(CONST.PROP_CHECKED, false);
    }

    if (isVenmoOnLimit) {
        $(CONST.PAYMENT_METHOD_VENMO).prop(CONST.PROP_CHECKED, false);
    }

    if (isGooglePayOnLimit) {
        $(CONST.PAYMENT_METHOD_GOOGLE_PAY).prop(CONST.PROP_CHECKED, false);
    }

    if (isSRCOnLimit) {
        $(CONST.PAYMENT_METHOD_SRC).prop(CONST.PROP_CHECKED, false);
    }

    if (isACHOnLimit) {
        $(CONST.PAYMENT_METHOD_US_BANK_ACCOUNT).prop(CONST.PROP_CHECKED, false);
    }

   disableRadioButton();
}

function handleCheckoutCheckboxWithLimitation() {
    if (isSelectedPMLimited() === 'true') {
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).hide();
    }
}

function isSelectedPMLimited() {
return (
    ($(CONST.PAYMENT_METHOD_PAYPAL).is(HTML.CHECKED) && isPayPalOnLimit) ||
    ($(CONST.CREDIT_CARD_PAYMENT_METHOD_ID).is(HTML.CHECKED) && isCardOnLimit) ||
    ($(CONST.PAYMENT_METHOD_VENMO).is(HTML.CHECKED) && isVenmoOnLimit) ||
    ($(CONST.PAYMENT_METHOD_GOOGLE_PAY).is(HTML.CHECKED) && isGooglePayOnLimit) ||
    ($(CONST.PAYMENT_METHOD_SRC).is(HTML.CHECKED) && isSRCOnLimit) ||
    ($(CONST.PAYMENT_METHOD_US_BANK_ACCOUNT).is(HTML.CHECKED) && isACHOnLimit)
);
}


function disableRadioButton() {
    var radioButtons = $(CONST.PAYMENT_METHOD_SECTION);
    if (radioButtons.length === 1) {
        radioButtons.prop(CONST.PROP_CHECKED, true);
        radioButtons.hide();
    } else if (radioButtons.length === 0) {
        $(CONST.NO_PAYMENT_METHODS_MESSAGE).removeClass('hidden');
        paymentMethod();
    } else if (!radioButtons.is(HTML.CHECKED)) {
        radioButtons.filter(':first').prop(CONST.PROP_CHECKED, true);
    }
}

function triggerCheckedPaymentMethod(){
    var radioButtons = $(CONST.PAYMENT_METHOD_SECTION);
    radioButtons.filter(HTML.CHECKED).trigger(EVENTS.CHANGE);
}

function paymentMethod() {
    if (isPayPalMethodSelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.MARK_PAYPAL_BUTTON).show();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.PAYPAL_CMS_IMAGE_SELECTOR).removeClass(CONST.DISABLE_CLICK);
        $(CONST.SELECT_PAYMENT).val(CONST.PAYPAL);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    } else if (isApplePaySelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).show();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.SELECT_PAYMENT).val(CONST.APPLEPAY_VAL);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).hide();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).prop("checked", false);
    } else if (isGooglePaySelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.GOOGLE_PAY_BUTTON).show();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    } else if (isLocalPaymentsSelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.LPM_BUTTONS).show();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).hide();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).prop("checked", false);
    } else if (isVenmoSelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.VENMO_BUTTON).show();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    } else if (isUsBankAccountSelected()) {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).show();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).show();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    } else if (isBrainTreeMethodSelected()){
        $(CONST.SRC_BUTTON).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.HOSTED_FIELDS).show();
        $(CONST.BILLING_ADDRESS_DATA).show();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).show();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).addClass(CONST.HEADLINE);
        $(CONST.PAYPAL_CMS_IMAGE_SELECTOR).addClass(CONST.DISABLE_CLICK);
        $(CONST.SELECT_PAYMENT).val("bt");
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    }else if (isSrcSelected()) {
        $(CONST.SRC_BUTTON).show();
        $(CONST.GOOGLE_PAY_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.CREADIT_CARD_LABEL_ID).removeClass(CONST.HEADLINE);
        $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).show();
    }else {
        $(CONST.SRC_BUTTON).hide();
        $(CONST.MARK_PAYPAL_BUTTON).hide();
        $(CONST.APPLE_PAY_BUTTON).hide();
        $(CONST.VENMO_BUTTON).hide();
        $(CONST.US_BANK_ACCOUNT_CONTAINER).hide();
        $(CONST.US_BANK_ACCOUNT_TEXT_AND_BUTTON_CONTAINER).hide();
        $(CONST.LPM_BUTTONS).hide();
        $(CONST.HOSTED_FIELDS).hide();
        $(CONST.BILLING_ADDRESS_DATA).hide();
        $(CONST.SUBMIT_CILENT_ORDER_POST_FORM_ID).hide();
        $(CONST.SAVE_PAYMENT_INFO_COMPONENT).hide();
        if (typeof addPaymentMethodsPage != 'undefined') {
            CONST.SAVE_PAYMENT_INFO_COMPONENT.hide();
        }
    }

    if (isMarkCheckoutPage()) {
        handleCheckoutCheckboxWithLimitation();
    }
}

function isApplePaySelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.APPLEPAY_VAL || $('input[name=onlyApplePaySelected]').val() === 'true';
}

function isBrainTreeMethodSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.BT_VAL;
}

function isPayPalMethodSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.PAYPAL_VAL || $('input[name=onlyPayPalSelected]').val() === 'true';
}

function isLocalPaymentsSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.LOCAL_PAYMENTS_VAL || $('input[name=onlyLocalPaymentsSelected]').val() === 'true';
}

function isVenmoSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.VENMO_VAL || $('input[name=onlyVenmoSelected]').val() === 'true';
}

function isUsBankAccountSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.US_BANK_ACCOUNT_VAL || $('input[name=onlyUsBankAccountSelected]').val() === 'true';
}

function isGooglePaySelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.GOOGLEPAY_VAL || $('input[name=onlyGooglePaySelected]').val() === 'true';
}

function isSrcSelected() {
    return $(CONST.PAYMENT_METHOD_SECTION_CHECKED).val() === CONST.SRC || $('input[name=onlySrcSelected]').val() === 'true';
}

function showGlobalErrorMessage(message) { // Show messages as GlobalMessages util (not pinned)
    $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
    var errorComponent = CONST.ERROR_DIV + message + HTML.DIV;
    $(CONST.GLOBAL_MESSAGES).append(errorComponent);
}

function showWarningMessage(message) {
    $(CONST.GLOBAL_MESSAGES).children(CONST.VALIDATION_CLASS).remove();
    var errorComponent = CONST.WARNING_DIV + message + HTML.DIV;
    $(CONST.GLOBAL_MESSAGES).append(errorComponent);
}

function showCustomAbsoluteErrorMessage(message) { // Show message pinned to the top of page
    $(CONST.SKIP_TO_CONTENT).empty();
    var errorComponent = $(HTML.DIV).attr(HTML.CLASS, CONST.ERROR_ALERT_CUSTOM);
    errorComponent.prepend(message);
    $(CONST.SKIP_TO_CONTENT).append(errorComponent);
    setTimeout(function () {
        $(CONST.SKIP_TO_CONTENT).empty();
    }, 7000);
}
function changeApplePayButtonShape(shape) {
    if (shape === 'squareCorners') {
        document.getElementById(CONST.APPLE_PAY_BUTTON_ID).style = 'border-radius: 0px';
    } else if (shape === 'pill-shaped') {
        document.getElementById(CONST.APPLE_PAY_BUTTON_ID).style = 'border-radius: 15px';
    }
}

function isMarkCheckoutPage(){
  return typeof paymentMethodsPage != 'undefined' && paymentMethodsPage !== '';
}

function isAccountPage(){
    return typeof accountPage !== 'undefined' && accountPage === 'accountAddPaymentMethodPage';
  }

function isShoppingCartPage(){
  return typeof shoppingCart != 'undefined' && shoppingCart !== '';
}
