/* Minification failed. Returning unminified contents.
(2713,6): run-time error JS1004: Expected ';'
(2731,25): run-time error JS1004: Expected ';'
(2735,25-31): run-time error JS1006: Expected ')': window
(2735,24): run-time error JS1004: Expected ';'
(2735,78): run-time error JS1004: Expected ';'
(2735,78-79): run-time error JS1195: Expected expression: )
(2735,79-80): run-time error JS1195: Expected expression: .
(2775,6): run-time error JS1004: Expected ';'
(2776,17-34): run-time error JS1006: Expected ')': isApplePayAllowed
(2776,17-34): run-time error JS1006: Expected ')': isApplePayAllowed
(2776,36): run-time error JS1004: Expected ';'
(2776,36-37): run-time error JS1195: Expected expression: )
(2776,37-38): run-time error JS1195: Expected expression: )
(2783,35): run-time error JS1004: Expected ';'
(2791,85-93): run-time error JS1006: Expected ')': function
(2791,96): run-time error JS1004: Expected ';'
(2805,10-11): run-time error JS1195: Expected expression: )
(2994,6): run-time error JS1004: Expected ';'
(2998,16-33): run-time error JS1006: Expected ')': isApplePayAllowed
(2998,16-33): run-time error JS1006: Expected ')': isApplePayAllowed
(2998,35): run-time error JS1004: Expected ';'
(2998,35-36): run-time error JS1195: Expected expression: )
(2998,37-39): run-time error JS1195: Expected expression: &&
(2998,74): run-time error JS1004: Expected ';'
(2998,74-75): run-time error JS1195: Expected expression: )
(3036,6): run-time error JS1004: Expected ';'
(3039,42): run-time error JS1004: Expected ';'
(3051,13-14): run-time error JS1005: Expected '(': {
(3052,30-31): run-time error JS1009: Expected '}': ;
(3052,30-31): run-time error JS1006: Expected ')': ;
(3052,30-31): run-time error JS1008: Expected '{': ;
(3064,6): run-time error JS1004: Expected ';'
(3066,64): run-time error JS1004: Expected ';'
(3178,6): run-time error JS1004: Expected ';'
(3184,50): run-time error JS1004: Expected ';'
(3237,6): run-time error JS1004: Expected ';'
(3255,37): run-time error JS1004: Expected ';'
(3261,6): run-time error JS1004: Expected ';'
(3274,40): run-time error JS1004: Expected ';'
(3278,19): run-time error JS1004: Expected ';'
(3289,43): run-time error JS1004: Expected ';'
(4164,21-22): run-time error JS1005: Expected '(': {
(4167,34-35): run-time error JS1009: Expected '}': ;
(4167,34-35): run-time error JS1006: Expected ')': ;
(4167,34-35): run-time error JS1008: Expected '{': ;
 */
// CountUp.js
var __assign = this && this.__assign || function () { return (__assign = Object.assign || function (t) { for (var i, a = 1, s = arguments.length; a < s; a++)for (var n in i = arguments[a]) Object.prototype.hasOwnProperty.call(i, n) && (t[n] = i[n]); return t }).apply(this, arguments) }, CountUp = function () { function t(t, i, a) { var s = this; this.target = t, this.endVal = i, this.options = a, this.version = "2.0.8", this.defaults = { startVal: 0, decimalPlaces: 0, duration: 2, useEasing: !0, useGrouping: !0, smartEasingThreshold: 999, smartEasingAmount: 333, separator: ",", decimal: ".", prefix: "", suffix: "" }, this.finalEndVal = null, this.useEasing = !0, this.countDown = !1, this.error = "", this.startVal = 0, this.paused = !0, this.count = function (t) { s.startTime || (s.startTime = t); var i = t - s.startTime; s.remaining = s.duration - i, s.useEasing ? s.countDown ? s.frameVal = s.startVal - s.easingFn(i, 0, s.startVal - s.endVal, s.duration) : s.frameVal = s.easingFn(i, s.startVal, s.endVal - s.startVal, s.duration) : s.countDown ? s.frameVal = s.startVal - (s.startVal - s.endVal) * (i / s.duration) : s.frameVal = s.startVal + (s.endVal - s.startVal) * (i / s.duration), s.countDown ? s.frameVal = s.frameVal < s.endVal ? s.endVal : s.frameVal : s.frameVal = s.frameVal > s.endVal ? s.endVal : s.frameVal, s.frameVal = Number(s.frameVal.toFixed(s.options.decimalPlaces)), s.printValue(s.frameVal), i < s.duration ? s.rAF = requestAnimationFrame(s.count) : null !== s.finalEndVal ? s.update(s.finalEndVal) : s.callback && s.callback() }, this.formatNumber = function (t) { var i, a, n, e, r = t < 0 ? "-" : ""; i = Math.abs(t).toFixed(s.options.decimalPlaces); var o = (i += "").split("."); if (a = o[0], n = o.length > 1 ? s.options.decimal + o[1] : "", s.options.useGrouping) { e = ""; for (var l = 0, h = a.length; l < h; ++l)0 !== l && l % 3 == 0 && (e = s.options.separator + e), e = a[h - l - 1] + e; a = e } return s.options.numerals && s.options.numerals.length && (a = a.replace(/[0-9]/g, function (t) { return s.options.numerals[+t] }), n = n.replace(/[0-9]/g, function (t) { return s.options.numerals[+t] })), r + s.options.prefix + a + n + s.options.suffix }, this.easeOutExpo = function (t, i, a, s) { return a * (1 - Math.pow(2, -10 * t / s)) * 1024 / 1023 + i }, this.options = __assign(__assign({}, this.defaults), a), this.formattingFn = this.options.formattingFn ? this.options.formattingFn : this.formatNumber, this.easingFn = this.options.easingFn ? this.options.easingFn : this.easeOutExpo, this.startVal = this.validateValue(this.options.startVal), this.frameVal = this.startVal, this.endVal = this.validateValue(i), this.options.decimalPlaces = Math.max(this.options.decimalPlaces), this.resetDuration(), this.options.separator = String(this.options.separator), this.useEasing = this.options.useEasing, "" === this.options.separator && (this.options.useGrouping = !1), this.el = "string" == typeof t ? document.getElementById(t) : t, this.el ? this.printValue(this.startVal) : this.error = "[CountUp] target is null or undefined" } return t.prototype.determineDirectionAndSmartEasing = function () { var t = this.finalEndVal ? this.finalEndVal : this.endVal; this.countDown = this.startVal > t; var i = t - this.startVal; if (Math.abs(i) > this.options.smartEasingThreshold) { this.finalEndVal = t; var a = this.countDown ? 1 : -1; this.endVal = t + a * this.options.smartEasingAmount, this.duration = this.duration / 2 } else this.endVal = t, this.finalEndVal = null; this.finalEndVal ? this.useEasing = !1 : this.useEasing = this.options.useEasing }, t.prototype.start = function (t) { this.error || (this.callback = t, this.duration > 0 ? (this.determineDirectionAndSmartEasing(), this.paused = !1, this.rAF = requestAnimationFrame(this.count)) : this.printValue(this.endVal)) }, t.prototype.pauseResume = function () { this.paused ? (this.startTime = null, this.duration = this.remaining, this.startVal = this.frameVal, this.determineDirectionAndSmartEasing(), this.rAF = requestAnimationFrame(this.count)) : cancelAnimationFrame(this.rAF), this.paused = !this.paused }, t.prototype.reset = function () { cancelAnimationFrame(this.rAF), this.paused = !0, this.resetDuration(), this.startVal = this.validateValue(this.options.startVal), this.frameVal = this.startVal, this.printValue(this.startVal) }, t.prototype.update = function (t) { cancelAnimationFrame(this.rAF), this.startTime = null, this.endVal = this.validateValue(t), this.endVal !== this.frameVal && (this.startVal = this.frameVal, this.finalEndVal || this.resetDuration(), this.finalEndVal = null, this.determineDirectionAndSmartEasing(), this.rAF = requestAnimationFrame(this.count)) }, t.prototype.printValue = function (t) { var i = this.formattingFn(t); "INPUT" === this.el.tagName ? this.el.value = i : "text" === this.el.tagName || "tspan" === this.el.tagName ? this.el.textContent = i : this.el.innerHTML = i }, t.prototype.ensureNumber = function (t) { return "number" == typeof t && !isNaN(t) }, t.prototype.validateValue = function (t) { var i = Number(t); return this.ensureNumber(i) ? i : (this.error = "[CountUp] invalid start or end value: " + t, null) }, t.prototype.resetDuration = function () { this.startTime = null, this.duration = 1e3 * Number(this.options.duration), this.remaining = this.duration }, t }();
//export{CountUp};;
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('.hidden-if-no-javascript').forEach(elem => {
        elem.classList.remove('hidden-if-no-javascript');
    })

    // Donation formsfunction movelabelup
    document.querySelector('.efundForm').addEventListener('submit', function () {
        preventDoubleSubmit(this);
    });
    // Popups
    //document.querySelectorAll('.modal').addEventListener('submit', '.popup-form', function () {
    //    popupPreventDoubleSubmit(this.closest('.efund-modal'));
    //});
    if (document.querySelector('#login-popup form')) {
        document.querySelector('#login-popup form').addEventListener('submit', function () {
            const parentModalElem = this.closest('.efund-modal');
            popupPreventDoubleSubmit(parentModalElem);
        });
    }

    // Dashboard panels
    document.querySelectorAll('.spinner-panel .reload-btn').forEach((reloadBtnElem) => {
        reloadBtnElem.addEventListener('click', function () {
            panelPreventDoubleSubmit(this);
        });
    });
    document.querySelectorAll('.spinner-panel form').forEach((form) => {
        form.addEventListener('submit', function () {
            panelPreventDoubleSubmit(this);
        });
    });

    setupSpammerCheck();
});

function setupSpammerCheck() {
    let intervalCount = 0,
        intervalMax = 10;
    let spamCheckInterval = window.setInterval(checkForSpammer, 1000);

    function checkForSpammer() {
        intervalCount++;
        if (intervalCount >= intervalMax) { window.clearInterval(spamCheckInterval); }

        if (isSpammer()) {
            document.querySelector('.g-recaptcha').remove();
            document.querySelector('.efund-recaptcha-wrapper').classList.add('captcha-blocked');
            window.clearInterval(spamCheckInterval);
        }
    }
}

function isHeroShotMultiPanel() {
    return document.getElementById('panelAmount');
}

function resetSubmit(formElem) {
    const buttonElem = document.getElementById('mainSubmit');
    // Enable button
    if (!document.getElementById('disableDonations')) {
        buttonElem.disabled = false;
    }
    // Hide spinner
    if (getBrowser() === "Edge") {
        buttonElem.style.display = 'block';
    } else {
        buttonElem.querySelector('.btn-text').style.display = 'block';
    }
    formElem.querySelector('.btn-spinner').classList.remove('show-spinner');
}
function preventDoubleSubmit(formElem) {
    const buttonElem = formElem.querySelector('#mainSubmit');
    // Disable button
    buttonElem.disabled = true;
    // Show spinner
    if (getBrowser() === "Internet Explorer" || getBrowser() === "Edge") {
        buttonElem.style.display = 'none';
    } else {
        buttonElem.querySelector('.btn-text').style.display = 'none';
    }
    formElem.querySelector('.btn-spinner').classList.add('show-spinner');
}
function popupPreventDoubleSubmit(popupElem) {
    // Disable button
    if (popupElem.querySelector('input[type="submit"]')) {
        popupElem.querySelector('input[type="submit"]').disabled = true;
    }
    if (popupElem.querySelector('button[type="submit"]')) {
        popupElem.querySelector('button[type="submit"]').disabled = true;
    }
    // Show spinner
    popupElem.querySelector('.popup-spinner').classList.add('show-spinner');
}

function popupResetSubmit(popupElem) {
    // Disable button
    popupElem.querySelector('input[type="submit"]').disabled = false;
    // Show spinner
    popupElem.querySelector('.popup-spinner').classList.remove('show-spinner');
}
function panelPreventDoubleSubmit(btnElem) {
    // Disable all buttons
    var panelElem = btnElem.closest('.panel');
    if (panelElem) {
        panelElem.querySelectorAll('.reload-btn').forEach((btn) => {
            btn.disabled = true;
        });
        panelElem.querySelectorAll('.dash-btn').forEach((btn) => {
            btn.disabled = true;
        });
        // Show spinner
        panelElem.querySelector('.popup-spinner').classList.add('show-spinner');
    }
}

// Force page to reload when page is returned to via "Back" button
window.addEventListener("pageshow", function (event) {
    var historyTraversal = event.persisted ||
        (typeof window.performance != "undefined" &&
            window.performance.navigation.type === 2);
    if (historyTraversal) {
        // Handle page restore.
        window.location.reload();
    }
});

function changeModalView(viewIdWithHash) {
    const viewId = viewIdWithHash.slice(1);
    var nextViewElem = document.getElementById(viewId);
    var allViewElems = document.querySelectorAll('.popup-view-container');
    allViewElems.forEach((viewElem) => {
        viewElem.classList.remove('show');
    });
    nextViewElem.classList.add('show');
}

function createResendConfirmEmailSubmit() {
    if (document.getElementById('ResendConfirmEmailForm')) {
        document.getElementById('ResendConfirmEmailForm').addEventListener('submit', function (e) {
            e.preventDefault();
            var data = serializeForm(this);

            var url = this.action;
            popupPreventDoubleSubmit(this.closest('.efund-modal'));

            // AJAX
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: data
            })
                .then((response) => {
                    return response.text().then(function (text) {
                        document.getElementById('resendConfirmEmail-popup').innerHTML = text;
                        createForgotPasswordSubmit();
                        popupResetSubmit(document.getElementById('resendConfirmEmail-popup').closest('.efund-modal'));
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        });
    }
}

function createForgotPasswordSubmit() {
    if (document.getElementById('ForgotPasswordForm')) {
        document.getElementById('ForgotPasswordForm').addEventListener('submit', function (e) {
            e.preventDefault();
            var data = serializeForm(this);

            var url = this.action;
            popupPreventDoubleSubmit(this.closest('.efund-modal'));

            // AJAX
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: data
            })
                .then((response) => {
                    return response.text().then(function (text) {
                        document.getElementById('forgotPassword-popup').innerHTML = text;
                        createForgotPasswordSubmit();
                        popupResetSubmit(document.getElementById('forgotPassword-popup').closest('.efund-modal'));
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        });
    }
}

//Set up One Click popups
document.addEventListener("DOMContentLoaded", function () {
    // Login loading
    if (document.getElementById('loginErrors')) {
        //document.getElementById('modal-oneclick-container').modal('show');
        const modalOneClick = new bootstrap.Modal(document.getElementById('modal-oneclick-container'), {});
        modalOneClick.show();
        changeModalView(document.querySelector('.one-click-login').getAttribute('data-view-target'));
    }
    // Change Popup View
    document.querySelectorAll('.one-click-login, .modal-btn').forEach((btnElem) => {
        btnElem.addEventListener('click', function () {
            changeModalView(this.getAttribute('data-view-target'));
        });
    });
    if (document.getElementById('modal-oneclick-container')) {
        document.getElementById('modal-oneclick-container').addEventListener('click', function (event) {
            var element = event.target;
            if (element.classList.contains('btn-change-popup')) {
                changeModalView(element.getAttribute('data-view-target'));
            } else if (element.parentNode.classList.contains('btn-change-popup')) {
                changeModalView(element.parentNode.getAttribute('data-view-target'));
            }
        });
    }

    //document.querySelector('.btn-change-popup').addEventListener('click', function () {
    //    changeModalView(this);
    //});

    // Prevent mouseup on popup background from closing popup
    addModalLock();
    document.querySelectorAll('.modal-dialog').forEach((modalDialogElem) => {
        modalDialogElem.addEventListener('mousedown', function () {
            //this.parent('.modal').modal('lock');
            const modal = new bootstrap.Modal(this.closest('.modal'), {});
            modal.lock();
        });
    });
    document.querySelectorAll('.modal-dialog').forEach((modalDialogElem) => {
        modalDialogElem.addEventListener('mouseup', function () {
            //this.parent('.modal').modal('unlock');
            const modal = new bootstrap.Modal(this.closest('.modal'), {});
            modal.unlock();
        });
    });
    document.querySelectorAll('.modal').forEach((modalElem) => {
        modalElem.addEventListener('mousedown', function (e) {
            if (e.target !== this) {
                return;
            }
            //this.modal('unlock');
            const modal = new bootstrap.Modal(this, {});
            modal.unlock();
        });
    });

    createForgotPasswordSubmit();

    createResendConfirmEmailSubmit();

    //Popup closing
    if (document.getElementById('modal-login-container')) {
        document.getElementById('modal-login-container').addEventListener('d-none.bs.modal', function () {
            resetFieldAndLabel(document.getElementById('LoginEmail'));
            resetFieldAndLabel(document.getElementById('LoginPassword'));
        });
    }

});

function setupSelectedPaymentOption(amountElem) {
    // Highlight Amounts
    document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
        const amountValue = amountElem.value;
        if (amountValue && (amountValue != '0') && (parseFloat(amountValue) === parseFloat(paymentOptionItemElem.getAttribute('data-amount')))) {
            document.querySelectorAll('.efund_PaymentOptionItem').forEach((otherPaymentOptionItemElem) => {
                otherPaymentOptionItemElem.classList.remove("selectedOption");
            });
            paymentOptionItemElem.classList.add("selectedOption");

            document.getElementById('OtherAmount').value = '';
            document.getElementById('OtherAmount').parentNode.querySelector('label').classList.remove('moveUp');

            if (document.getElementById('CoverFee')) {
                updateCoverFeeLabel(amountElem.value);
            }
            //showPaypalButton();
        }
    });
}

function setupSelectedOtherAmount(amountElem) {
    if (document.getElementById('OtherAmount')) {
        const otherAmountValue = document.getElementById('OtherAmount').value;
        if (otherAmountValue && (otherAmountValue != '0')) {
            document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
                paymentOptionItemElem.classList.remove("selectedOption");
            });
            //showPaypalButton();
        }
    }
}

//Things to do on start up
document.addEventListener("DOMContentLoaded", function () {
    //Set the Cover Fee label on startup
    if (document.getElementById('CoverFee')) {
        updateCoverFeeLabel(0);
    }

    //Click PaymentOption or fill Other Amount
    const amountElem = document.getElementById('Amount');
    setupSelectedOtherAmount(amountElem);
    setupSelectedPaymentOption(amountElem);
    if (amountElem) {
        updateTotalAmount(amountElem.value);
    }
    updateRequireAmount();
    if (document.getElementById('btnPayPal')) {
        resetPayPalContainer();
    }
    //Implement startsWith for IE
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }

    //Replace loading icons with gifs for IE and Edge
    if (getBrowser() === "Edge") {
        document.querySelectorAll('.popup-spinner').forEach((popupSpinnerElem) => {
            popupSpinnerElem.querySelector('img').setAttribute('src', '/images/loading/spinner-green-48.gif');
        });
        document.querySelectorAll('.btn-spinner').forEach((btnSpinnerElem) => {
            const formGroupElem = btnSpinnerElem.closest('.efund-form-group');
            formGroupElem.appendChild(btnSpinnerElem);
            btnSpinnerElem.classList.add('spinner-ie');
            btnSpinnerElem.querySelector('img').setAttribute('src', '/images/loading/spinner-gray-32.gif');
        });
    }

    // Set Credit Card pattern to Amex if Credit Card is Amex
    if (document.getElementById('CCNumber') && document.getElementById('CCNumber').value !== undefined && document.getElementById('CCNumber').value.startsWith('37')) {
        document.getElementById('CCNumber').setAttribute('pattern', '[0-9 ]{17}');

        document.getElementById('CCSecurity').setAttribute('placeholder', '•'.repeat(4));
        document.getElementById('CCSecurity').setAttribute('pattern', '[0-9]{4}');

    }

    // Update decoy address
    updateDecoyAddress();

    //Person type (Individiual, Company, Couple)

    //Set Retired to checked if checked
    if (document.getElementById('Retired') && document.getElementById('Retired').checked
        || ((document.querySelector('#donor-dashboard #Employer')
            && document.querySelector('#donor-dashboard #Employer').value === 'Retired'))) {

        document.querySelectorAll('.retired-toggle').forEach((retiredToggleElem) => {
            retiredToggleElem.style.display = 'none';
        });
        forceEmploymentRequired(false);
        if (document.getElementById('btn-retired-col')) {
            document.getElementById('btn-retired-col').classList.add('full-width');
        }
        document.querySelector("label[for='Retired']").classList.add('selected');
    }

    //Set Retired Other to checked if checked
    if (document.getElementById('RetiredOther') && document.getElementById('RetiredOther').checked) {
        document.querySelectorAll('.retired-toggle-other').forEach((retiredToggleOtherElem) => {
            retiredToggleOtherElem.style.display = 'none';
        });
        forceEmploymentOtherRequired(false);
        document.getElementById('btn-retired-col-other').classList.add('full-width');
        document.querySelector("label[for='RetiredOther']").classList.add('selected');
    }

    //Check confirmation box
    if (document.getElementById('DisclaimerAgree') && document.getElementById('DisclaimerAgree').checked) {
        document.querySelector("label[for='DisclaimerAgree']").classList.add('selected');
    }

    //Check Attending event box
    if (document.getElementById('AttendingEvent') && document.getElementById('AttendingEvent').checked) {
        document.querySelector("label[for='AttendingEvent']").classList.add('selected');
    }

    //Check additional checkboxes (yeah... no)

    // Disable 'disabled' <a> tags
    document.querySelectorAll('a.disabled').forEach((disabledLinkElem) => {
        disabledLinkElem.addEventListener('click', function (e) {
            e.preventDefault();
        });
    });

    //Fill in Phone
    let phone = document.getElementById('Phone').value;
    if (phone !== '') {
        document.getElementById('Phone').dispatchEvent(new Event('input'));
    }

    //Fill in Custom fields order
    if (document.getElementById('CustomFieldsOrder')) {
        document.getElementById('CustomFieldsOrder').value = (document.getElementById('CustomFieldsOrder').getAttribute('data-order'));
    }

    //Fill in Custom fields preset value
    document.querySelectorAll('input[data-fill-value]').forEach((inputElem) => {
        if (inputElem.value === '') {
            inputElem.value = (inputElem.getAttribute('data-fill-value'));
        }
    });

    //Fill in custom checkboxes values from SelectedQuestions hidden fields
    if (document.querySelector('.selected-question-field-value')) {
        document.querySelectorAll('.selected-question-field-value').forEach((inputElem) => {
            const checkboxIndex = parseInt(inputElem.value),
                checkboxElems = document.querySelectorAll('.selected-question-field-display');
            if (Number.isInteger(checkboxIndex) && checkboxIndex < checkboxElems.length) {
                const checkboxElem = checkboxElems[checkboxIndex];
                checkboxElem.checked = true;
                checkboxElem.dispatchEvent(new Event('change'));
            }
        });
    }


    //Handle started up Payment Methods
    if (document.getElementById('PreselectACH') && document.getElementById('PreselectACH').value === 'True') {
        handleACHClick();
    }

    //Reset ACH value (Work around >:( )
    if (document.getElementById('BraintreeNonce')) {
        document.getElementById('BraintreeNonce').value = '';
    }

    // Handle Braintree errors
    const serverErrorElem = document.querySelector('.eFund_ErrorMessage');
    if (serverErrorElem) {
        const serverErrorMsg = serverErrorElem.innerHTML;
        switch (serverErrorMsg) {
            case "The zip code you provided does not match the credit card's reported address.":
                // Zip errors
                addInputErrorMessage('CCZip', serverErrorMsg);
                break;
            case "Card Issuer Declined CVV":
                // CVV errors
                addInputErrorMessage('CCSecurity', serverErrorMsg);
                break;
            case "Merchant account does not support payment instrument.":
                // Credit card number errors
                addInputErrorMessage('CCNumber', serverErrorMsg);
                break;
        }
    }

    function addInputErrorMessage(inputId, msg) {
        const inputElem = document.getElementById(inputId);

        inputElem.setAttribute('data-validate', 'fail');
        inputElem.setAttribute('data-validate-message', msg);
        updateInputValidationStyle(inputElem);
    }

});


// Extend Bootstrap modal object to include lock and unlock options 
function addModalLock() {
    // save the original function object
    var _superModal = bootstrap.Modal;

    // add locked as a new option
    //$.extend(_superModal.Default, {
    //    locked: false
    //});
    _superModal.Default.locked = false;

    // capture the original hide
    var _hide = _superModal.prototype.hide;

    // add the lock, unlock and override the hide of modal
    //$.extend(_superModal.prototype, {
    //    // locks the dialog so that it cannot be hidden
    //    lock: function () {
    //        this._config.locked = true;
    //    },
    //    // unlocks the dialog so that it can be hidden by 'esc' or clicking on the backdrop (if not static)
    //    unlock: function () {
    //        this._config.locked = false;
    //    },
    //    // override the original hide so that the original is only called if the modal is unlocked
    //    hide: function () {
    //        if (this._config.locked) return;

    //        _hide.apply(this, arguments);
    //    }
    //});
    _superModal.prototype.lock = function () {
        this._config.locked = true;
    };
    _superModal.prototype.unlock = function () {
        this._config.locked = false;
    };
    _superModal.prototype.hide = function () {
        if (this._config.locked) return;
        _hide.apply(this, arguments);
    };
}
function resetFieldAndLabel(fieldElem) {
    fieldElem.value = "";
    fieldElem.classList.remove("valid");
    fieldElem.parentNode.querySelector('label').classList.remove('moveUp');
}

function resetFieldToSpecificValue(fieldElem, value) {
    fieldElem.value = value;
    fieldElem.classList.remove("valid");
}

// label adjuster
document.addEventListener("DOMContentLoaded", function () {
    moveAllLabelsUp();
    document.querySelectorAll('input, textarea, select').forEach((fieldElem) => {
        fieldElem.addEventListener('focus', function () {
            if (this.parentNode.querySelector('label')) {
                this.parentNode.querySelector('label').classList.add('moveUp');
            }
        });
    });
    document.querySelectorAll('input, textarea, select').forEach((fieldElem) => {
        fieldElem.addEventListener('change', function () {
            moveLabelUp(this);
        });
    });
    document.querySelectorAll('input, textarea, select').forEach((fieldElem) => {
        fieldElem.addEventListener('focusout', function () {
            if (!this.value) {
                var domFieldElem = document.getElementById(this.id);
                if (domFieldElem.parentNode.querySelector('label')) {
                    domFieldElem.parentNode.querySelector('label').classList.remove('moveUp');
                }
            }
        });
    });
    document.querySelectorAll('.modal').forEach((modalElem) => {
        modalElem.addEventListener('focus', function (event) {
            var element = event.target;
            if (element.tagName == 'INPUT') {
                element.parentNode.querySelector('label').classList.add('moveUp');
            }
        });
    });
    document.querySelectorAll('.modal').forEach((modalElem) => {
        function resetModalInputLabels(event) {
            var element = event.target;
            if (element.tagName == 'INPUT') {
                if (element != document.activeElement && !element.value) {
                    element.parentNode.querySelector('label').classList.remove('moveUp');
                }
            }
        }
        modalElem.addEventListener('blur', resetModalInputLabels);
        modalElem.addEventListener('input', resetModalInputLabels);
    });
});

function moveLabelUp(inputElem) {
    var val = inputElem.value.trim();
    if (val.length > 0) {
        var labelElem = inputElem.parentNode.querySelector('label');
        if (labelElem && (labelElem.getAttribute('for') === inputElem.getAttribute('id'))) {
            labelElem.classList.add('moveUp');
        }
    }
}
function moveAllLabelsUp() {
    document.querySelectorAll('textarea.form-control, input.form-control').forEach((fieldElem) => {
        moveLabelUp(fieldElem);
    });
}

function handleCompanyClick() {
    document.getElementById('panelFirstLastName').style.display = 'none';
    if (document.getElementById('panelOtherName')) {
        document.getElementById('panelOtherName').style.display = 'none';
    }
    if (document.getElementById('panelEmployOcc')) {
        document.getElementById('panelEmployOcc').style.display = 'none';
    }
    if (document.getElementById('panelOtherEmployer')) {
        document.getElementById('panelOtherEmployer').style.display = 'none';
    }
    if (document.getElementById('panelEmployerLocation')) {
        document.getElementById('panelEmployerLocation').style.display = 'none';
    }
    if (document.getElementById('panelEmployerLocationOther')) {
        document.getElementById('panelEmployerLocationOther').style.display = 'none';
    }
    fadeIn(document.getElementById('panelCompanyName'), 'fast');
    if (document.querySelector('.two-contributor-title')) {
        document.querySelectorAll('.two-contributor-title').forEach((twoContributorTitleElem) => {
            twoContributorTitleElem.style.display = 'none';
        });
    }
    document.getElementById('CompanyDonation').value = 't';
    if (document.getElementById('SecondDonation')) {
        document.getElementById('SecondDonation').value = 'f';
    }
    document.getElementById('btnCompany').disabled = true;
    document.getElementById('btnPersonal').disabled = false;
    if (document.getElementById('btnSecond')) {
        document.getElementById('btnSecond').disabled = false;
    }
    document.getElementById('NameFirst').required = false;
    document.getElementById('NameLast').required = false;
    document.getElementById('NameCompany').required = true;
    if (document.getElementById('NameFirstOther')) {
        document.getElementById('NameFirstOther').required = false;
    }
    if (document.getElementById('NameLastOther')) {
        document.getElementById('NameLastOther').required = false;
    }
    if (document.getElementById('CompanyType')) {
        document.getElementById('CompanyType').required = true;
        updatePAC_IDRequirement(true);
    }
    if (document.getElementById('AuthAgentFirstName')) {
        updateAuthAgentRequirement(true);
    }
    if (document.getElementById('CompanyDisclaimerAgree')) {
        document.getElementById('CompanyDisclaimerAgree').required = true;
    }
    setEmploymentRequired(false);
    setEmploymentOtherRequired(false);
    document.getElementById('CCAddressDifferent').textContent = ("My credit card address is different than my business address.");
    //New
    if (document.getElementById('AddressTitle')) {
        document.getElementById('AddressTitle').textContent = ('Company address');
    }
    updateMaxAmountAndValidations();
    if (document.getElementById('CoverFee')) {
        validateCoverFee();
    }
    handleHeroShotMaxAmountValidation();

    checkCoupleDecimalAmountValidation(document.getElementById('Amount').value);
}

function handleIndividualClick() {
    fadeIn(document.getElementById('panelFirstLastName'), 'fast');
    if (document.getElementById('panelOtherName')) {
        document.getElementById('panelOtherName').style.display = 'none';
    }
    if (document.getElementById('panelEmployOcc')) {
        fadeIn(document.getElementById('panelEmployOcc'), 'fast');
    }
    if (document.getElementById('panelEmployerLocation')) {
        fadeIn(document.getElementById('panelEmployerLocation'), 'fast');
    }
    if (document.getElementById('panelOtherEmployer')) {
        document.getElementById('panelOtherEmployer').style.display = 'none';
    }
    if (document.getElementById('panelEmployerLocationOther')) {
        document.getElementById('panelEmployerLocationOther').style.display = 'none';
    }
    if (document.getElementById('panelCompanyName')) {
        document.getElementById('panelCompanyName').style.display = 'none';
    }
    if (document.querySelector('.two-contributor-title')) {
        document.querySelectorAll('.two-contributor-title').forEach((twoContributorTitleElem) => {
            twoContributorTitleElem.style.display = 'none';
        });
    }
    if (document.getElementById('CompanyDonation')) {
        document.getElementById('CompanyDonation').value = 'f';
    }
    if (document.getElementById('SecondDonation')) {
        document.getElementById('SecondDonation').value = 'f';
    }
    if (document.getElementById('btnCompany')) {
        document.getElementById('btnCompany').disabled = false;
    }
    if (document.getElementById('btnSecond')) {
        document.getElementById('btnSecond').disabled = false;
    }
    if (document.getElementById('NameCompany')) {
        document.getElementById('NameCompany').required = false;
    }
    if (document.getElementById('NameFirstOther')) {
        document.getElementById('NameFirstOther').required = false;
    }
    if (document.getElementById('NameLastOther')) {
        document.getElementById('NameLastOther').required = false;
    }
    if (document.getElementById('CompanyType')) {
        document.getElementById('CompanyType').required = false;
        updatePAC_IDRequirement(false);
    }
    if (document.getElementById('AuthAgentFirstName')) {
        updateAuthAgentRequirement(false);
    }
    if (document.getElementById('CompanyDisclaimerAgree')) {
        document.getElementById('CompanyDisclaimerAgree').required = false;
    }

    if (document.getElementById('btnPersonal')) {
        document.getElementById('btnPersonal').disabled = true;
    }
    if (document.getElementById('NameFirst')) {
        document.getElementById('NameFirst').required = true;
    }
    if (document.getElementById('NameLast')) {
        document.getElementById('NameLast').required = true;
    }
    if (document.getElementById('CCAddressDifferent')) {
        document.getElementById('CCAddressDifferent').textContent = ("My credit card address is different than my home address.");
    }

    // Occupation/Employer Required Amount
    if (isOccupationRequired()) {
        setEmploymentRequired(true);
    }
    else {
        setEmploymentRequired(false);
    }
    setEmploymentOtherRequired(false);
    //New
    if (document.getElementById('hdnAddressTitle') && document.getElementById('AddressTitle')) {
        document.getElementById('AddressTitle').textContent = (document.getElementById('hdnAddressTitle').value);
    }
    updateMaxAmountAndValidations();
    if (document.getElementById('CoverFee')) {
        validateCoverFee();
    }
    handleHeroShotMaxAmountValidation();

    checkCoupleDecimalAmountValidation(document.getElementById('Amount').value);
}

function updateAuthAgentRequirement(companyVisible) {

    let AuthAgentLastName = document.getElementById('AuthAgentLastName');
    let AuthAgentFirstName = document.getElementById('AuthAgentFirstName');

    if (!(AuthAgentLastName && AuthAgentFirstName)) {
        return;
    }

    let requirementType = document.getElementById('panelAuthAgentCondition').textContent.trim();

    if (requirementType === "LLC") {

        let CompanyTypeElement = document.getElementById('CompanyType');
        let isLLC = true;
        if (CompanyTypeElement) {
            isLLC = CompanyTypeElement.value === "LLC";
        }

        AuthAgentLastName.required = isLLC && companyVisible;
        AuthAgentFirstName.required = isLLC && companyVisible;

        if (companyVisible) {
            if (isLLC) {
                fadeIn(document.getElementById('panelAuthAgent'), 'fast');
                fadeIn(document.getElementById('AuthAgentFirstName'), 'fast');
                fadeIn(document.getElementById('AuthAgentLastName'), 'fast');
            } else {
                fadeOut(document.getElementById('panelAuthAgent'), 'fast');
                fadeOut(document.getElementById('AuthAgentFirstName'), 'fast');
                fadeOut(document.getElementById('AuthAgentLastName'), 'fast');
            }
        }
    }
    else {
        AuthAgentLastName.required = companyVisible;
        AuthAgentFirstName.required = companyVisible;
    }
}

function updatePAC_IDRequirement(companyVisible) {

    let PAC_ID = document.getElementById('PAC_ID');

    if (!PAC_ID) {
        return;
    }

    let CompanyTypeElement = document.getElementById('CompanyType');
    let isPAC = true;
    if (CompanyTypeElement) {
        isPAC = CompanyTypeElement.value === "PAC";
    }

    PAC_ID.required = isPAC && companyVisible;

    if (companyVisible) {
        if (isPAC) {
            fadeIn(document.getElementById('panelPAC_ID'), 'fast');
            fadeIn(PAC_ID, 'fast');
        } else {
            fadeOut(document.getElementById('panelPAC_ID'), 'fast');
            fadeOut(PAC_ID, 'fast');
        }
    }
}

function isOccupationRequired() {
    return document.getElementById('Occupation') &&
        isEmploymentPanelVisible() &&
        doesAmountExceedOccupationMin();
}

function isEmploymentPanelVisible() {
    return document.getElementById('panelEmployOcc') && getComputedStyle(document.getElementById('panelEmployOcc')).getPropertyValue('display') !== 'none';
}

function doesAmountExceedOccupationMin() {
    return getTotalWithIterations() >= getOccupationMin();
}

function getOccupationMin() {
    return document.getElementById('Occupation').hasAttribute('requireamount') ?
        parseFloat(document.getElementById('Occupation').getAttribute('requireamount')) :
        0.0;
}

function handleCoupleClick() {
    if (document.getElementById('panelEmployOcc')) {
        fadeIn(document.getElementById('panelEmployOcc'), 'fast');
    }
    if (document.getElementById('panelOtherEmployer')) {
        fadeIn(document.getElementById('panelOtherEmployer'), 'fast');
    }
    if (document.querySelector('.two-contributor-title')) {
        document.querySelectorAll('.two-contributor-title').forEach((twoContributorTitleElem) => {
            fadeIn(twoContributorTitleElem, 'fast');
        });
    }
    if (document.getElementById('panelCompanyName')) {
        document.getElementById('panelCompanyName').style.display = 'none';
    }
    if (document.getElementById('CompanyDonation')) {
        document.getElementById('CompanyDonation').value = 'f';
    }
    if (document.getElementById('btnCompany')) {
        document.getElementById('btnCompany').disabled = false;
    }
    if (document.getElementById('NameCompany')) {
        document.getElementById('NameCompany').required = false;
    }
    if (document.getElementById('CompanyType')) {
        document.getElementById('CompanyType').required = false;
        updatePAC_IDRequirement(false);
    }
    if (document.getElementById('AuthAgentFirstName')) {
        updateAuthAgentRequirement(false);
    }
    if (document.getElementById('CompanyDisclaimerAgree')) {
        document.getElementById('CompanyDisclaimerAgree').required = false;
    }
    fadeIn(document.getElementById('panelFirstLastName'), 'fast');
    fadeIn(document.getElementById('panelOtherName'), 'fast');
    document.getElementById('SecondDonation').value = 't';
    document.getElementById('btnPersonal').disabled = false;
    document.getElementById('btnSecond').disabled = true;
    document.getElementById('NameFirst').required = true;
    document.getElementById('NameLast').required = true;
    document.getElementById('NameFirstOther').required = true;
    document.getElementById('NameLastOther').required = true;
    document.getElementById('CCAddressDifferent').textContent = ("My credit card address is different than my home address.");
    // Occupation/Employer Required Amount
    if (isOccupationRequired()) {
        setEmploymentRequired(true);
        setEmploymentOtherRequired(true);
    }
    else {
        setEmploymentRequired(false);
        setEmploymentOtherRequired(false);
    }
    //New
    if (document.getElementById('hdnAddressTitle') && document.getElementById('AddressTitle')) {
        document.getElementById('AddressTitle').textContent = (document.getElementById('hdnAddressTitle').value);
    }

    updateMaxAmountAndValidations();
    if (document.getElementById('CoverFee')) {
        validateCoverFee();
    }

    //For HeroShot :(
    handleHeroShotMaxAmountValidation();

    checkCoupleDecimalAmountValidation(document.getElementById('Amount').value);
}

function handleHeroShotMaxAmountValidation() {
    if (document.getElementById('amount-error')) {
        if (doesExceedMaxWithIterations()) {
            document.getElementById('amount-error').style.display = 'block';
        } else {
            document.getElementById('amount-error').style.display = 'none';
        }
    }
}

function doesExceedMaxWithIterations() {
    return getTotalWithIterations() > getAccountMax();
}

function getTotalWithIterations() {
    let iterations = getIterations(),
        totalOneTimeAmount = parseFloat(document.getElementById('Amount').value);

    if (document.getElementById('GiveAmount') && document.getElementById('GiveAmount').value != '') {
        const amountExcludingMerch = parseFloat(document.getElementById('GiveAmount').value) || 0;
        return amountExcludingMerch * (iterations - 1) + totalOneTimeAmount;
    } else {
        return totalOneTimeAmount * iterations;
    }
}

function getIterations() {
    if (!document.getElementById('Iterations')) {
        return 1;
    }

    return document.getElementById('Iterations').value > 1 ?
        parseInt(document.getElementById('Iterations').value) :
        1;
}

function updateMaxAmountAndValidations() {
    updateAccountMax();
    updateMaxMessages();
    validateOtherAmountMax();
}

function updateMaxMessages() {
    let max = getAccountMax().toFixed(2);
    let min = getAccountMin().toFixed(2);
    let replacement = '';

    if (document.getElementById('coupleMaxOverride')) {
        let validate34 = document.getElementById('trans-validate34').getAttribute('translate-base');
        if (validate34 !== undefined && validate34 !== null && validate34 !== "") {
            let replacement = validate34.replace('{data-translate-1}', min).replace('{data-translate-2}', max);
            document.getElementById('trans-validate34').innerHTML = (replacement);
        }
    } else {
        let validate8 = document.getElementById('trans-validate8').getAttribute('translate-base');
        if (validate8 !== undefined && validate8 !== null && validate8 !== "") {
            let replacement = validate8.replace('{data-translate-1}', min).replace('{data-translate-2}', max);
            document.getElementById('trans-validate8').innerHTML = (replacement);
        }
    }
    if (replacement != '') {
        document.getElementById('OtherAmount').setAttribute('title', replacement);
    }

    updateMaxMessage(document.getElementById('trans-validate-11'));
    updateMaxMessage(document.getElementById('trans-validate-21'));
    //Applies to 24 as well
    updateMaxMessage(document.getElementById('total-amount-max-error'));
    updateMaxMessage(document.getElementById('cover-fee-error'));
    updateMaxMessage(document.getElementById('amount-error'));
}

function updateMaxMessage(messageElem) {
    if (messageElem) {
        let max = getAccountMax().toFixed(2);
        let validation = messageElem.getAttribute('translate-base');
        if (validation !== undefined && validation !== null && validation !== "") {
            messageElem.innerHTML = (validation.replace('{data-translate-1}', max));
        }
    }
}

function validateOtherAmountMax() {
    if (document.querySelector('.efundForm')) {
        let amountElem = document.getElementById('OtherAmount');
        validateInput(amountElem);
        updateInputValidationStyle(amountElem);
        document.getElementById('Amount').dispatchEvent(new Event('change'));
        if (document.getElementById('CoverFee')) {
            validateCoverFee();
        }
    }
}

// Donation Person Type
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('.two-contributor-title').forEach((twoContributorTitleElem) => {
        twoContributorTitleElem.style.display = 'none';
    });
    if (document.getElementById('AddressTitle')) {
        document.getElementById('hdnAddressTitle').value = (document.getElementById('AddressTitle').textContent);
    }
    if (document.getElementById('btnCompany')) {
        document.getElementById('btnCompany').addEventListener('click', function () {
            handleCompanyClick();
        });
        if (document.getElementById('CompanyType')) {
            document.getElementById('CompanyType').addEventListener('change', function () {
                updateAuthAgentRequirement(true);
                updatePAC_IDRequirement(true);
            });
        }
    }
    if (document.getElementById('btnPersonal')) {
        document.getElementById('btnPersonal').addEventListener('click', function () {
            handleIndividualClick();
        });
    }
    if (document.getElementById('btnSecond')) {
        document.getElementById('btnSecond').addEventListener('click', function () {
            handleCoupleClick();
        });
    }
});

// This doesn't make any sense, so replaced with document loaded listener: -Alex 2/15
//document.querySelectorAll('.efund_choice').forEach((efundChoiceElem) => {
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('CompanyDonation') && document.getElementById('CompanyDonation').value == 't') {
        document.getElementById('btnCompany').disabled = true;
        document.getElementById('panelFirstLastName').style.display = 'none';
        document.getElementById('panelOtherName').style.display = 'none';
        document.getElementById('panelEmployOcc').style.display = 'none';
        document.getElementById('panelOtherEmployer').style.display = 'none';
        fadeIn(document.getElementById('panelCompanyName'), 'fast');
        document.getElementById('NameFirst').required = false;
        document.getElementById('NameLast').required = false;
        updatePAC_IDRequirement(true);
        updateAuthAgentRequirement(true);
        setEmploymentRequired(false);
        document.getElementById('NameCompany').required = true;
    }
    else if (document.getElementById('SecondDonation') && document.getElementById('SecondDonation').value == 't') {
        document.getElementById('btnSecond').disabled = true;
        fadeIn(document.getElementById('panelFirstLastName'), 'fast');
        fadeIn(document.getElementById('panelOtherName'), 'fast');
        fadeIn(document.getElementById('panelEmployOcc'), 'fast');
        fadeIn(document.getElementById('panelOtherEmployer'), 'fast');
        document.getElementById('panelCompanyName').style.display = 'none';
        document.getElementById('NameFirst').required = true;
        document.getElementById('NameLast').required = true;
        document.getElementById('NameFirstOther').required = true;
        document.getElementById('NameLastOther').required = true;
        updatePAC_IDRequirement(false);
        updateAuthAgentRequirement(false);
        if (!document.getElementById('RetiredOther').checked) {
            if (isOccupationRequired()) {
                setEmploymentOtherRequired(true);
            }
            else {
                setEmploymentOtherRequired(false);
            }
        }
    }
    else {
        updatePAC_IDRequirement(false);
        updateAuthAgentRequirement(false);
        if (document.getElementById('btnPersonal')) {
            document.getElementById('btnPersonal').disabled = true;
        }
        document.getElementById('NameFirst').required = true;
        document.getElementById('NameLast').required = true;
    }
});

// Monthly Donation
function HideRecurringMessages() {
    if (document.getElementById('weeklyMessage')) {
        document.getElementById('weeklyMessage').style.display = 'none';
    }
    if (document.getElementById('monthlyMessage')) {
        document.getElementById('monthlyMessage').style.display = 'none';
    }
    if (document.getElementById('quarterlyMessage')) {
        document.getElementById('quarterlyMessage').style.display = 'none';
    }
    if (document.getElementById('annuallyMessage')) {
        document.getElementById('annuallyMessage').style.display = 'none';
    }
}

function DisableRecurringOptions() {
    if (document.getElementById('btnOneTime')) {
        document.getElementById('btnOneTime').disabled = false;
    }
    if (document.getElementById('btnWeekly')) {
        document.getElementById('btnWeekly').disabled = false;
    }
    if (document.getElementById('btnMonthly')) {
        document.getElementById('btnMonthly').disabled = false;
    }
    if (document.getElementById('btnQuarterly')) {
        document.getElementById('btnQuarterly').disabled = false;
    }
    if (document.getElementById('btnAnnually')) {
        document.getElementById('btnAnnually').disabled = false;
    }
}

function HandleOneTimeClick() {
    if (document.querySelectorAll('.efund_RecurringDonation').length > 0) {
        document.querySelectorAll('.efund_RecurringDonation').forEach((efundRecurringDonationElem) => {
            efundRecurringDonationElem.style.display = 'none';
        });
    }
    if (document.getElementById('efund-recurring-instructions')) {
        document.getElementById('efund-recurring-instructions').style.display = 'none';
    }
    if (document.getElementById('panelMonthlyDonation')) {
        document.getElementById('panelMonthlyDonation').style.display = 'none'; // legacy
    }
    HideRecurringMessages();
    if (document.getElementById('Iterations')) {
        document.getElementById('Iterations').required = false;
        document.getElementById('Iterations').removeAttribute("pattern");
        document.getElementById('Iterations').value = '1';
    }
    if (document.getElementById('RecurringChoice')) {
        document.getElementById('RecurringChoice').value = '';
    }
    DisableRecurringOptions();
    if (document.getElementById('btnOneTime')) {
        document.getElementById('btnOneTime').disabled = true;
    }
    if (document.getElementById('ppNavButton')) {
        fadeIn(document.getElementById('ppNavButton'), 'fast');
    }
    if (document.getElementById('btnPayPal')) {
        enablePayPal();
    }
    if (googleAllowed) {
        toggleGooglePayContainers(true);
    }
}

function HandleWeeklyClick(resetIterations) {
    HandleRecurringClick(document.getElementById('weeklyMessage'), document.getElementById('btnWeekly'), document.getElementById('trans-weeks').textContent, "Weekly", resetIterations);
}

function HandleMonthlyClick(resetIterations) {
    HandleRecurringClick(document.getElementById('monthlyMessage'), document.getElementById('btnMonthly'), document.getElementById('trans-months').textContent, "Monthly", resetIterations);
}

function HandleQuarterlyClick(resetIterations) {
    HandleRecurringClick(document.getElementById('quarterlyMessage'), document.getElementById('btnQuarterly'), document.getElementById('trans-quarters').textContent, "Quarterly", resetIterations);
}

function HandleAnnuallyClick(resetIterations) {
    HandleRecurringClick(document.getElementById('annuallyMessage'), document.getElementById('btnAnnually'), document.getElementById('trans-years').textContent, "Annually", resetIterations);
}

function HandleRecurringClick(recurringMessageElem, btnRecurringElem, pluralTerm, adverbTerm, resetIterations) {
    toggleGooglePayContainers(false);
    document.querySelectorAll('.efund_RecurringDonation').forEach((efundRecurringDonationElem) => {
        fadeIn(efundRecurringDonationElem, 'fast');
    });
    if (document.getElementById('efund-recurring-instructions')) {
        fadeIn(document.getElementById('efund-recurring-instructions'), 'fast');
    }
    if (document.getElementById('panelMonthlyDonation')) {
        fadeIn(document.getElementById('panelMonthlyDonation'), 'fast'); // legacy
    }
    HideRecurringMessages();
    fadeIn(recurringMessageElem, "fast");
    document.getElementById('Iterations').required = true;
    DisableRecurringOptions();
    btnRecurringElem.disabled = true;
    document.getElementById('IterationsLabel').textContent = (pluralTerm);
    document.getElementById('RecurringChoice').value = adverbTerm;
    disableNonRecurringPaymentMethods();

    if (document.getElementById('Iterations').getAttribute('continuous-recurring') === 'true') {
        //document.getElementById('Iterations').setAttribute('value', '1');
        document.getElementById('Iterations').value = '1';
    }
    else if (resetIterations) {
        //document.getElementById('Iterations').setAttribute('value', '');
        document.getElementById('Iterations').value = '';
        document.getElementById('Iterations').classList.remove('valid');
    }
}

function SetupRecurring(checkMessages) {
    if (document.getElementById('RecurringChoice')) {
        let choiceElem = document.getElementById('RecurringChoice');
        if (choiceElem.value !== undefined) {
            if (choiceElem.value === "" && document.getElementById('RecurringChoice').getAttribute('force-recurring') === 'true') {
                if (document.getElementById('btnWeekly')) {
                    document.getElementById('RecurringChoice').value = ('Weekly');
                    document.getElementById('Iterations').value = '';
                }
                else if (document.getElementById('btnMonthly')) {
                    document.getElementById('RecurringChoice').value = ('Monthly');
                    document.getElementById('Iterations').value = '';
                }
                else if (document.getElementById('btnQuarterly')) {
                    document.getElementById('RecurringChoice').value = ('Quarterly');
                    document.getElementById('Iterations').value = '';
                }
                else if (document.getElementById('btnAnnually')) {
                    document.getElementById('RecurringChoice').value = ('Annually');
                    document.getElementById('Iterations').value = '';
                }
                else if (checkMessages) {
                    if (document.getElementById('weeklyMessage')) {
                        document.getElementById('RecurringChoice').value = ('Weekly');
                        document.getElementById('Iterations').value = '';
                    }
                    else if (document.getElementById('monthlyMessage')) {
                        document.getElementById('RecurringChoice').value = ('Monthly');
                        document.getElementById('Iterations').value = '';
                    }
                    else if (document.getElementById('quarterlyMessage')) {
                        document.getElementById('RecurringChoice').value = ('Quarterly');
                        document.getElementById('Iterations').value = '';
                    }
                    else if (document.getElementById('annuallyMessage')) {
                        document.getElementById('RecurringChoice').value = ('Annually');
                        document.getElementById('Iterations').value = '';
                    }
                }
            }

            //choiceElem = document.getElementById('RecurringChoice');
            if (choiceElem.value !== "") {
                let reset = true;
                if (choiceElem.value === "Monthly") {
                    HandleMonthlyClick(reset);
                }
                else if (choiceElem.value === "Weekly") {
                    HandleWeeklyClick(reset);
                }
                else if (choiceElem.value === "Quarterly") {
                    HandleQuarterlyClick(reset);
                }
                else if (choiceElem.value === "Annually") {
                    HandleAnnuallyClick(reset);
                }
            }
            else {
                if (document.querySelector('#efund-recurring-btns input.btn.btn-default')) {
                    //Disable the first one
                    var firstId = document.querySelector('#efund-recurring-btns input.btn.btn-default').getAttribute('id');
                    if (firstId === 'btnOneTime') {
                        HandleOneTimeClick();
                    } else if (firstId === 'btnWeekly') {
                        HandleWeeklyClick(true);
                    } else if (firstId === 'btnMonthly') {
                        HandleMonthlyClick(true);
                    } else if (firstId === 'btnQuarterly') {
                        HandleQuarterlyClick(true);
                    } else if (firstId === 'btnAnnually') {
                        HandleAnnuallyClick(true);
                    }
                }
                // If OneTime selected, set iterations to 1
                if (document.getElementById('btnOneTime') && document.getElementById('btnOneTime').disabled === true) {
                    document.getElementById('Iterations').value = '1';
                }
            }
        }
    }
}

//Set up Recurring
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('btnOneTime')) {
        document.getElementById('btnOneTime').addEventListener('click', function () {
            HandleOneTimeClick();
        });
    }
    if (document.getElementById('btnWeekly')) {
        document.getElementById('btnWeekly').addEventListener('click', function () {
            HandleWeeklyClick(true);
        });
    }
    if (document.getElementById('btnMonthly')) {
        document.getElementById('btnMonthly').addEventListener('click', function () {
            HandleMonthlyClick(true);
        });
    }
    if (document.getElementById('btnQuarterly')) {
        document.getElementById('btnQuarterly').addEventListener('click', function () {
            HandleQuarterlyClick(true);
        });
    }
    if (document.getElementById('btnAnnually')) {
        document.getElementById('btnAnnually').addEventListener('click', function () {
            HandleAnnuallyClick(true);
        });
    }

    SetupRecurring(false);
});

//Payment Type setup
function handleCreditCardClick() {
    if (document.getElementById('btnVenmo')) {
        hideVenmoTab();
    }
    if (document.getElementById('ACHDonation')) {
        document.getElementById('ACHDonation').value = 'False';
    }
    if (document.getElementById('RoutingNumber')) {
        document.getElementById('RoutingNumber').required = false;
        document.getElementById('RoutingNumber').value = '';
    }
    if (document.getElementById('AccountNumber')) {
        document.getElementById('AccountNumber').required = false;
        document.getElementById('AccountNumber').value = '';
    }
    if (document.getElementById('btnACH')) {
        validateAndUpdateACHInputs();
    }
    if (document.getElementById('ach-opt')) {
        document.getElementById('ach-opt').style.display = 'none';
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').disabled = false;
    }
    if (document.getElementById('ach-error')) {
        document.getElementById('ach-error').style.display = 'none';
    }
    if (document.getElementById('CCNumber')) {
        document.getElementById('CCNumber').required = true;
        document.getElementById('ExpDate').required = true;
    }
    if (document.getElementById('CCSecurity')) {
        if (document.getElementById('CCSecurity').getAttribute('rerequire') === 'true') {
            document.getElementById('CCSecurity').required = true;
        }
    }
    if (document.getElementById('paypal-tab-content')) {
        document.getElementById('paypal-tab-content').style.display = 'none';
    }
    if (document.getElementById('creditcard-opt')) {
        fadeIn(document.getElementById('creditcard-opt'), 'fast');
    }
    if (document.getElementById('btnCreditCard')) {
        document.getElementById('btnCreditCard').disabled = true;
    }
    if (document.getElementById('btnPayPal')) {
        document.getElementById('btnPayPal').disabled = false;
    }
    if (document.getElementById('mainSubmit')) {
        if (!document.getElementById('disableDonations')) {
            document.getElementById('mainSubmit').disabled = false;
        } else {
            document.getElementById('mainSubmit').disabled = true;
        }
    }
    showRecaptcha();
}

function handleACHClick() {
    if (document.getElementById('btnVenmo')) {
        hideVenmoTab();
    }
    document.getElementById('ACHDonation').value = 'True';
    //document.getElementById('AccountNumber').value = '';
    document.getElementById('CCNumber').required = false;
    document.getElementById('ExpDate').required = false;
    document.getElementById('CCSecurity').required = false;
    document.getElementById('CCNumber').value = '';
    document.getElementById('ExpDate').value = '';
    document.getElementById('CCSecurity').value = '';
    let CCAddressDifferent = document.getElementById('CCAddressDifferent');
    if (CCAddressDifferent && CCAddressDifferent.checked) {
        CCAddressDifferent.click();
    }
    document.getElementById('RoutingNumber').required = true;
    document.getElementById('AccountNumber').required = true;
    document.getElementById('creditcard-opt').style.display = 'none';
    validateAndUpdateCreditCardInputs();
    if (document.getElementById('paypal-tab-content')) {
        document.getElementById('paypal-tab-content').style.display = 'none';
    }
    fadeIn(document.getElementById('ach-opt'), 'fast');

    if (document.getElementById('btnCreditCard')) {
        document.getElementById('btnCreditCard').disabled = false;
    }
    if (document.getElementById('btnPayPal')) {
        document.getElementById('btnPayPal').disabled = false;
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').disabled = true;
    }
    if (!document.getElementById('disableDonations')) {
        document.getElementById('mainSubmit').disabled = false;
    } else {
        document.getElementById('mainSubmit').disabled = true;
    }

    showRecaptcha();
}

function handlePayPalClick() {
    if (document.getElementById('btnVenmo')) {
        hideVenmoTab();
    }
    if (document.getElementById('ACHDonation')) {
        document.getElementById('ACHDonation').value = 'False';
    }
    if (document.getElementById('ApplePayDonation')) {
        document.getElementById('ApplePayDonation').value = 'False';
    }
    if (document.getElementById('GooglePayDonation')) {
        document.getElementById('GooglePayDonation').value = 'False';
    }
    if (document.getElementById('RoutingNumber')) {
        document.getElementById('RoutingNumber').required = false;
        document.getElementById('RoutingNumber').value = '';
    }
    if (document.getElementById('AccountNumber')) {
        document.getElementById('AccountNumber').required = false;
        document.getElementById('AccountNumber').value = '';
    }
    if (document.getElementById('btnACH')) {
        validateAndUpdateACHInputs();
    }
    if (document.getElementById('ach-opt')) {
        document.getElementById('ach-opt').style.display = 'none';
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').disabled = false;
    }
    document.getElementById('CCNumber').required = false;
    document.getElementById('ExpDate').required = false;
    document.getElementById('CCSecurity').required = false;
    document.getElementById('CCNumber').value = '';
    document.getElementById('ExpDate').value = '';
    document.getElementById('CCSecurity').value = '';
    let CCAddressDifferent = document.getElementById('CCAddressDifferent');
    if (CCAddressDifferent && CCAddressDifferent.checked) {
        CCAddressDifferent.click();
    }
    document.getElementById('creditcard-opt').style.display = 'none';
    fadeIn(document.getElementById('paypal-tab-content'), 'fast');
    document.getElementById('btnCreditCard').disabled = false;
    document.getElementById('btnPayPal').disabled = true;
    document.getElementById('mainSubmit').disabled = true;
    if (document.getElementById('btnPayPal')) {
        updatePayPalStatus();
        resetPayPalContainer();
    }
    hideRecaptcha();
    validateAndUpdateCreditCardInputs();
    updateFieldErrors();
}

function handleVenmoClick() {
    showVenmoTab();

    /* Reset other payment methods: */
    if (document.getElementById('ACHDonation')) {
        document.getElementById('ACHDonation').value = 'False';
    }
    if (document.getElementById('ApplePayDonation')) {
        document.getElementById('ApplePayDonation').value = 'False';
    }
    if (document.getElementById('GooglePayDonation')) {
        document.getElementById('GooglePayDonation').value = 'False';
    }
    if (document.getElementById('RoutingNumber')) {
        document.getElementById('RoutingNumber').required = false;
        document.getElementById('RoutingNumber').value = '';
    }
    if (document.getElementById('AccountNumber')) {
        document.getElementById('AccountNumber').required = false;
        document.getElementById('AccountNumber').value = '';
    }
    if (document.getElementById('btnACH')) {
        validateAndUpdateACHInputs();
    }
    if (document.getElementById('ach-opt')) {
        document.getElementById('ach-opt').style.display = 'none';
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').disabled = false;
    }
    document.getElementById('CCNumber').required = false;
    document.getElementById('ExpDate').required = false;
    document.getElementById('CCSecurity').required = false;
    document.getElementById('CCNumber').value = '';
    document.getElementById('ExpDate').value = '';
    document.getElementById('CCSecurity').value = '';
    let CCAddressDifferent = document.getElementById('CCAddressDifferent');
    if (CCAddressDifferent && CCAddressDifferent.checked) {
        CCAddressDifferent.click();
    }
    document.getElementById('creditcard-opt').style.display = 'none';
    if (document.getElementById('paypal-tab-content')) {
        document.getElementById('paypal-tab-content').style.display = 'none';
    }
    document.getElementById('btnCreditCard').disabled = false;
    if (document.getElementById('btnPayPal')) {
        document.getElementById('btnPayPal').disabled = false;
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').disabled = false;
    }
    if (document.getElementById('btnPayPal')) {
        resetPayPalContainer();
    }
    hideRecaptcha();
    validateAndUpdateCreditCardInputs();
    updateFieldErrors();
}

function validateAndUpdateACHInputs() {
    validateAndUpdateInput(document.getElementById('RoutingNumber'));
    validateAndUpdateInput(document.getElementById('AccountNumber'));
}

function validateAndUpdateCreditCardInputs() {
    validateAndUpdateInput(document.getElementById('CCNumber'));
    validateAndUpdateInput(document.getElementById('ExpDate'));
    validateAndUpdateInput(document.getElementById('CCSecurity'));
}

function hideRecaptcha() {
    if (document.querySelector('.g-recaptcha')) {
        document.querySelector('.g-recaptcha').style.display = "none";
        hideRecaptchaError();
    }
}

function showRecaptcha() {
    if (document.querySelector('.g-recaptcha')) {
        document.querySelector('.g-recaptcha').style.display = "block";
    }
}

function disableFormSubmit() {
    document.getElementById('mainSubmit').disabled = true;
}

function enableFormSubmit() {
    if (!document.getElementById('disableDonations')) {
        document.getElementById('mainSubmit').disabled = false;
    }
}

function showVenmoTab() {
    document.getElementById('btnVenmo').disabled = true;
    fadeIn(document.getElementById('venmo-tab-content'), 'fast');
    disableFormSubmit();
}

function hideVenmoTab() {
    document.getElementById('btnVenmo').disabled = false;
    document.getElementById('venmo-tab-content').style.display = 'none';
    enableFormSubmit();
    resetVenmo();
}

function resetVenmo() {
    resetVenmoValues();
    resetVenmoTabContent();
}

function resetVenmoValues() {
    document.getElementById('BraintreeNonce').value = '';
    document.getElementById('VenmoId').value = '';
    document.getElementById('VenmoDonation').value = 'False';
}

function resetVenmoTabContent() {
    document.getElementById('venmo-column').disabled = false;
    document.getElementById('venmo-message-error').style.display = 'none';
}

document.addEventListener("DOMContentLoaded", function () {
    //Set up click events
    if (document.getElementById('btnCreditCard')) {
        document.getElementById('btnCreditCard').addEventListener('click', function () {
            handleCreditCardClick();
        });
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').addEventListener('click', function () {
            handleACHClick();
        });
    }

    if (document.getElementById('btnPayPal')) {
        document.getElementById('btnPayPal').addEventListener('click', function () {
            handlePayPalClick();
        });
    }

    if (document.getElementById('btnVenmo')) {
        document.getElementById('btnVenmo').addEventListener('click', function () {
            handleVenmoClick();
        });
    }

    if (document.getElementById('ACHDonation') && document.getElementById('ACHDonation').value === 'True') {
        handleACHClick();
    } else if ((!document.getElementById('ApplePayDonation') || document.getElementById('ApplePayDonation').value !== 'True') &&
        (!document.getElementById('GooglePayDonation') || document.getElementById('GooglePayDonation').value !== 'True')) {
        //document.getElementById('btnCreditCard').dispatchEvent(new Event('click'));
        handleCreditCardClick();
    }

    // 3rd party payment
    if (document.querySelector('.btn-hide-default-pay')) {
        document.querySelector('.btn-hide-default-pay').addEventListener('click', function () {
            let hasScrolled = false;
            if (document.getElementById('section-amount') && !validateAmount(document.querySelector('.efundForm'))) {
                //Hover to the payment section if payment is invalid
                document.getElementById("section-amount").scrollIntoView({ behavior: "smooth" });
                hasScrolled = true;
            }

            handleIndividualClick();
            handleCreditCardClick();

            googleAllowed = false;
            toggleApplePayContainers(false);
            toggleGooglePayContainers(false);

            if (!hasScrolled) {
                if (document.getElementById("section-personal")) {
                    document.getElementById("section-personal").scrollIntoView({ behavior: "smooth" });
                } else if (document.getElementById('buttonCCPrev')) {
                    document.getElementById('buttonCCPrev').dispatchEvent(new Event('click'));
                }
            }
        });
    }

    if (document.getElementById('apple-pay-confirm')) {
        document.getElementById('apple-pay-confirm').addEventListener('click', function () {
            handleDefaultPayConfirmationClick(this);
        });
    }

    if (document.getElementById('default-pay-confirm')) {
        document.getElementById('default-pay-confirm').addEventListener('click', function () {
            handleDefaultPayConfirmationClick(this);
        });
    }

    //ApplePay Setup stuff
    if (document.getElementById('apple-pay-submit')) {
        setupApplePay();
        // async, but no reason to await
        toggleApplePayFromServerData();
    }

    //GooglePay Setup stuff
    if (document.getElementById('google-pay-submit')) {
        onGooglePayLoaded();
        toggleGooglePayFromServerData();
    }
    //PayPal Setup stuff
});

// Google Places API Autocomplete

// Address decoy field
function updateDecoyAddress() {
    if (document.getElementById('decoy-address')) {
        document.getElementById('decoy-address').value = document.getElementById('StreetAddress').value;
    }
    if (document.getElementById('apple-decoy-address')) {
        document.getElementById('apple-decoy-address').value = document.getElementById('apple-address').value;
    }
}
function updateRealAddress() {
    if (document.getElementById('decoy-address')) {
        document.getElementById('StreetAddress').value = document.getElementById('decoy-address').value;
    }
    if (document.getElementById('apple-decoy-address')) {
        document.getElementById('apple-address').value = document.getElementById('apple-decoy-address').value;
    }
}

document.addEventListener("DOMContentLoaded", function () {
    // Update StreetAddress field on form submit
    document.querySelector(".form-submit").addEventListener('click', function () {
        updateRealAddress();
    });

    if (document.getElementById('apple-pay-confirm')) {
        document.getElementById('apple-pay-confirm').addEventListener('click', function () {
            updateRealAddress();
        });
    }

    if (document.getElementById('default-pay-confirm')) {
        document.getElementById('default-pay-confirm').addEventListener('click', function () {
            updateRealAddress();
        });
    }


    // Update StreetAddress field in HeroShot
    document.querySelectorAll(".form-flow-btn").forEach((cbcpNextBtn) => {
        cbcpNextBtn.addEventListener('click', function () {
            updateRealAddress();
        });
    });

    // Prevent autocomplete of decoy address
    if (document.getElementById('decoy-address')) {
        document.getElementById('decoy-address').addEventListener('focus', function () {
            if (this.getAttribute('autocomplete') === 'off') {
                this.setAttribute('autocomplete', 'nope');
            }
        });
    }

});

var googleComponentForm = {
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    postal_code: 'short_name'
};
function initAutocomplete() {
    // Create autocomplete object, restricting suggestions to geographical location types
    autocomplete = new google.maps.places.Autocomplete(
        document.getElementById('decoy-address'), { types: ['geocode'] });

    // Restrict set of place fields to address components.
    autocomplete.setFields(["address_components", "geometry", "icon", "name"]);

    // When user selects address from the drop-down, populate the address fields in form
    autocomplete.addListener('place_changed', fillInAddress);

    // Overwrite Google API placeholder
    if (document.getElementById('decoy-address')) {
        document.getElementById('decoy-address').setAttribute('placeholder', '');
    }
}

function fillInAddress() {
    // Get the place details from the autocomplete object
    var place = autocomplete.getPlace();

    document.querySelectorAll('.address-field').forEach((addressFieldElem) => {
        addressFieldElem.value = '';
    });

    // Get address components from place details, and fill-in the corresponding form fields
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (googleComponentForm[addressType]) {
            var val = place.address_components[i][googleComponentForm[addressType]];
            document.querySelectorAll('.address-field').forEach((addressFieldElem) => {
                if (addressFieldElem.getAttribute('data-address-component') === addressType) {
                    addressFieldElem.value = val;
                }
            });
        }
    }
    // Show address number and street only in StreetAddress field
    var addressNum = place.address_components[0]['short_name'];
    var addressStreet = place.address_components[1]['long_name'];
    document.getElementById('decoy-address').value = (addressNum + ' ' + addressStreet);

    // Validate inputs
    document.querySelectorAll('.address-field').forEach((addressFieldElem) => {
        validateInput(addressFieldElem);
        updateInputValidationStyle(addressFieldElem);
    });
    // Move up labels
    document.querySelectorAll('.address-field').forEach((addressFieldElem) => {
        addressFieldElem.closest('.efund-form-group').querySelector('.form-label').classList.add('moveUp');
    });
    // Focus Retired checkbox
    if (document.getElementById('Retired')) {
        document.getElementById('Retired').dispatchEvent(new Event('focus'));
    }
}

// =================================
// Input Formatting and Masking
// =================================
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('.form-control[type="text"]').forEach((inputElem) => {
        inputElem.addEventListener('blur', function () {
            this.value = this.value.trim();
        });
    });

    // Masking with Cleave library
    // Phone
    if (document.getElementById('Phone')) {
        document.getElementById('Phone').removeAttribute('maxlength');
        const phoneValue = document.getElementById('Phone').value;

        let phoneCleave = (phoneValue.length > 0 && phoneValue[0] != '1') ?
            new Cleave('#Phone', {
                delimiters: ['(', ') ', '-'],
                blocks: [0, 3, 3, 4],
                numericOnly: true
            }) :
            new Cleave('#Phone', {
                delimiters: [' (', ') ', '-'],
                blocks: [1, 3, 3, 4],
                numericOnly: true
            });
        document.getElementById('Phone').addEventListener('keyup', function (e) {
            phoneCleave = updatePhoneCleave(this, phoneCleave);
        });
        document.getElementById('Phone').addEventListener('input', function (e) {
            phoneCleave = updatePhoneCleave(this, phoneCleave);
            document.getElementById('Phone').value = phoneCleave.properties.result;
        });
    }

    // ApplePhone
    if (document.getElementById('ApplePhone')) {
        document.getElementById('ApplePhone').removeAttribute('maxlength');
        const ApplePhoneValue = document.getElementById('ApplePhone').value;

        let applePhoneCleave = (ApplePhoneValue.length > 0 && ApplePhoneValue[0] != '1') ?
            new Cleave('#ApplePhone', {
                delimiters: ['(', ') ', '-'],
                blocks: [0, 3, 3, 4],
                numericOnly: true
            }) :
            new Cleave('#ApplePhone', {
                delimiters: [' (', ') ', '-'],
                blocks: [1, 3, 3, 4],
                numericOnly: true
            });
        document.getElementById('ApplePhone').addEventListener('keyup', function (e) {
            applePhoneCleave = updateApplePhoneCleave(this, applePhoneCleave);
        });
        document.getElementById('ApplePhone').addEventListener('input', function (e) {
            applePhoneCleave = updateApplePhoneCleave(this, applePhoneCleave);
            document.getElementById('ApplePhone').value = applePhoneCleave.properties.result;
        });
    }

    // Zipcodes
    addCleaveToZip('StreetZip');
    addCleaveToZip('AppleZip');
    addCleaveToZip('CCZip');

    // CC Number
    if (document.getElementById('CCNumber')) {
        document.getElementById('CCNumber').removeAttribute('maxlength');
        new Cleave('#CCNumber', {
            creditCard: true
        });
    }

    // Exp Date
    replaceMaxlengthWithCleave('ExpDate', {
        date: true,
        datePattern: ['m', 'y']
    });

    // CVV
    if (document.getElementById('CCSecurity')) {
        document.getElementById('CCSecurity').removeAttribute('maxlength');

        const ccNumber = document.getElementById('CCNumber').value,
            cvvLength = getCvvLengthFromCCNumber(ccNumber);

        let cvvCleave = updateCvvCleave(cvvLength);

        document.getElementById('CCNumber').addEventListener('input', function (e) {
            const ccNumber = e.target.value,
                cvvLength = getCvvLengthFromCCNumber(ccNumber);

            // Update CVV format
            document.getElementById('CCSecurity').setAttribute('placeholder', '•'.repeat(cvvLength));
            document.getElementById('CCSecurity').setAttribute('pattern', '[0-9]{' + cvvLength + '}');

            cvvCleave = updateCvvCleave(cvvLength, cvvCleave);
        });
    }
});

function updateCvvCleave(cvvLength, cvvCleave) {
    if (cvvCleave != null) {
        cvvCleave.destroy();
        cvvCleave = null;
    }

    cvvCleave = new Cleave('#CCSecurity', {
        blocks: [cvvLength],
        numericOnly: true
    });

    return cvvCleave;
}

function addCleaveToZip(zipId) {
    replaceMaxlengthWithCleave(zipId, {
        blocks: [5],
        numericOnly: true
    });
}

function replaceMaxlengthWithCleave(elemId, cleaveOptions) {
    if (document.getElementById(elemId)) {
        document.getElementById(elemId).removeAttribute('maxlength');
        new Cleave('#' + elemId, cleaveOptions);
    }
}

function updatePhoneCleave(phoneFieldElem, phoneCleave) {

    var oldValue = '';
    if (phoneFieldElem.getAttribute('data-old-value') != undefined) {
        oldValue = phoneFieldElem.getAttribute('data-old-value');
    }

    var currentValue = phoneFieldElem.value;
    if (phoneCleave != null) {
        currentValue = phoneCleave.getRawValue();
    }

    if (oldValue.length != currentValue.length) {
        phoneFieldElem.setAttribute('data-old-value', currentValue);

        const rawValue = phoneCleave.getRawValue();

        if (phoneCleave != null) {
            phoneCleave.destroy();
            phoneCleave = null;
        }

        if (rawValue.length === 0 || rawValue[0] === '1' || rawValue[0] === '+') {
            phoneCleave = new Cleave('#Phone', {
                delimiters: [' (', ') ', '-'],
                blocks: [1, 3, 3, 4],
                numericOnly: true
            });
        }
        else {
            phoneCleave = new Cleave('#Phone', {
                delimiters: ['(', ') ', '-'],
                blocks: [0, 3, 3, 4],
                numericOnly: true
            });
        }
    }

    return phoneCleave;
}

function updateApplePhoneCleave(phoneFieldElem, phoneCleave) {

    var oldValue = '';
    if (phoneFieldElem.getAttribute('data-old-value') != undefined) {
        oldValue = phoneFieldElem.getAttribute('data-old-value');
    }

    var currentValue = phoneFieldElem.value;
    if (phoneCleave != null) {
        currentValue = phoneCleave.getRawValue();
    }

    if (oldValue.length != currentValue.length) {
        phoneFieldElem.setAttribute('data-old-value', currentValue);

        const rawValue = phoneCleave.getRawValue();

        if (phoneCleave != null) {
            phoneCleave.destroy();
            phoneCleave = null;
        }

        if (rawValue.length === 0 || rawValue[0] === '1' || rawValue[0] === '+') {
            phoneCleave = new Cleave('#ApplePhone', {
                delimiters: [' (', ') ', '-'],
                blocks: [1, 3, 3, 4],
                numericOnly: true
            });
        }
        else {
            phoneCleave = new Cleave('#ApplePhone', {
                delimiters: ['(', ') ', '-'],
                blocks: [0, 3, 3, 4],
                numericOnly: true
            });
        }
    }

    return phoneCleave;
}

// CC Number Format and Length
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('CCNumber')) {
        document.getElementById('CCNumber').addEventListener('input', function (e) {
            const ccNumber = e.target.value,
                maxLength = getCCLengthFromCCNumber(ccNumber);

            // Update CC Number format
            this.setAttribute('pattern', '[0-9 ]{' + maxLength + '}');
        });
    }
});

function getCvvLengthFromCCNumber(ccNumber) {
    return /^3[47]/.test(ccNumber) ? 4 : 3;
}

function getCCLengthFromCCNumber(ccNumber) {
    return /^3[47]/.test(ccNumber) ? 17 : 19;
}

document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('CCNumber')) {
        document.getElementById('CCNumber').addEventListener('input', function (e) {
            showCCIcon(this);
        });
    }
});
window.addEventListener('load', function () {
    if (document.getElementById('CCNumber')) {
        showCCIcon(document.getElementById('CCNumber'));
    }
})
function showCCIcon(inputElem) {
    var value = inputElem.value.trim().replace(/\D/g, '');
    var ccFileName;
    if (value.length === 0) {
        ccFileName = 'generic-cc-small';
    } else if (/^3[47]/.test(value)) { // Amex
        ccFileName = 'amex-cc-small';
    } else if (/^3[089]/.test(value)) { // Diners Club
        ccFileName = 'diners-club-cc-small';
    } else if (/^4/.test(value)) { // Visa
        ccFileName = 'visa-cc-small';
    } else if (/^5[1-5]/.test(value)) { // Mastercard
        ccFileName = 'mastercard-cc-small';
    } else if (/^6/.test(value)) { // Discover
        ccFileName = 'discover-cc-small';
    } else {
        ccFileName = 'generic-cc-small';
    }
    if (inputElem.closest('.efund-form-group')) {
        inputElem.closest('.efund-form-group').querySelector('.cc-icon img').setAttribute('src', '/images/credit-cards/' + ccFileName + '.png');
    }

}

// CC Address Display
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('CCAddressDifferent')) {
        checkCCZip(document.getElementById('CCAddressDifferent'));
        document.getElementById('CCAddressDifferent').addEventListener('change', function () {
            checkCCZip(this);
        });
    }
    function checkCCZip(checkboxElem) {
        if (checkboxElem.checked) {
            setTimeout(function () {
                if (checkboxElem.checked) {
                    fadeIn(document.getElementById('panelCCAddress'), 'fast');
                }
            }, 300);
            document.getElementById('CCZip').required = true;
            document.getElementById('CCZip').setAttribute("rerequire", "true");
            document.getElementById('CCZip').setAttribute("pattern", "[0-9]{5}");
            document.getElementById('CCAddressDifferentColumn').classList.remove('col-md-12');
            document.getElementById('CCAddressDifferentColumn').classList.add('col-md-8');
        }
        else {
            document.getElementById('panelCCAddress').style.display = 'none';
            document.getElementById('CCZip').required = false;
            document.getElementById('CCZip').removeAttribute("rerequire");
            document.getElementById('CCZip').removeAttribute("pattern");
            document.getElementById('CCAddressDifferentColumn').classList.add('col-md-12');
            document.getElementById('CCAddressDifferentColumn').classList.remove('col-md-8');
        }
    }
});

// Other Amount Field Masking
document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById("OtherAmount")) {
        document.getElementById("OtherAmount").addEventListener('keydown', function (e) {
            allowDecimalNumber(this, e);
        });
        document.getElementById('OtherAmount').addEventListener('input', function () {
            limitTwoDecimal(this);
        });
        document.getElementById("OtherAmount").addEventListener('blur', function () {
            clearNumberField(this);
        });
    }
});

function allowDecimalNumber(input, evt) {
    // Allow only decimals and numbers
    // Allow: . (if no decimal already)
    if (!RegExp('\\.').test(input.value)) {
        if (evt.keyCode === 190) {
            return;
        }
    }
    // Allow: backspace, delete, tab, escape, enter
    const keyCodes = [46, 8, 9, 27, 13, 110];
    if (keyCodes.indexOf(evt.keyCode) !== -1 ||
        // Allow: Ctrl+A, Command+A
        (evt.keyCode === 65 && (evt.ctrlKey === true || evt.metaKey === true)) ||
        // Allow: home, end, left, right, down, up
        (evt.keyCode >= 35 && evt.keyCode <= 40)) {
        return;
    }
    if ((evt.shiftKey || (evt.keyCode < 48 || evt.keyCode > 57)) && (evt.keyCode < 96 || evt.keyCode > 105)) {
        evt.preventDefault();
    }
}

function limitTwoDecimal(input) {
    // Limit out 2 decimal spaces 
    var regex = /^\d+\.?\d{0,2}/;
    var val = input.value;
    if (val && parseFloat(val) % 1 != 0) {
        input.value = val.match(regex)[0];
    }
}

function clearNumberField(inputElem) {
    // Clear field if value is empty string
    if (inputElem.value === '' || inputElem.value === '0') {
        inputElem.value = '';
    }
}

//Key down stuff
document.addEventListener("DOMContentLoaded", function () {
    // Only Numbers
    document.querySelectorAll(".numbersOnly").forEach((numbersOnlyFieldElem) => {
        numbersOnlyFieldElem.addEventListener('keydown', function (e) {
            // Allow: backspace, delete, tab, escape, enter
            const keyCodes = [46, 8, 9, 27, 13];
            if (keyCodes.indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                //Allow: Ctrl+C, Command+C
                (e.keyCode === 86 && (e.ctrlKey === true || e.metaKey === true)) ||
                // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                return;
            }
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
    });

    //Prevent spaces
    document.querySelectorAll('.no-space').forEach((noSpaceFieldElem) => {
        noSpaceFieldElem.addEventListener('keydown', function (e) {
            if (e.keyCode === 32) {
                e.preventDefault();
            }
        });
        noSpaceFieldElem.addEventListener('input', function () {
            this.value = this.value.replace(/\s/g, '');
        });
    });
});

//Some random events and other stuff
document.addEventListener("DOMContentLoaded", function () {

    // Highlight Amounts
    document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
        paymentOptionItemElem.addEventListener('click', function () {
            document.querySelectorAll('.efund_PaymentOptionItem').forEach((otherPaymentOptionItemElem) => {
                otherPaymentOptionItemElem.classList.remove("selectedOption");
            });
            this.classList.add("selectedOption");
            updateTotalAmount(this.getAttribute('data-amount'));

            resetFieldAndLabel(document.getElementById('OtherAmount'));
            document.getElementById('OtherAmount').classList.remove('invalid');
            if (document.getElementById('OtherAmount').parentNode.querySelector('.error')) {
                document.getElementById('OtherAmount').parentNode.querySelector('.error').remove();
            }
            if (document.getElementById('OtherAmount').parentNode.querySelector('.error-icon')) {
                document.getElementById('OtherAmount').parentNode.querySelector('.error-icon').remove();
            }
            if (document.getElementById('OtherAmount').parentNode.querySelector('.more-info-btn')) {
                document.getElementById('OtherAmount').parentNode.querySelector('.more-info-btn').classList.remove('red');
            }
            document.getElementById('mainSubmit').removeAttribute('fromOtherAmount');
            validateInput(document.getElementById('OtherAmount'));
            updateInputValidationStyle(document.getElementById('OtherAmount'));

            document.getElementById('missing-amount').style.display = 'none';

            // Employer/Occupation Require Amount
            updateRequireAmount();
            if (document.getElementById('btnPayPal')) {
                resetPayPalContainer();
            }
        });
    });

    if (document.getElementById('OtherAmount')) {
        document.getElementById('OtherAmount').addEventListener('focusout', function () {
            var text = this.value;
            var parsedAmount = parseFloat(text);
            var fromOtherAmount = typeof document.getElementById('mainSubmit').getAttribute('fromOtherAmount') !== typeof undefined && document.getElementById('mainSubmit').getAttribute('fromOtherAmount') !== false;
            if ((text === '' || isNaN(parsedAmount)) && !fromOtherAmount) {
                this.parentNode.querySelector('label').classList.remove('moveUp');
            }
            else if (text && parsedAmount != 0) {
                document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
                    paymentOptionItemElem.classList.remove("selectedOption");
                });
                document.getElementById('mainSubmit').setAttribute('fromOtherAmount', "true");
                document.getElementById('missing-amount').style.display = 'none';
                updateTotalAmount(text);
            } else {
                this.value = '';
                this.parentNode.querySelector('label').classList.remove('moveUp');

                //Reset mainsubmit
                document.querySelector('#mainSubmit .btn-text').textContent = document.getElementById('mainSubmit').value;
                if (document.querySelector('.venmo-summary-total-value')) { document.querySelector('.venmo-summary-total-value').textContent = '0' };
                document.getElementById('mainSubmit').removeAttribute('fromOtherAmount');
                if (!(document.querySelector('.selectedOption'))) {
                    updateTotalAmount('0');
                }
                else {
                    updateTotalAmount(document.getElementById('Amount').value);
                }
            }
            // Employer/Occupation Required Amount
            updateRequireAmount();
            if (document.getElementById('btnPayPal')) {
                updatePayPalStatus();
                resetPayPalContainer();
            }
            updateFieldErrors();
        });
    }

    // Does not allow Space key to be used in fields with provided class selector
    document.querySelectorAll('.disallow-spaces').forEach((disallowSpacesElem) => {
        disallowSpacesElem.addEventListener('keydown', function (e) {
            if (e.keyCode == 32) return false;
        });
    });

    //Adjust amounts
    if (document.getElementById('CoverFee')) {
        document.getElementById('CoverFee').addEventListener('change', function (event) {
            if (this.checked) {
                if (parseFloat(document.getElementById('BaseAmount').value) > 0) {
                    updateTotalAmount(document.getElementById('BaseAmount').value);
                }
            }
            else {
                updateTotalAmount(document.getElementById('BaseAmount').value);
            }
            runIterationsValidation();
            validateCoverFee();
        });
    }

    // Run iterations function on iterations change
    if (document.getElementById('Iterations')) {
        document.getElementById('Iterations').addEventListener('change', function (event) {
            runIterationsValidation();
            updateRequireAmount();
        });
    }

    //Prevent # of Guests from ever being blank
    if (document.getElementById("NumberOfGuests")) {
        document.getElementById("NumberOfGuests").addEventListener('change', function () {
            if (this.value == '') {
                this.value = '0';
            }
        });
    }
});

function updateCoverFeeLabel(amount) {
    let requiredCoverFeeElem = document.getElementById('RequiredCoverFeeText');
    if (requiredCoverFeeElem) {
        let coverFeeCheckboxElem = document.getElementById('CoverFee');
        if (!coverFeeCheckboxElem.checked) {
            coverFeeCheckboxElem.checked = true;
            coverFeeCheckboxElem.dispatchEvent(new Event('change'));
        }

        let requiredCoverFeeText = document.getElementById('trans-coverfee').textContent;
        requiredCoverFeeText = requiredCoverFeeText.replace('{data-translate-1}', (addCoverFee(amount) - amount).toFixed(2));

        requiredCoverFeeElem.innerHTML = requiredCoverFeeText;
    } else {
        let checkedStatus = document.getElementById('CoverFee').checked ? '' : 'd-none';
        let labelText = document.getElementById('trans-checkbox4').textContent;

        if (checkedStatus === '') {
            labelText = document.getElementById('trans-checkbox5').textContent;
        }
        else {
            if (amount > 0) {
                labelText = labelText.replace('{data-translate-1}', (addCoverFee(amount) - amount).toFixed(2));
            }
            else {
                labelText = labelText.replace(' (+${data-translate-1})', '');
            }
        }
        document.getElementById('cover-fee-label').innerHTML = '<span class="checkbox-button-circle"><i class="fa fa-check ' + checkedStatus + '" aria-hidden="true"></i></span>' + labelText;
    }
}

function updateAccountMax() {
    const otherAmountElem = document.getElementById('OtherAmount');
    const individualMax = otherAmountElem.getAttribute('data-individual-max');
    let accountMax = individualMax;

    if (document.getElementById('btnSecond') && document.getElementById('btnSecond').disabled === true) {
        accountMax = (2 * parseFloat(individualMax)).toFixed(2);
    }

    otherAmountElem.setAttribute('max', accountMax);
}

function getAccountMax() {
    return parseFloat(document.getElementById('OtherAmount').getAttribute('max'));
}

function getAccountMin() {
    return parseFloat(document.getElementById('OtherAmount').getAttribute('min'));
}

function addCoverFee(amount) {
    let amount2 = (parseFloat(amount) + parseFloat(document.getElementById('PerTransaction').value)) / (1 - (0.01 * parseFloat(document.getElementById('DiscountRate').value)));
    return amount2.toFixed(2);
}

function applyFactors(amount) { // why do we need this -Alex 2/25/22
    amount = factorCoverFee(amount);
    return amount;
}

function factorCoverFee(amount) {
    if (document.getElementById('CoverFee')) {
        if (document.getElementById('CoverFee').checked && amount > 0) {
            amount = addCoverFee(amount);
        }
    }

    return amount;
}

function updateTotalAmount(amount) {
    document.getElementById('BaseAmount').value = (amount);
    if (document.getElementById('CoverFee')) {
        updateCoverFeeLabel(amount);
        amount = factorCoverFee(amount);
        validateCoverFee(amount);
    }

    document.getElementById('Amount').value = (amount);
    document.getElementById('Amount').dispatchEvent(new Event('change'));
    checkCoupleDecimalAmountValidation(document.getElementById('Amount').value);
    updateSubmitButtonTextWithAmount(document.getElementById('Amount').value);
}

function updateSubmitButtonTextWithAmount(amount) {
    if (parseFloat(amount) > 0) {
        var formattedAmount = parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        document.querySelector('#mainSubmit .btn-text').textContent = (document.getElementById('mainSubmit').value + ' $' + formattedAmount);
        if (document.querySelector('.venmo-summary-total-value')) { document.querySelector('.venmo-summary-total-value').textContent = formattedAmount };
    }
    else {
        document.querySelector('#mainSubmit .btn-text').textContent = (document.getElementById('mainSubmit').value);
        if (document.querySelector('.venmo-summary-total-value')) { document.querySelector('.venmo-summary-total-value').textContent = '0' };
    }
}

function disableAmountAffectors() {
    //Disable other amount
    if (document.getElementById('OtherAmount')) {
        document.getElementById('OtherAmount').disabled = true;
        document.getElementById('OtherAmountLabel').style.backgroundColor = '#EEE';
    }

    //Disable buttons
    document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
        paymentOptionItemElem.classList.add('disable-click');
    });

    //Disable recurring buttons
    document.querySelectorAll('#efund-recurring-btns .efund_choice').forEach((efundChoiceElem) => {
        efundChoiceElem.classList.add('disable-click');
    });

    //Disable Merchandise (non-event)
    document.querySelectorAll('.qty-field').forEach((qtyFieldElem) => {
        qtyFieldElem.classList.add('disable-click');
    });

    document.querySelectorAll('.qty-btn').forEach((qtyBtnElem) => {
        qtyBtnElem.classList.add('disable-click');
    });

    //Disable Tickets (event)
    if (document.getElementById('ticket-tab-btn')) {
        document.getElementById('ticket-tab-btn').classList.add('disable-click');
    }
    if (document.getElementById('contribution-tab-btn')) {
        document.getElementById('contribution-tab-btn').classList.add('disable-click');
    }

    //Disable Additional Amount (event)
    if (document.getElementById('OtherTicketAmount')) {
        document.getElementById('OtherTicketAmount').disabled = true;
        document.getElementById('OtherTicketAmountLabel').style.backgroundColor = '#EEE';
    }

    //Disable Cover Fee button
    if (document.getElementById('cover-fee-button')) {
        document.getElementById('cover-fee-button').classList.add('disable-click');
    }

    //Hide cancel payment selection
    if (document.getElementById('cancel-contribution-btn')) {
        document.getElementById('cancel-contribution-btn').style.display = 'none';
    }

    //Disable payment method buttons
    if (document.getElementById('btnCreditCard')) {
        document.getElementById('btnCreditCard').classList.add('disable-click');
    }
    if (document.getElementById('btnACH')) {
        document.getElementById('btnACH').classList.add('disable-click');
    }
    if (document.getElementById('btnPayPal')) {
        document.getElementById('btnPayPal').classList.add('disable-click');
    }
}

function disableNonRecurringPaymentMethods() {
    if (document.getElementById('paypal-tab-content')) {
        disablePayPal();
    }
}

// =================================
// ACH
// =================================
function isACHSelected() {
    return document.getElementById("ACHDonation").value === "True";
}

function ACHBraintreeCapture(callback) {
    try {

        var clientToken = document.getElementById('BraintreeClientToken').value;
        braintree.client.create({
            authorization: clientToken
        }, function (clientErr, clientInstance) {
            if (clientErr) {
                handleACHException(clientErr, callback, "ACHBraintreeCapture", "braintree.client.create", "There was an error creating the Client");
                return;
            }

            braintree.usBankAccount.create({
                client: clientInstance
            }, function (usBankAccountErr, usBankAccountInstance) {
                if (usBankAccountErr) {
                    handleACHException(usBankAccountErr, callback, "ACHBraintreeCapture", "braintree.usBankAccount.create", "There was an error creating the USBankAccount instance.");
                    return;
                }

                var bankDetails = {
                    accountNumber: document.getElementById('AccountNumber').value,
                    routingNumber: document.getElementById('RoutingNumber').value,
                    accountType: 'checking',
                    ownershipType: document.getElementById('CompanyDonation').value === 't' ? 'business' : 'personal',
                    billingAddress: {
                        streetAddress: document.getElementById('StreetAddress').value,
                        extendedAddress: '',
                        locality: document.getElementById('City').value,
                        region: document.getElementById('StreetState').value,
                        postalCode: document.getElementById('StreetZip').value
                    }
                };

                if (bankDetails.ownershipType === 'personal') {
                    bankDetails.firstName = document.getElementById('NameFirst').value;
                    bankDetails.lastName = document.getElementById('NameLast').value;
                } else {
                    bankDetails.businessName = document.getElementById('NameCompany').value;
                }

                usBankAccountInstance.tokenize({
                    bankDetails: bankDetails,
                    mandateText: 'By clicking ["Checkout"], I authorize Braintree, a service of PayPal, on behalf of [your business name here] (i) to verify my bank account information using bank information and consumer reports and (ii) to debit my bank account.'
                }, function (tokenizeErr, tokenizedPayload) {
                    if (tokenizeErr) {
                        handleACHException(tokenizeErr, callback, "ACHBraintreeCapture", "usBankAccountInstance.tokenize", "There was an error tokenizing the bank details");
                        return;
                    }
                    document.getElementById('BraintreeNonce').value = (tokenizedPayload.nonce);
                    callback(true);
                });
            });
        });
    }
    catch (err) {
        //That didn't work, so better try something else!!!
        handleACHException(err, callback, "ACHBraintreeCapture", "catch", "An error occured with ACH");
    }
}

function handleACHException(err, callback, target, action, consoleMessage) {
    var failMessage = document.querySelector('#ach-error p').innerHTML;
    console.error(consoleMessage, err);
    resetSubmit(document.querySelector('.efundForm'));
    fadeIn(document.getElementById('ach-error'), 'fast');
    callback(false);
}

function handlePostValidation(element, e) {
    //ACH
    if (element.getAttribute('id') === 'mainSubmit'
        && document.getElementById('RoutingNumber')
        && isACHSelected()
        && document.getElementById('BraintreeNonce').value === '') {
        e.preventDefault();
        preventDoubleSubmit(document.querySelector('.efundForm'));
        ACHBraintreeCapture(function (result) {
            if (result) {
                resetSubmit(document.querySelector('.efundForm'));

                element.dispatchEvent(new Event('click'));
            }
        });
    } else if (element.getAttribute('id') === 'mainSubmit'
        && document.getElementById('RoutingNumber')
        && isACHSelected()) {


        element.closest('.efundForm').submit();
        // Disable button
        element.disabled = true;
        // Show spinner
        if (getBrowser() === "Edge") {
            element.style.display = 'none';
        } else {
            element.querySelector('.btn-text').style.display = 'none';
        }
        element.querySelector('.btn-spinner').classList.add('show-spinner');

    }
}


// =================================
// Default Payment Options
// =================================

var defaultShown;

function validateInputsFromPaymentInfo() {
    var result = true;
    if (!validateInput(document.getElementById('NameFirst')) || !validateInput(document.getElementById('NameLast'))) {
        document.getElementById('apple-popup-name').style.display = 'flex';
        document.getElementById('AppleNameFirst').value = document.getElementById('NameFirst').value;
        document.getElementById('AppleNameFirst').required = true;
        document.getElementById('AppleNameFirst').dispatchEvent(new Event('change'));
        document.getElementById('AppleNameLast').value = document.getElementById('NameLast').value;
        document.getElementById('AppleNameLast').required = true;
        document.getElementById('AppleNameLast').dispatchEvent(new Event('change'));
        result = false;
    }

    if (document.getElementById('Phone') && !validateInput(document.getElementById('Phone'))) {
        document.getElementById('apple-popup-phone').style.display = 'flex';
        document.getElementById('ApplePhone').value = document.getElementById('Phone').value;
        if (document.getElementById('Phone').required) {
            document.getElementById('ApplePhone').required = true;
        }
        document.getElementById('ApplePhone').dispatchEvent(new Event('change'));
        result = false;
    }

    if (!validateInput(document.getElementById('StreetAddress')) ||
        !validateInput(document.getElementById('City')) ||
        !validateInput(document.getElementById('StreetState')) ||
        !validateInput(document.getElementById('StreetZip'))) {

        document.getElementById('apple-popup-address').style.display = 'block';
        document.getElementById('AppleAddress').value = (document.getElementById('StreetAddress').value);
        document.getElementById('AppleAddress').required = true;
        document.getElementById('AppleAddress').dispatchEvent(new Event('change'));
        document.getElementById('AppleCity').value = (document.getElementById('City').value);
        document.getElementById('AppleCity').required = true;
        document.getElementById('AppleCity').dispatchEvent(new Event('change'));
        var stateVal = document.getElementById('StreetState').value;
        if (!stateVal) {
            stateVal = document.getElementById('DefaultState').value;
        }
        document.getElementById('AppleState').value = (stateVal);
        document.getElementById('AppleState').required = true;
        document.getElementById('AppleState').dispatchEvent(new Event('change'));
        document.getElementById('AppleZip').value = (document.getElementById('StreetZip').value);
        document.getElementById('AppleZip').required = true;
        document.getElementById('AppleZip').dispatchEvent(new Event('change'));
        result = false;
    }

    return result;
}

function handleDefaultPayConfirmationClick(buttonElem) {
    //Prevent double submit
    buttonElem.disabled = true;
    if (validateApplePayConfirm()) {
        //Fill in values (if visible)
        if (document.getElementById('apple-popup-name').style.display == 'flex') {
            document.getElementById('NameFirst').value = (document.getElementById('AppleNameFirst').value);
            document.getElementById('NameFirst').dispatchEvent(new Event('change'));
            document.getElementById('NameLast').value = (document.getElementById('AppleNameLast').value);
            document.getElementById('NameLast').dispatchEvent(new Event('change'));
        }

        if (document.getElementById('apple-popup-phone').style.display == 'flex') {
            document.getElementById("Phone").value = (document.getElementById('ApplePhone').value);
            document.getElementById("Phone").dispatchEvent(new Event('change'));
        }

        if (document.getElementById('apple-popup-address').style.display == 'block') {
            document.getElementById("StreetAddress").value = (document.getElementById('AppleAddress').value);
            document.getElementById("StreetAddress").dispatchEvent(new Event('change'));
            document.getElementById("City").value = (document.getElementById('AppleCity').value);
            document.getElementById("City").dispatchEvent(new Event('change'));
            document.getElementById("StreetState").value = (document.getElementById('AppleState').value);
            document.getElementById("StreetState").dispatchEvent(new Event('change'));
            document.getElementById("StreetZip").value = (document.getElementById('AppleZip').value);
            document.getElementById("StreetZip").dispatchEvent(new Event('change'));
        }

        document.querySelector('.efundForm').submit();
    } else {
        buttonElem.disabled = false;
        //It's not valid, so say something
    }
}

function showPaymentInfoConfirmPopup() {
    //document.getElementById('modal-oneclick-container').modal('show');
    const modalOneClick = new bootstrap.Modal(document.getElementById('modal-oneclick-container'), {});
    modalOneClick.show();
    changeModalView('#apple-pay-popup');
}

function toggleDefaultPaymentContainers(show) {
    defaultShown = show;
    if (show) {
        if (!document.getElementById('panelEmployOcc')) {
            fadeOut(document.getElementById('section-personal'), 'fast');
        }
        document.querySelectorAll('.default-pay-show').forEach((defaultPayShowElem) => {
            fadeIn(defaultPayShowElem, 'fast');
        });
        document.querySelectorAll('.default-pay-hide').forEach((defaultPayHideElem) => {
            fadeOut(defaultPayHideElem, 'fast');
        });
    } else {
        if (appleShown) {
            toggleApplePayContainers(false);
        }

        if (googleShown) {
            toggleGooglePayContainers(false);
        }

        if (document.getElementById('section-personal')) {
            fadeIn(document.getElementById('section-personal'), 'fast');
        }
        document.querySelectorAll('.default-pay-show').forEach((defaultPayShowElem) => {
            fadeOut(defaultPayShowElem, 'fast');
        });
        document.querySelectorAll('.default-pay-hide').forEach((defaultPayHideElem) => {
            fadeIn(defaultPayHideElem, 'fast');
        });
    }
}

// =================================
// Apple Pay
// =================================
async function isApplePayAllowed() {
    if (document.getElementById('disableDonations')) {
        return false;
    }
    let merchant = "";
    if (document.getElementById('panelMerchant')) {
        merchant = document.getElementById('panelMerchant').textContent.trim();
    }
    if (!merchant) {
        // No merchantID
        return false;
    }

    const achonly = (new URLSearchParams(window.location.search)).get("achonly");
    if (achonly != "true" && !isIframe() && window.ApplePaySession && window.ApplePaySession.supportsVersion(4)) {

        if (getBrowser() === "Safari") {
            // applePayCapabilities doesn't work reliably on Safari for some reason, and canMakePaymentsWithActiveCard only works on Safari...
            return await window.ApplePaySession.canMakePaymentsWithActiveCard(merchant);
        }

        // Else
        result = (await window.ApplePaySession.applePayCapabilities(merchant)).paymentCredentialStatus;

        ////////////////////////
        // Test accounts
        if (merchant == "V2DKXMZBHML7E") {
            // Test accounts don't show as having a card, let test account see the button
            console.log(result);
            return result != "applePayUnsupported";
        }
        ///////////////////////////


        if (result == "paymentCredentialsAvailable") {
            // They have a card on file, must display Apple Pay button
            return true;
        }

        if (result == "paymentCredentialStatusUnknown") {
            // Third-party browser, they might have a card on file

            // Windows shows this, don't show button on Windows
            return false;
        }

        if (result == "paymentCredentialsUnavailable") {
            // They don't have a card on file, we don't want to display Apple Pay button
            return false;
        }

        if (result == "applePayUnsupported") {
            // Apple Pay not supported, we can't display Apple Pay button
            return false;
        }
        // Should not trip
        return false;
    } else {
        return false;
    }
}

async function setupApplePay() {
    if (!(await isApplePayAllowed())) {
        toggleApplePayContainers(false);
        return;
    }

    try {
        let applepay = paypal.Applepay();
        let applepayConfig = await applepay.config();

        if (!applepayConfig.isEligible) {
            toggleApplePayContainers(false);
            return;
        }

        // Add Click Handlers
        document.getElementById('apple-pay-submit').addEventListener('click', async function () {
            if (document.getElementById('section-amount') && !validateAmount(document.querySelector('.efundForm'))) {
                //Hover to the payment section if payment is invalid
                document.getElementById("section-amount").scrollIntoView({ behavior: "smooth" });
                return;
            }


            //if (document.getElementById('ApplePayDonation').value === 'True' && document.getElementById('BraintreeNonce').value) {
            //    //Looks like they exited out of Apple Pay confirm popup
            //    showPaymentInfoConfirmPopup();
            //} else {
            payWithApplePay(this, applepayConfig);
            //}
        });
        toggleApplePayContainers(true);
    } catch (err) {
        toggleApplePayContainers(false);
        handleApplePayException(err, "payWithApplePay", "catch", 'There was an error paying with Apple Pay');
    }
}

function handleApplePaySetupException(err, target, action, consoleMessage) {
    console.error(consoleMessage, err);
    toggleApplePayContainers(false);
    //document.getElementById('show-apple-pay').style.display = 'none';
    document.getElementById('hide-default-pay').style.display = 'none';
}

function payWithApplePay(submitElem, applepayConfig) {
    if (!validateAndLogApplePayForm(submitElem)) {
        return;
    }

    try {
        let applepay = paypal.Applepay();

        //Payment request
        var paymentRequest = generateApplePaymentRequest(applepayConfig);

        var session = new ApplePaySession(4, paymentRequest);

        session.onvalidatemerchant = (event) => {
            applepay.validateMerchant({
                validationUrl: event.validationURL,
                displayName: document.getElementById('AccountName').value.substring(0, 64)
            })
                .then(validateResult => {
                    session.completeMerchantValidation(validateResult.merchantSession);
                })
                .catch(err => {
                    handleApplePayException(err, "payWithApplePay", "session.onvalidatemerchant", 'There was an error validating merchant');
                    session.abort();
                });

        };

        session.onpaymentauthorized = (event) => {
            let amount = parseFloat(document.getElementById('Amount').value)
            let merchant = "";
            if (document.getElementById('panelMerchant')) {
                merchant = document.getElementById('panelMerchant').textContent.trim();
            }
            let apiBase = document.getElementById('panelAppleEndPoint').textContent.trim();
            fetch(`${apiBase}/PayPal/orders/create/${merchant}/${amount}/true`, {
                method: 'post',
            })
                .then(res => res.text())
                .then((orderId) => {
                    if (!orderId || orderId == '-1') {
                        console.log("Failed to create order");
                        session.completePayment(ApplePaySession.STATUS_FAILURE);
                        return;
                    }

                    document.getElementById('PayPalOrderID').value = orderId;
                    applepay.confirmOrder({
                        orderId: orderId,
                        token: event.payment.token,
                        billingContact: event.payment.billingContact
                    })
                        .then(confirmResult => {
                            document.getElementById('BraintreeNonce').value = JSON.stringify(confirmResult.approveApplePayPayment.payment_source.apple_pay.card);
                            session.completePayment(ApplePaySession.STATUS_SUCCESS);

                            toggleGooglePayContainers(false);
                            googleAllowed = false;

                            //Take care of the things
                            fadeOut(document.getElementById('apple-pay-failure'), 'fast');
                            document.getElementById('ApplePayDonation').value = 'True';
                            fillInfoFromApplePay(event.payment.billingContact, event.payment.shippingContact);
                            updateFieldsOnSubmit();
                            disableAmountAffectors();

                            if (validateInputsFromPaymentInfo()) {
                                //document.querySelector('.efundForm').dispatchEvent(new Event('submit'));
                                document.querySelector('.efundForm').submit();
                            } else {
                                //Hide the choose a different payment method (no going back!)
                                fadeOut(document.querySelector('.btn-hide-default-pay'), 'fast');
                                showPaymentInfoConfirmPopup();
                            }
                        })
                        .catch(confirmError => {
                            if (confirmError) {
                                console.error('Error confirming order with applepay token');
                                console.error(confirmError);
                                session.completePayment(ApplePaySession.STATUS_FAILURE);
                            }
                        });
                }).catch((error) => {
                    console.log("Throw in create order");
                    console.log(error);
                    session.completePayment(ApplePaySession.STATUS_FAILURE);
                    return;
                });
        };

        session.begin();

    } catch (err) {
        handleApplePayException(err, "payWithApplePay", "catch", 'There was an error paying with Apple Pay');
    }
}

function handleApplePayException(err, target, action, consoleMessage) {
    var failMessage = document.querySelector('#apple-pay-failure p').innerHTML;
    console.error(consoleMessage, err);
    fadeIn(document.getElementById('apple-pay-failure'), 'fast');
}

function generateApplePaymentRequest(applepayConfig) {
    var amount = parseFloat(document.getElementById('Amount').value);

    return {
        countryCode: applepayConfig.countryCode,
        currencyCode: "USD",
        merchantCapabilities: applepayConfig.merchantCapabilities,
        supportedNetworks: applepayConfig.supportedNetworks,
        total: {
            label: 'eFund Connect',
            amount: amount
        },
        requiredShippingContactFields: [
            "phone",
            "email"
        ],
        requiredBillingContactFields: [
            "name",
            "postalAddress"
        ]
    }
}

function fillInfoFromApplePay(addressInfo, contactInfo) {
    //Fill inputs
    document.getElementById("NameFirst").value = (addressInfo.givenName);
    document.getElementById("NameLast").value = (addressInfo.familyName);

    document.getElementById("StreetAddress").value = (addressInfo.addressLines[0]);

    document.getElementById("City").value = (addressInfo.locality);
    var stateVal = addressInfo.administrativeArea;
    if (!stateVal) {
        stateVal = '';
    } else {
        stateVal = stateVal.toUpperCase();
    }
    document.getElementById("StreetState").value = (stateVal);
    document.getElementById("StreetZip").value = (addressInfo.postalCode);

    // Pull real Address fields into the decoys
    updateDecoyAddress();

    document.getElementById('Email').value = (contactInfo.emailAddress);
    document.getElementById('Phone').value = (contactInfo.phoneNumber);
    document.getElementById('Phone').dispatchEvent(new Event('input'));
    document.getElementById('Phone').dispatchEvent(new Event('change'));
}

var appleShown;
function toggleApplePayContainers(show) {
    appleShown = show;
    if (show) {
        toggleDefaultPaymentContainers(true);
        document.querySelectorAll('.apple-pay-show').forEach((applePayShowElem) => {
            fadeIn(applePayShowElem, 'fast');
        });
        document.querySelectorAll('.apple-pay-hide').forEach((applePayHideElem) => {
            fadeOut(applePayHideElem, 'fast');
        });
    } else {
        toggleDefaultPaymentContainers(googleShown);
        document.querySelectorAll('.apple-pay-show').forEach((applePayShowElem) => {
            fadeOut(applePayShowElem, 'fast');
        });
        document.querySelectorAll('.apple-pay-hide').forEach((applePayHideElem) => {
            fadeIn(applePayHideElem, 'fast');
        });
    }
}

async function toggleApplePayFromServerData() {
    const hasOptedForCCPayment = (document.getElementById('ApplePayDonation').value === 'False'),
        hasCCValue = Boolean(document.getElementById('CCNumber').value);

    if ((await isApplePayAllowed()) && hasOptedForCCPayment && hasCCValue) {
        toggleApplePayContainers(false);
    }
}

// =================================
// Google Pay
// =================================

var googleShown;
var googleAllowed = true;

/*
* Define the version of the Google Pay API referenced when creating your
* configuration
*/

let baseRequest = {
    apiVersion: 2,
    apiVersionMinor: 0,
};

let paymentsClient = null,
    allowedGooglePaymentMethods = null,
    merchantInfo = null;

/* Configure your site's support for payment methods supported by the Google Pay */

// https://developers.google.com/pay/api/web/reference/request-objects#IsReadyToPayRequest
function getGoogleIsReadyToPayRequest(allowedGooglePaymentMethods) {
    return Object.assign({}, baseRequest, {
        allowedPaymentMethods: allowedGooglePaymentMethods,
        existingPaymentMethodRequired: true,
    });
}

/* Fetch Default Config from PayPal via PayPal SDK */

async function getGooglePayConfig() {
    try {
        if (allowedGooglePaymentMethods == null || merchantInfo == null) {
            const googlePayConfig = await paypal.Googlepay().config();
            allowedGooglePaymentMethods = googlePayConfig.allowedPaymentMethods;
            merchantInfo = googlePayConfig.merchantInfo;
            merchantInfo.merchantName = document.getElementById('AccountName').value.substring(0, 64);

            if (!googlePayConfig.isEligible) {
                googleAllowed = false;
                toggleGooglePayContainers(false);
            }
            baseRequest.apiVersion = googlePayConfig.apiVersion;
            baseRequest.apiVersionMinor = googlePayConfig.apiVersionMinor;
        }
    } catch {
        googleAllowed = false;
        toggleGooglePayContainers(false);
    }

    return {
        allowedGooglePaymentMethods,
        merchantInfo,
    };
}

/* Configure support for the Google Pay API */

async function getGooglePaymentDataRequest() {
    const paymentDataRequest = Object.assign({}, baseRequest);
    const { allowedGooglePaymentMethods, merchantInfo } = await getGooglePayConfig();

    paymentDataRequest.allowedPaymentMethods = allowedGooglePaymentMethods;
    paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
    paymentDataRequest.merchantInfo = merchantInfo;
    paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
    paymentDataRequest.shippingAddressRequired = true;
    paymentDataRequest.shippingAddressParameters = {};
    paymentDataRequest.shippingAddressParameters.allowedCountryCodes = ["US"];
    paymentDataRequest.shippingAddressParameters.phoneNumberRequired = true;
    paymentDataRequest.emailRequired = true;
    ;

    return paymentDataRequest;

}

function onGooglePaymentAuthorized(paymentData) {

    return new Promise(function (resolve, reject) {
        processGooglePayment(paymentData)
            .then(function (data) {
                resolve({ transactionState: "SUCCESS" });
            })

            .catch(function (errDetails) {
                resolve({ transactionState: "ERROR" });
            });
    });
}

function getGooglePaymentsClient() {

    if (paymentsClient === null) {
        let enviroment = "";

        if (document.getElementById('panelEnvironment')) {
            enviroment = document.getElementById('panelEnvironment').textContent.trim().toUpperCase();
        }

        if (!enviroment) {
            // Can't make client
            googleAllowed = false;
            toggleGooglePayContainers(false);
            return;
        }

        paymentsClient = new google.payments.api.PaymentsClient({
            environment: enviroment,
            merchantInfo: merchantInfo,
            paymentDataCallbacks: {
                onPaymentAuthorized: onGooglePaymentAuthorized,
            },
        });
    }

    return paymentsClient;
}
function isGooglePayAllowed() {
    if (googleAllowed) {
        if (document.getElementById('disableDonations')) {
            googleAllowed = false;
            return googleAllowed;
        }
        let merchant = "";
        if (document.getElementById('panelMerchant')) {
            merchant = document.getElementById('panelMerchant').textContent.trim();
        }
        if (!merchant) {
            // No merchantID
            googleAllowed = false;
        }

        ////////////////////////
        // Temp Disable

        if (merchant != "8BPNHZDCXQ8G4" && merchant != "V2DKXMZBHML7E") {
            googleAllowed = false;
        }


        ///////////////////////////

        if (!document.getElementById('panelEnvironment')) {
            googleAllowed = false;
        }

        if (googleAllowed) {
            const achonly = (new URLSearchParams(window.location.search)).get("achonly");
            googleAllowed = achonly != "true" && !isIframe();

        }
    }

    if (!googleAllowed) {
        toggleGooglePayContainers(false);
    }
    return googleAllowed;
}

/////////////////////////////
// Temp Debug

function ShowGoogleOverride() {
    googleAllowed = true;
    if (!googleButtonExists) {
        addGooglePayButton();
    }
}

////////////////////////////

async function onGooglePayLoaded() {

    if (!isGooglePayAllowed()) {
        return;
    }

    const { allowedGooglePaymentMethods } = await getGooglePayConfig();
    const paymentsClient = getGooglePaymentsClient();


    let iRTPpayload = getGoogleIsReadyToPayRequest(allowedGooglePaymentMethods);
    console.log("iRTP Request PayLoad")
    console.log(iRTPpayload)
    paymentsClient
        .isReadyToPay(iRTPpayload)
        .then(function (response) {
            console.log("iRTP Response")
            console.log(response);
            if (response.result && response.paymentMethodPresent) {
                addGooglePayButton();
            } else {
                googleAllowed = false;
                toggleGooglePayContainers(false);
            }
        })
        .catch(function (err) {
            googleAllowed = false;
            toggleGooglePayContainers(false);
            console.error(err);
        });
}
var googleButtonExists = false;
function addGooglePayButton() {
    const paymentsClient = getGooglePaymentsClient();
    const button = paymentsClient.createButton({
        buttonType: 'plain',
        onClick: onGooglePaymentButtonClicked,
        allowedPaymentMethods: allowedGooglePaymentMethods,
        buttonSizeMode: 'fill',
        buttonRadius: 0,
    });
    document.getElementById("google-pay-submit").appendChild(button);
    googleButtonExists = true;
    toggleGooglePayContainers(true);
}

function getGoogleTransactionInfo() {
    var amount = parseFloat(document.getElementById('Amount').value);

    return {

        countryCode: "US",
        currencyCode: "USD",
        totalPriceStatus: "FINAL",
        totalPrice: amount.toString(),
        totalPriceLabel: "eFund Connect",
    };
}

async function onGooglePaymentButtonClicked() {

    if (document.getElementById('section-amount') && !validateAmount(document.querySelector('.efundForm'))) {
        //Hover to the payment section if payment is invalid
        document.getElementById("section-amount").scrollIntoView({ behavior: "smooth" });
        return;
    }

    if (document.getElementById('GooglePayDonation').value === 'True' && document.getElementById('BraintreeNonce').value) {
        //Looks like they exited out of Apple Pay confirm popup
        showPaymentInfoConfirmPopup();
        return;
    }

    if (!validateAndLogGooglePayForm(document.getElementById('google-pay-submit'))) {
        return;
    }

    const paymentDataRequest = await getGooglePaymentDataRequest();
    // paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
    const paymentsClient = getGooglePaymentsClient();
    paymentsClient.loadPaymentData(paymentDataRequest);
}

async function processGooglePayment(paymentData) {

    try {

        /* Create Order */
        let id = -1;
        let amount = parseFloat(document.getElementById('Amount').value)
        let merchant = "";
        if (document.getElementById('panelMerchant')) {
            merchant = document.getElementById('panelMerchant').textContent.trim();
        }
        let apiBase = document.getElementById('panelAppleEndPoint').textContent.trim();

        let orderCreateResponse = await fetch(`${apiBase}/PayPal/orders/create/${merchant}/${amount}/false`, {
            method: 'post',
        });

        id = await orderCreateResponse.text();

        if (!id || id == '-1') {
            console.log("Failed to create order");
            return { transactionState: "ERROR" };
        }

        document.getElementById('PayPalOrderID').value = id;
        toggleApplePayContainers(false);


        const orderConfirmResponse = await paypal.Googlepay().confirmOrder({
            orderId: id,
            paymentMethodData: paymentData.paymentMethodData,
        });

        document.getElementById('BraintreeNonce').value = JSON.stringify(orderConfirmResponse.payment_source.google_pay.card);
        fillInfoFromGooglePay(paymentData);
        updateFieldsOnSubmit();
        disableAmountAffectors();

        document.getElementById('GooglePayDonation').value = 'True';

        if (orderConfirmResponse.status === "APPROVED") {
            /* Capture the Order */

            if (validateInputsFromPaymentInfo()) {
                document.querySelector('.efundForm').submit();
            } else {
                //Hide the choose a different payment method (no going back!)
                fadeOut(document.querySelector('.btn-hide-default-pay'), 'fast');
                showPaymentInfoConfirmPopup();
            }

            return { transactionState: "SUCCESS" };
        }
        else if (orderConfirmResponse.status === "PAYER_ACTION_REQUIRED") {
            // 3DS Secure authentication
            // Confirm Payment Completed Payer Action Required
            paypal.Googlepay().initiatePayerAction({ orderId: id });
            return { transactionState: "SUCCESS" };
        }
        else {
            return {
                transactionState: "ERROR",
                error: {
                    reason: "PAYMENT_DATA_INVALID",
                    message: "Failed to authorize payment. Try another card",
                    intent: "PAYMENT_AUTHORIZATION"
                }
            };
        }

    } catch (err) {
        console.error(err);
        return {
            transactionState: "ERROR",
            error: {
                message: err.message,
            },
        };
    }
}

function fillInfoFromGooglePay(paymentData) {
    //Fill inputs
    let name = paymentData.paymentMethodData.info.billingAddress.name.split(" ");
    document.getElementById("NameFirst").value = (name[0]);

    if (name.length > 1) {
        document.getElementById("NameLast").value = (name[name.length - 1]);
    }

    document.getElementById("StreetAddress").value = (paymentData.paymentMethodData.info.billingAddress.address1);

    document.getElementById("City").value = (paymentData.paymentMethodData.info.billingAddress.locality);
    var stateVal = paymentData.paymentMethodData.info.billingAddress.administrativeArea;
    if (!stateVal) {
        stateVal = '';
    } else {
        stateVal = stateVal.toUpperCase();
    }
    document.getElementById("StreetState").value = (stateVal);
    document.getElementById("StreetZip").value = (paymentData.paymentMethodData.info.billingAddress.postalCode);

    // Pull real Address fields into the decoys
    updateDecoyAddress();

    document.getElementById('Email').value = (paymentData.email);
    document.getElementById('Phone').value = (paymentData.shippingAddress.phoneNumber);
    document.getElementById('Phone').dispatchEvent(new Event('input'));
    document.getElementById('Phone').dispatchEvent(new Event('change'));
}

function toggleGooglePayContainers(show) {

    if (googleAllowed) {
        googleShown = show && googleButtonExists;
    } else {
        googleShown = false;
        show = false;
    }

    if (show) {
        toggleDefaultPaymentContainers(true);
        document.querySelectorAll('.google-pay-show').forEach((googlePayShowElem) => {
            fadeIn(googlePayShowElem, 'fast');
        });
        document.querySelectorAll('.google-pay-hide').forEach((googlePayHideElem) => {
            fadeOut(googlePayHideElem, 'fast');
        });
    } else {
        toggleDefaultPaymentContainers(appleShown);
        document.querySelectorAll('.google-pay-show').forEach((googlePayShowElem) => {
            fadeOut(googlePayShowElem, 'fast');
        });
        document.querySelectorAll('.google-pay-hide').forEach((googlePayHideElem) => {
            fadeIn(googlePayHideElem, 'fast');
        });
    }
}

function toggleGooglePayFromServerData() {
    const hasOptedForCCPayment = (document.getElementById('GooglePayDonation').value === 'False'),
        hasCCValue = Boolean(document.getElementById('CCNumber').value);

    if (isGooglePayAllowed() && hasOptedForCCPayment && hasCCValue) {
        toggleGooglePayContainers(false);
    }
}

// =================================
// Misc. Functionality
// =================================

function isRetired() {
    return document.getElementById('Retired') && document.getElementById('Retired').checked;
}

function isRetiredOther() {
    return document.getElementById('RetiredOther') && document.getElementById('RetiredOther').checked;
}

function updateRequireAmount() {
    // Employer/Occupation Required Amount
    if (isOccupationRequired()) {
        setEmploymentRequired(true);
        if (document.getElementById('SecondDonation') && document.getElementById('SecondDonation').value == 't') {
            setEmploymentOtherRequired(true);
        }
    } else {
        setEmploymentRequired(false);
        if (document.getElementById('SecondDonation') && document.getElementById('SecondDonation').value == 't') {
            setEmploymentOtherRequired(false);
        }
    }
}

function setEmploymentRequired(val) {
    if (!isRetired()) {
        forceEmploymentRequired(val);
    }
}
function setEmploymentOtherRequired(val) {
    if (!isRetiredOther()) {
        forceEmploymentOtherRequired(val);
    }
}

function forceEmploymentRequired(val) {
    if (document.getElementById('donor-dashboard')) {
        document.querySelectorAll('.employment-field').forEach((employmentFieldElem) => {
            if (employmentFieldElem.getAttribute('data-required') === 'true') {
                employmentFieldElem.required = val;
            }
        });
    } else {
        if (document.getElementById("Employer")) {
            document.getElementById("Employer").required = val;
        }
        if (document.getElementById("Occupation")) {
            document.getElementById("Occupation").required = val;
        }

        if (document.getElementById("EmployerCity")) {
            document.getElementById("EmployerCity").required = val;
            document.getElementById('EmployerState').required = val;
        }
    }
}

function forceEmploymentOtherRequired(val) {
    if (document.getElementById("EmployerOther")) {
        document.getElementById("EmployerOther").required = val;
    }
    if (document.getElementById("OccupationOther")) {
        document.getElementById("OccupationOther").required = val;
    }

    if (document.getElementById("EmployerCityOther")) {
        document.getElementById("EmployerCityOther").required = val;
    }
}

// Resize Amount Buttons
document.addEventListener("DOMContentLoaded", function () {
    optimizeButtonWidth();
    if (document.getElementById('OtherAmount')) {
        reduceLabelSize(document.getElementById('OtherAmount').closest('.efund-form-group'));
    }
    window.addEventListener('load', function () {
        optimizeButtonWidth();
        if (document.getElementById('OtherAmount')) {
            reduceLabelSize(document.getElementById('OtherAmount').closest('.efund-form-group'));
        }
    });
    window.addEventListener('resize', function () {
        optimizeButtonWidth();
        if (document.getElementById('OtherAmount')) {
            reduceLabelSize(document.getElementById('OtherAmount').closest('.efund-form-group'));
        }
    });
    if (document.getElementById('contribution-tab-btn')) {
        document.getElementById('contribution-tab-btn').addEventListener('click', function () {
            window.setTimeout(optimizeButtonWidth, 400);
        });
    }

    function optimizeButtonWidth() {
        var numBoxes, vpWidth, maxPerRow, numPerRow, boxWidth, boxWidthPercent;
        // Get number of buttons + Other box
        numBoxes = document.querySelectorAll('.efund_PaymentOptionItem').length + 1;

        // Determine max buttons per row based on row width
        maxPerRow = buttonsPerRow();
        if (document.querySelector('.efund_PaymentOptionItem .efund_PaymentOptionDesc')) {
            maxPerRow -= 1;
        }
        // Determine optimal buttons per row based on total number of buttons
        if (numBoxes < maxPerRow) {
            numPerRow = numBoxes;
        } else if ((numBoxes % maxPerRow === 0) || ((numBoxes + 1) % maxPerRow === 0)) {
            numPerRow = maxPerRow;
        } else if ((numBoxes % (maxPerRow - 1) === 0) || ((numBoxes + 1) % (maxPerRow - 1) === 0)) {
            numPerRow = maxPerRow - 1;
        } else if ((maxPerRow === 5) && ((numBoxes % (maxPerRow - 2) === 0) || ((numBoxes + 1) % (maxPerRow - 2) === 0))) {
            numPerRow = maxPerRow - 2;
        } else {
            numPerRow = maxPerRow;
        }
        boxWidth = 1 / numPerRow;
        boxWidthPercent = Math.floor(boxWidth * 10000) / 100;
        // Set button and input width
        document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
            paymentOptionItemElem.style.width = boxWidthPercent + '%';
        });
        document.querySelectorAll('.efund_PaymentOptionOther').forEach((paymentOptionOtherElem) => {
            paymentOptionOtherElem.style.width = boxWidthPercent + '%';
        });
    }

    // Get max number of buttons per row based on viewport width
    function buttonsPerRow() {
        if (document.querySelector('.efund_PaymentOptionList')) {
            var rowWidth = document.querySelector('.efund_PaymentOptionList').offsetWidth;
            if (rowWidth <= 293) {
                return 2;
            } else if (rowWidth <= 393) {
                return 3;
            } else if (rowWidth <= 513) {
                return 4;
            } else {
                return 5;
            }
        }
        return;
    }
});

// Recurring Buttons Styling
document.addEventListener("DOMContentLoaded", function () {
    if (document.querySelector('#efund-recurring-btns .btn-wrapper')) {
        const recurringBtnCount = document.querySelectorAll('#efund-recurring-btns .btn-wrapper').length;
        document.querySelectorAll('#efund-recurring-btns .btn-wrapper')[recurringBtnCount - 1].classList.add('last');
    }
});

// Resize Recurring Buttons
window.addEventListener('load', function () {
    if (document.querySelector('#efund-recurring-btns .btn-wrapper')) {
        resizeRecurringButtons();
    }
});
window.addEventListener('resize', function () {
    if (document.querySelector('#efund-recurring-btns .btn-wrapper')) {
        resizeRecurringButtons();
    }
});

document.addEventListener("DOMContentLoaded", function () {
    if (document.getElementById('contribution-tab-btn')) {
        document.getElementById('contribution-tab-btn').addEventListener('click', function () {
            if (document.querySelector('#efund-recurring-btns .btn-wrapper')) {
                window.setTimeout(resizeRecurringButtons, 400);
            }
        });
    }

});

//document.getElementById('efund-recurring-btns efund_choice span').each(function () {
//    this.width
//})

function resizeRecurringButtons() {
    var minBtnWidth, btnListElem, rowWidth, btnsPerRow, numBtns, btnWidth, inputWidth;
    if (window.location.href.indexOf("lang=sp") > -1) {
        minBtnWidth = 120;
    } else {
        minBtnWidth = 84;
    }

    btnListElem = document.getElementById('efund-recurring-btns');
    rowWidth = btnListElem.clientWidth - (parseInt(getComputedStyle(btnListElem).getPropertyValue('padding-left')) + parseInt(getComputedStyle(btnListElem).getPropertyValue('padding-right')));
    btnsPerRow = Math.floor(rowWidth / minBtnWidth);
    numBtns = btnListElem.querySelectorAll('.btn-wrapper').length;

    if (numBtns <= btnsPerRow) {
        btnWidth = Math.floor((rowWidth / numBtns)) - 0.5;
        inputWidth = rowWidth;
        btnListElem.querySelector('.btn').style.height = '44px';
    } else {
        btnWidth = Math.floor(rowWidth / 2);
        inputWidth = Math.floor(rowWidth / 2);
        btnListElem.querySelector('.btn').style.height = '54px';
    }

    // Set button and input width
    btnListElem.querySelectorAll('.btn-wrapper').forEach((btn) => {
        btn.style.width = btnWidth.toString() + 'px';
    });
    document.querySelector('.efund_RecurringDonation').style.width = inputWidth.toString() + 'px';
}

// Checkbox-Buttons
document.addEventListener("DOMContentLoaded", function () {
    //document.querySelectorAll('.checkbox-button').find('label').prepend('<i class="material-icons">radio_button_unchecked</i>');  
    document.querySelectorAll('.checkbox-button input[type="checkbox"]').forEach((checkboxBtnElem) => {
        checkIfChecked(checkboxBtnElem);
        checkboxBtnElem.addEventListener('change', function () {
            checkIfChecked(this);
        });
        checkboxBtnElem.addEventListener('focus blur', function () {
            this.closest('.checkbox-button').querySelector('label').classList.add('focused');
        });
    });

    function checkIfChecked(checkboxElem) {
        var labelElem = checkboxElem.closest('.checkbox-button').querySelector('label');
        if (checkboxElem.checked) {
            labelElem.classList.add('selected');
            if (labelElem.querySelector('.fa-check')) {
                labelElem.querySelector('.fa-check').classList.remove('d-none');
            }
        } else {
            labelElem.classList.remove('selected');
            if (labelElem.querySelector('.fa-check')) {
                labelElem.querySelector('.fa-check').classList.add('d-none');
            }
        }
    }
});

// Add Custom Checkbox Mark & Focus Style
document.addEventListener("DOMContentLoaded", function () {
    // Show/hide custom check mark
    document.querySelectorAll('.custom-check input[type="checkbox"]').forEach((customCheckboxElem) => {
        customCheck(customCheckboxElem);

        customCheckboxElem.addEventListener('change', function () {
            customCheck(this);
        });

        // Add/remove focus styling to custom check box
        customCheckboxElem.addEventListener('focus', function () {
            this.parentNode.querySelector('label').classList.add('focused');
        });
        customCheckboxElem.addEventListener('blur', function () {
            this.parentNode.querySelector('label').classList.remove('focused');
        });
    });
});

function customCheck(checkboxElem) {
    if (checkboxElem.checked) {
        checkboxElem.parentNode.querySelector('label').classList.add('show-check');
    } else {
        checkboxElem.parentNode.querySelector('label').classList.remove('show-check');
    }
}

// Retired Checkboxes
document.addEventListener("DOMContentLoaded", function () {
    // Hide employment options if retired
    if (document.getElementById('Retired')) {
        document.getElementById('Retired').addEventListener('change', function () {
            if (document.getElementById('employer-info')) {
                document.getElementById('employer-info').classList.add('d-none');
            }
            if (this.checked) {
                document.querySelectorAll('.retired-toggle').forEach((retiredToggleElem) => {
                    retiredToggleElem.style.display = 'none';
                });
                forceEmploymentRequired(false);
                if (document.getElementById('btn-retired-col')) {
                    document.getElementById('btn-retired-col').classList.add('full-width');
                }
            } else {
                if (document.getElementById('btn-retired-col')) {
                    document.getElementById('btn-retired-col').classList.remove('full-width');
                }
                setTimeout(function () {
                    if (!document.getElementById('Retired').checked) {
                        document.querySelectorAll('.retired-toggle').forEach((retiredToggleElem) => {
                            fadeIn(retiredToggleElem, 'fast');
                        });
                    }
                }, 300);
                // Occupation/Employer Required Amount
                if (isOccupationRequired()) {
                    forceEmploymentRequired(true);
                }
                else {
                    forceEmploymentRequired(false);
                }
            }
        });
    }
    if (document.getElementById('RetiredOther')) {
        document.getElementById('RetiredOther').addEventListener('change', function () {
            document.getElementById('employer-info-other').classList.add('d-none');
            if (this.checked) {
                document.querySelectorAll('.retired-toggle-other').forEach((retiredToggleOtherElem) => {
                    retiredToggleOtherElem.style.display = 'none';
                });
                forceEmploymentOtherRequired(false);
                document.getElementById('btn-retired-col-other').classList.add('full-width');
            } else {
                document.getElementById('btn-retired-col-other').classList.remove('full-width');
                setTimeout(function () {
                    if (!document.getElementById('RetiredOther').checked) {
                        document.querySelectorAll('.retired-toggle-other').forEach((retiredToggleOtherElem) => {
                            fadeIn(retiredToggleOtherElem, 'fast');
                        });
                    }
                }, 300);
                // Occupation/Employer Required Amount
                if (isOccupationRequired()) {
                    forceEmploymentOtherRequired(true);
                }
                else {
                    forceEmploymentOtherRequired(false);
                }
            }
        });
    }
});

document.querySelectorAll('.more-info-btn').forEach((moreInfoBtnElem) => {
    moreInfoBtnElem.addEventListener('click', function () {
        var tooltipId = this.getAttribute('data-toggle'),
            tooltipClassList = document.getElementById(tooltipId).classList;

        if (tooltipClassList.contains('d-none')) {
            tooltipClassList.remove('d-none');
        } else {
            tooltipClassList.add('d-none');
        }
    });
});

// Translations - Labels Resize
document.addEventListener("DOMContentLoaded", function () {
    // Make sure labels don't cover more info icons
    //document.querySelectorAll('.more-info-btn').siblings('.form-label').classList.add('label-spacing-right');
    //document.querySelectorAll('.invalid').siblings('.form-label').classList.add('label-spacing-right');
});
window.addEventListener('load', function () {
    document.querySelectorAll('.efund-form-group').forEach((formGroupElem) => {
        reduceLabelSize(formGroupElem);
    });
});
//window.smartresize(function () {
//    document.querySelectorAll('.efund-form-group').forEach((formGroupElem) => {
//        reduceLabelSize(formGroupElem);
//    })
//});

function reduceLabelSize(formGroupElem) {
    var labelElem = formGroupElem.querySelector('.form-label');
    if (labelElem) {
        var inputElem = formGroupElem.querySelector('.form-control'),
            labelWidth = getWidth(labelElem),
            inputWidth;
        //labelHeight = labelElem.height();    
        if (inputElem.classList.contains('invalid') || (formGroupElem.querySelector('.more-info-btn'))) {
            inputWidth = getWidth(inputElem) - 36;
        } else {
            inputWidth = getWidth(inputElem);
        }
        var labelIsTooLong = ((inputElem) && (labelWidth >= inputWidth));
        //var labelIsTooLong = (labelHeight > 24);
        if (labelIsTooLong) {
            labelElem.classList.add('reduced-label-size');
            //formGroupElem.closest('.row').classList.add('spacing-top');
            if (inputElem.classList.contains('invalid') || (formGroupElem.querySelector('.more-info-btn'))) {
                labelElem.classList.add('label-spacing-right');
            }
        } else {
            labelElem.classList.remove('reduced-label-size');
            //formGroupElem.closest('.row').classList.remove('spacing-top');
        }
    }
}

function getWidth(itemElem) {
    if (isHidden(itemElem)) {
        var hiddenElem = itemElem.cloneNode(true);
        document.querySelector('body').appendChild(hiddenElem);

        // calculate the width of the clone
        var width = hiddenElem.offsetWidth;

        // remove the clone from the DOM
        hiddenElem.remove();

        return width;
    } else {
        return itemElem.offsetWidth;
    }

}

function isHidden(el) {
    return (el.offsetParent === null)
}

//// Smart Resize Function
//(function ($, sr) {
//    // debouncing function from John Hann
//    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
//    var debounce = function (func, threshold, execAsap) {
//        var timeout;

//        return function debounced() {
//            var obj = this, args = arguments;
//            function delayed() {
//                if (!execAsap)
//                    func.apply(obj, args);
//                timeout = null;
//            };

//            if (timeout)
//                clearTimeout(timeout);
//            else if (execAsap)
//                func.apply(obj, args);

//            timeout = setTimeout(delayed, threshold || 100);
//        };
//    }
//    // smartresize 
//    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
//})(jQuery, 'smartresize');

if (document.getElementById('CCAddressDifferentLabel')) {
    document.getElementById('CCAddressDifferentLabel').addEventListener('click', function () {

        setTimeout(function () {
            reduceLabelSize(document.getElementById('CCZip').closest('.efund-form-group'));
        }, 600);
    });
}

// =================================
// Logging
// =================================

//Start logging
var pingAttempts = 0;
var notifyAttempts = 0;
var pingingApi, thankYouNotifying;
var firstLogUpdate = false;
document.addEventListener("DOMContentLoaded", function () {
    if (document.querySelector('.thank-you-panel')) {
        thankYouNotifying = setInterval(
            function () {
                //thankYouNotification();
            }, 3 * 1000
        );
    }
});

function thankYouNotification() {
    if (notifyAttempts > 10) {
        clearInterval(thankYouNotifying);
    }
}

function pingApi() {
    if (pingAttempts > 10) {
        clearInterval(pingingApi);
    }
}

function getBrowser() {
    try {
        let userAgent = navigator.userAgent
        // Opera 8.0+
        var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || userAgent.indexOf(' OPR/') > -1;
        if (isOpera) {
            return "Opera";
        }
        // Firefox 1.0+
        if (typeof InstallTrigger !== 'undefined' || userAgent.indexOf('FxiOS') > -1) {
            return "Firefox";
        }
        // Safari 3.0+ "[object HTMLElementConstructor]" 
        if (/constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification))
            || ((userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1 && userAgent.indexOf('CriOS') === -1 && userAgent.indexOf('FxiOS') === -1))) {
            return "Safari";
        }
        // Internet Explorer 6-11
        var isIE = /*@cc_on!@*/false || !!document.documentMode;
        if (isIE) {
            return "Internet Explorer";
        }
        // Edge 20+
        if (!isIE && !!window.StyleMedia) {
            return "Edge";
        }
        // Chrome 1 - 71
        var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
        if (isChrome || userAgent.indexOf('CriOS') > -1) {
            return "Chrome";
        }

        var isEdgeChromium = isChrome && (userAgent.indexOf("Edg") != -1);
        if (isEdgeChromium) {
            return "Edge-Chromium";
        }

        // Blink engine detection
        if ((isChrome || isOpera) && !!window.CSS) {
            return "Blink";
        }
    } catch (err) {
        return "Unknown";
    }

    return "Unknown";
}

function isMobile() {
    try {
        var check = false;
        (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
        return check;
    } catch (err) {
        return false;
    }
}

function isSmallScreen() {
    // Cut-off for the styling that splits SingleClient into two seperate columns
    return viewportWidth() < 992;
}

function isIframe() {
    return window.location !== window.parent.location;
}

// =================================
// Validation
// =================================
document.addEventListener("DOMContentLoaded", function () {
    // Validation at Submit
    document.querySelectorAll("input[type='submit'], button[type='submit']").forEach((submitBtnElem) => {
        submitBtnElem.addEventListener('click', function (e) {
            updateFieldsOnSubmit();
            updateRequireAmount();
            if (!validateAndLogForm(this)) {
                e.preventDefault(e);
            } else {
                //If donation page and ACH, then do ACH stuff
                handlePostValidation(this, e);
            }
        });
    });

    // Validate on Dashboard Load if UpdateInfo required
    window.addEventListener('load', function () {
        if ((document.getElementById('donor-dashboard')) && (document.getElementById('modal-missinginfo-container'))) {
            validateEntireForm(document.getElementById('userInfoForm'));
        }
    });
});

// Validation at Input Fields
document.addEventListener("DOMContentLoaded", function () {
    let isSubmitMidClick = false;
    document.getElementById('mainSubmit').addEventListener('mousedown', function () {
        isSubmitMidClick = true;
    })
    document.getElementById('mainSubmit').addEventListener('mouseup', function () {
        isSubmitMidClick = false;
    })
    // User exits field
    function doFieldValidateSteps(fieldElem) {
        // Don't validate individual field if about to validate entire form - 
        //   updates to error messages could move submit button's position and prevent submit click
        if (isSubmitMidClick) {
            return;
        }

        validateInput(fieldElem);
        updateInputValidationStyle(fieldElem);

        if (document.getElementById('btnPayPal')) {
            updatePayPalStatus();
        }
        updateFieldErrors();
    }
    document.querySelectorAll('.form-control').forEach((fieldElem) => {
        fieldElem.addEventListener('change', function () {
            doFieldValidateSteps(this);
        });
        fieldElem.addEventListener('blur', function () {
            doFieldValidateSteps(this);
        });
    });
    document.getElementById('StreetState').addEventListener('change', function () {
        doFieldValidateSteps(document.getElementById('StreetZip'));
    });

    if (document.getElementById('AppleState')) {
        document.getElementById('AppleState').addEventListener('change', function () {
            doFieldValidateSteps(document.getElementById('AppleZip'));
        });
    }

    // User enters field
    document.querySelectorAll('.form-control').forEach((fieldElem) => {
        fieldElem.addEventListener('focus', function () {
            this.classList.remove('invalid');
            if (this.parentNode.querySelector('.error-icon')) {
                this.parentNode.querySelector('.error-icon').remove();
            }
            if (this.parentNode.querySelector('.more-info-btn')) {
                this.parentNode.querySelector('.more-info-btn').classList.remove('red');
            }
        });
    });
    // Checkboxes
    document.querySelectorAll('.checkbox').forEach((checkboxElem) => {
        checkboxElem.addEventListener('click', function () {
            validateCheckbox(this);
            updateInputValidationStyle(this);

            if (document.getElementById('btnPayPal')) {
                updatePayPalStatus();
            }
            updateFieldErrors();
        });
    });
});

function updateFieldsOnSubmit() {
    if (document.getElementById('btnCompany')) {
        handleCompanyFieldsOnSubmit();
    }
    updateSelectedQuestionValues();
}

function handleCompanyFieldsOnSubmit() {
    if (!isCompanyDonor()) {
        clearCompanyFields();
    }
}
function isCompanyDonor() {
    return document.getElementById('btnCompany').disabled;
}
function clearCompanyFields() {
    document.querySelectorAll('#panelCompanyName input[type="text"]').forEach(companyElem => {
        companyElem.value = '';
    });
}

function updateSelectedQuestionValues() {
    if (document.querySelector('.selected-question-field-display')) {
        resetSelectedQuestionFields();
        document.querySelectorAll('.selected-question-field-display').forEach((checkboxElem, index) => {
            if (checkboxElem.checked) {
                fillFirstEmptySelectedQuestion(index);
            }
        });
        removeEmptySelectedQuestionFields();
    }
}
function resetSelectedQuestionFields() {
    const questionsCount = document.querySelectorAll('.selected-question-field-display').length,
        wrapperElem = document.querySelector('.selected-question-values-wrapper');

    wrapperElem.innerHTML = '';
    for (let i = 0; i < questionsCount; i++) {
        const questionHTML = '<input class="selected-question-field-value" id="SelectedQuestionValue' + i + '" name="Donation.SelectedQuestions[' + i + ']" type="text" value="">'
        wrapperElem.insertAdjacentHTML("beforeend", questionHTML);
    }
}
function findFirstEmptySelectedQuestion(selectedQuestions) {
    return selectedQuestions.findIndex(q => q.value === '');
}
function fillFirstEmptySelectedQuestion(value) {
    const selectedQuestionElems = document.querySelectorAll('.selected-question-field-value'),
        selectedQuestions = Array.from(selectedQuestionElems),
        selectedQuestionIndex = findFirstEmptySelectedQuestion(selectedQuestions),
        selectedQuestion = selectedQuestionElems[selectedQuestionIndex];

    selectedQuestion.value = value;
}
function removeEmptySelectedQuestionFields() {
    document.querySelectorAll('.selected-question-field-value').forEach(fieldElem => {
        if (fieldElem.value === '') {
            fieldElem.remove();
        }
    });
}

function newPostAction() {
    return {
        callbacks: [],
        add: function (callback) {
            this.callbacks.push(callback);
        },
        execute: function () {
            for (var i = 0; i < this.callbacks.length; i++) {
                this.callbacks[i]();
            }

            this.callbacks = [];
        }
    };
}

//class PostAction {
//    constructor() {
//        this.callbacks = [];
//    }

//    add(callback) {
//        this.callbacks.push(callback);
//    }

//    execute() {
//        for (var i = 0; i < this.callbacks.length; i++) {
//            this.callbacks[i]();
//        }

//        this.callbacks = [];
//    }
//}

function updateFieldErrors(submit) {
    var errorElems = document.querySelectorAll('.error:not([style*="display: none"])');
    if (errorElems.length === 0) {
        document.getElementById('field-error').innerHTML = ('');
        document.getElementById('field-error').style.display = 'none';
        return;
    }

    if (submit) {
        if (errorElems.length === 1) {
            const errorElem = errorElems[0];
            const fieldId = errorElem.hasAttribute('data-errorfor') ? errorElem.getAttribute('data-errorfor') : null;
            var fieldLabel
            try {
                fieldLabel = fieldId ? document.querySelector('label[for="' + fieldId + '"]').textContent : null;
            } catch {
                // Can throw TypeError if document.querySelector('label[for="' + fieldId + '"]') returns null, preventing submission from aborting
                // If the query fails, assign null
                fieldLabel = null;
            }
            const errorMsg = (errorElem.textContent === 'Please fill out this field.' && fieldLabel) ?
                'Please fill out the ' + fieldLabel + ' field.' :
                errorElem.textContent;
            document.getElementById('field-error').innerHTML = errorMsg;
        } else {
            document.getElementById('field-error').innerHTML = document.getElementById('trans-validate33').textContent;
        }
        fadeIn(document.getElementById('field-error'), 'fast');
        //document.getElementById('field-error').scrollIntoView({ behavior: "smooth" })
    }
}

function validateAndLogForm(submitBtnElem, e) {
    var formElem = submitBtnElem.closest('form');
    if (!validateEntireForm(formElem)) {
        updateFieldErrors(true);
        scrollToFirstError();
        return false;
    }

    return true;
}

function scrollToFirstError() {
    if (document.querySelector('.efund-tooltip.error')) {
        const firstTooltip = getFirstVisibleElement(document.querySelectorAll('.efund-tooltip.error'));
        if (!isInViewport(firstTooltip)) {
            firstTooltip.scrollIntoView(false);
        }
    }
}
function getFirstVisibleElement(elements) {
    for (i = 0; i < elements.length; i++) {
        const element = elements[i];
        if (element.offsetWidth > 0 || element.offsetHeight > 0) {
            return element;
        }
    }
}

function validateAndLogApplePayForm(submitBtnElem) {
    var formElem = submitBtnElem.closest('form');
    if (!validateApplePayForm(formElem)) {
        // Show error message below submit button for smaller screens
        if (isSmallScreen()) {
            fadeIn(document.getElementById('submit-error'), 'fast');
        }
        scrollToFirstError();
        return false;
    }
    // Hide error message below submit button for smaller screens
    fadeOut(document.getElementById('submit-error'), 'fast');

    return true;
}

function validateAndLogGooglePayForm(submitBtnElem) {
    var formElem = submitBtnElem.closest('form');
    if (!validateGooglePayForm(formElem)) {
        // Show error message below submit button for smaller screens
        if (isSmallScreen()) {
            fadeIn(document.getElementById('submit-error'), 'fast');
        }
        scrollToFirstError();
        return false;
    }
    // Hide error message below submit button for smaller screens
    fadeOut(document.getElementById('submit-error'), 'fast');

    return true;
}

function validateEntireForm(formElem) {
    var result = validateFormExceptInputs(formElem);
    result = validateInputs(formElem) && result;
    return result;
}

function isFormValid(formElem) {
    updateRealAddress();
    return areInputsValid(formElem) &&
        isAmountValid(formElem) &&
        areCheckboxesValid(formElem) &&
        isGoogleCaptchaValid(formElem) &&
        isCoverFeeValid();
}

function validateFormExceptInputs(formElem) {
    var errorCount = ((!validateAmount(formElem)
        //|| !validateTicketAmount(formElem)
    ) +
        !validateAllCheckboxes(formElem) +
        !validateGoogleCaptcha(formElem) +
        !validateCoverFee() +
        validateIsSpammer());

    return errorCount == 0;
}

function validateIsSpammer() {
    var post = newPostAction();

    if (isSpammer()) {
        document.getElementById('submit-error').style.display = 'block';
    }

    post.execute();
    return isSpammer();
}

function isSpammer() {
    return !!document.querySelector('.antigate_solver');
}

//function isSpammer() {
//    //return !!document.querySelector('.antigate_solver');

//    // make sure DOM has no 'antigate_solver' class (Anti-Captcha's browser extension)
//    if (document.querySelector('.antigate_solver')) {
//        return true;
//    }

//    // make sure recaptcha HTML structure has no unexpected elements
//    if (document.querySelector('.g-recaptcha')) {
//        return !isValidRecaptchaStructure(document.querySelector('.efund-recaptcha-wrapper'))
//    }

//    return false;
//}

function isValidRecaptchaStructure(wrapperElement) {
    if (wrapperElement.children.length === 2 && wrapperElement.children[0].classList.contains('g-recaptcha')) {
        const recaptchaElement = wrapperElement.children[0];

        if (recaptchaElement.children.length === 0) {
            return true;
        }

        if (recaptchaElement.children.length === 2 &&
            recaptchaElement.children[0].children.length === 2 &&
            recaptchaElement.children[0].children[0].children.length === 1) {
            return true;
        }
    }

    return false;
}

function validateApplePayConfirm() {
    //var result = true;
    //document.getElementById('apple-pay-popup').find('.form-control:visible').each(function () {
    //    if (!validateInput(this)) {
    //        result = false;
    //    }
    //    updateInputValidationStyle(this);
    //    if (document.getElementById('donor-dashboard').length === 0) {
    //    }
    //});

    //if (!result) {
    //    return false;
    //}

    var popupElem = document.getElementById('apple-pay-popup');
    if (!validateApplePayName() || !validateApplePayPhone() || !validateApplePayAddress()) {
        return false;
    }

    return true;
}

function validateApplePayName() {

    if (document.getElementById('apple-popup-name').style.display == 'flex') {
        if (!validateInput(document.getElementById('AppleNameFirst'))) {
            return false;
        };
        if (!validateInput(document.getElementById('AppleNameLast'))) {
            return false;
        };
    }

    return true;
}

function validateApplePayPhone() {

    if (document.getElementById('apple-popup-phone').style.display == 'flex') {
        if (!validateInput(document.getElementById('ApplePhone'))) {
            return false;
        };
    }

    return true;
}

function validateApplePayAddress() {

    if (document.getElementById('apple-popup-address').style.display == 'block') {
        if (!validateInput(document.getElementById('AppleAddress'))) {
            return false;
        };
        if (!validateInput(document.getElementById('AppleCity'))) {
            return false;
        };
        if (!validateInput(document.getElementById('AppleState'))) {
            return false;
        };
        if (!validateInput(document.getElementById('AppleZip'))) {
            return false;
        };
    }
    return true;
}

function validateApplePayForm(formElem) {
    var result = validateFormExceptInputs(formElem);
    result = validateApplePayInputs(formElem) && result;
    return result;
}

function validateApplePayInputs(formElem) {
    var result = true;
    formElem.querySelectorAll('.form-control').forEach((fieldElem) => {
        if (!(fieldElem.closest('.apple-pay-hide') || fieldElem.closest('.default-pay-hide'))) {
            if (!validateInput(fieldElem)) {
                result = false;
            }
            updateInputValidationStyle(fieldElem);
        }
    });
    return result;
}

function validateGooglePayForm(formElem) {
    var result = validateFormExceptInputs(formElem);
    result = validateGooglePayInputs(formElem) && result;
    return result;
}

function validateGooglePayInputs(formElem) {
    var result = true;
    formElem.querySelectorAll('.form-control').forEach((fieldElem) => {
        if (!(fieldElem.closest('.google-pay-hide') || fieldElem.closest('.default-pay-hide'))) {
            if (!validateInput(fieldElem)) {
                result = false;
            }
            updateInputValidationStyle(fieldElem);
        }
    });
    return result;
}

function validateInputs(containerElem, requireVisibility) {
    if (requireVisibility === undefined) {
        requireVisibility = false;
    }

    var selector = '.form-control';
    if (requireVisibility === true) {
        // Is Apple Pay Validation
        selector += ':visible';
    }

    var result = true;
    containerElem.querySelectorAll(selector).forEach((fieldElem) => {
        if (!validateInput(fieldElem)) {
            result = false;
        }
        updateInputValidationStyle(fieldElem);
    });
    return result;
}

function areInputsValid(containerElem, requireVisibility) {
    if (requireVisibility === undefined) {
        requireVisibility = false;
    }

    var selector = '.form-control';
    if (requireVisibility === true) {
        selector += ':visible';
    }

    items = containerElem.querySelectorAll(selector);
    for (var i = 0; i < items.length; i++) {
        if (!isInputValid(items[i])) {
            return false;
        }
    }
    return true;
}

function validateAmount(formElem) {
    var post = newPostAction();
    var result = isAmountValid(formElem, post);
    post.execute();
    return result;
}

function isAmountValid(formElem, post) {
    post = post || newPostAction();
    var result = true,
        amountValue;
    if (formElem.querySelector('#Amount') && formElem.querySelector('#Amount').getAttribute('value')) {
        amountValue = formElem.querySelector('#Amount').getAttribute('value');
    }

    if (amountValue == 0) {

        result = false;
        post.add(function () {
            fadeIn(document.getElementById('missing-amount'), 'fast');

            var message = document.querySelector('#missing-amount p').innerHTML;
        });

    } else if (document.getElementById('btnSecond') && isCoupleDecimalAmountOdd(amountValue)) {

        result = false;
        post.add(function () {
            handleInvalidCoupleDecimalAmount(amountValue);
        });

    }
    return result;
}

function isCoupleDecimalAmountOdd(amountValue) {
    return (document.getElementById('btnSecond').disabled === true && (amountValue * 100 % 2 != 0));
}
function checkCoupleDecimalAmountValidation(amountValue) {

    if (document.getElementById('btnSecond') && isCoupleDecimalAmountOdd(amountValue)) {

        handleInvalidCoupleDecimalAmount(amountValue);
        return false;

    } else {

        handleValidCoupleDecimalAmount(amountValue);
        return true;
    }
}
function handleInvalidCoupleDecimalAmount(amountValue) {
    fadeIn(document.getElementById('odd-decimal-amount'), 'fast');
    //if (document.getElementById('OtherAmount').value === amountValue) {
    //    document.getElementById('OtherAmount').classList.add('invalid');
    //}

    var message = document.querySelector('#odd-decimal-amount p').innerHTML;
}
function handleValidCoupleDecimalAmount(amountValue) {
    fadeOut(document.getElementById('odd-decimal-amount'), 'fast');
    //if (document.getElementById('OtherAmount').value === amountValue) {
    //    document.getElementById('OtherAmount').classList.remove('invalid');
    //}

}

function validateAllCheckboxes(formElem) {
    var result = true;
    formElem.querySelectorAll('.checkbox').forEach((checkboxElem) => {
        if (!validateCheckbox(checkboxElem)) {
            result = false;
        }
        updateInputValidationStyle(checkboxElem);
    });
    return result;
}

function areCheckboxesValid(formElem) {
    var result = true;
    formElem.querySelectorAll('.checkbox').forEach((checkboxElem) => {
        if (!isRequiredCheckbox(checkboxElem)) {
            result = false;
        }
    });
    return result;
}

function validateGoogleCaptcha(formElem) {
    post = newPostAction();
    var result = isGoogleCaptchaValid(formElem, post);
    post.execute();
    return result;
}

function isGoogleCaptchaValid(formElem, post) {
    post = post || newPostAction();
    var result = true;

    if (shouldUseCaptcha()) {
        if (document.querySelector('.captcha-blocked')) {
            console.log('captcha blocked');
            result = false;
            post.add(function () {
                fadeIn(document.getElementById('recaptcha-error'), 'fast');
                var recaptchaMessage = document.querySelector('#recaptcha-error p').innerHTML;
            })
        }
        formElem.querySelectorAll('.g-recaptcha').forEach(function () {
            var response = grecaptcha.getResponse();
            if (response == "") {
                result = false;
                post.add(function () {
                    fadeIn(document.getElementById('recaptcha-error'), 'fast');
                    var recaptchaMessage = document.querySelector('#recaptcha-error p').innerHTML;
                })
            }
            else {
                post.add(function () {
                    document.getElementById('CaptchaResponseToken').value = (response);
                });
            }
        });
    } else {
        hideRecaptchaError();
        updateFieldErrors(false);
    }

    return result;
}

function shouldUseCaptcha() {
    const isPayPalTransaction = document.getElementById('btnPayPal') ?
        document.getElementById('btnPayPal').disabled :
        false;
    const isVenmoTransaction = document.getElementById('btnVenmo') ?
        document.getElementById('btnVenmo').disabled :
        false;

    return !(isPayPalTransaction || isVenmoTransaction || googleShown || appleShown);
}

function validateCoverFee(amount) {
    var post = newPostAction();
    var result = isCoverFeeValid(amount, post);
    post.execute();
    return result;
}

function isCoverFeeValid(amount, post) {
    post = post || newPostAction();
    if (amount === undefined && document.getElementById('Amount')) {
        amount = document.getElementById('Amount').value;
    }

    if (document.getElementById('CoverFee')) {
        //let amount = parseFloat(document.getElementById('Amount').value);
        if (document.getElementById('CoverFee').checked && amount > getAccountMax()) {
            post.add(function () {
                document.getElementById('cover-fee-error').style.display = 'block';
            });
            return false;
        }
        post.add(function () {
            document.getElementById('cover-fee-error').style.display = 'none';
        });
    }

    return true;
}

function validateCheckbox(checkboxElem) {
    var post = newPostAction();
    var result = isRequiredCheckbox(checkboxElem, post);
    post.execute();
    return result;
}

function isRequiredCheckbox(checkboxElem, post) {
    post = post || newPostAction();
    if (!checkboxElem.checked && (checkboxElem.getAttribute('required') || checkboxElem.getAttribute('required') === '')) {
        post.add(function () {
            checkboxElem.setAttribute('data-validate', 'fail');
            checkboxElem.setAttribute('data-validate-message', document.getElementById('trans-validate17').textContent);
        });
        return false;
    }

    post.add(function () {
        checkboxElem.removeAttribute('data-validate');
    });
    return true
}

function validateInput(inputElem) {
    var post = newPostAction();
    var result = isInputValid(inputElem, post);
    post.execute();
    return result;
}

function validateAndUpdateInput(inputElem) {
    validateInput(inputElem);
    updateInputValidationStyle(inputElem);
}

function isInputValid(inputElem, post) {
    post = post || newPostAction();
    var dataValidate, dataValidateMessage, isValid;
    // Trim input
    var value = (inputElem.value || '').trim();

    // If input is empty
    if (!value) {
        // If required
        if (inputElem.hasAttribute('required')) {
            post.add(function () {
                inputElem.setAttribute('data-validate', 'fail');
                if (inputElem.nodeName === 'SELECT') {
                    inputElem.setAttribute('data-validate-message', document.getElementById('trans-validate29').textContent);
                } else {
                    inputElem.setAttribute('data-validate-message', document.getElementById('trans-validate1').textContent);
                }
            });
            return false;
        }

        post.add(function () {
            inputElem.removeAttribute('data-validate');
        });
        return true;
    }

    // Check for WAF blocked characters
    if (inputElem.getAttribute('id') !== 'ExpDate' && hasDangerousCharacters(value)) {
        isValid = false;
        inputElem.title = 'Please remove the following characters: %+&/\`‘’<>“”'

        // Iterations Field
    } else if ((inputElem.getAttribute('id') === 'Iterations')) {
        isValid = isValidIterations(parseInt(value), post);

        // Street Zip
    } else if (inputElem.getAttribute('id') === 'StreetZip') {
        isValid = isValidZip(value, document.getElementById('StreetState').value);
    } else if (inputElem.getAttribute('id') === 'AppleZip') {
        isValid = isValidZip(value, document.getElementById('AppleState').value);

        // Credit Card Number
    } else if (inputElem.getAttribute('id') === 'CCNumber') {
        isValid = isValidCC(value, post);

        //Routing Number
    } else if (inputElem.getAttribute('id') === 'RoutingNumber') {
        isValid = isValidRoutingNumber(value);

        // Exp Date
    } else if (inputElem.getAttribute('id') === 'ExpDate') {
        isValid = isValidExpDate(value);
    } else if (inputElem.getAttribute('type') === 'number') {
        isValid = isValidNumber(value);

        // Email inputs
    } else if (inputElem.getAttribute('type') === 'email') {
        isValid = isValidEmail(value);

        // Checks if text input passes HTML5 validation
    } else {
        isValid = isValidTextField(inputElem, value);
    }

    if (!isValid) {
        post.add(function () {
            inputElem.setAttribute('data-validate', 'fail');

            if (inputElem.getAttribute('id') === 'OtherAmount') {
                if (document.getElementById('coupleMaxOverride')) {
                    inputElem.setAttribute('title', document.getElementById('trans-validate34').textContent);
                } else {
                    inputElem.setAttribute('title', document.getElementById('trans-validate8').textContent);
                }
                if (document.getElementById('btnPayPal')) {
                    resetPayPalContainer();
                }
            }
            inputElem.setAttribute('data-validate-message', inputElem.getAttribute('title'));
        });

    }
    else {

        post.add(function () {
            inputElem.setAttribute('data-validate', 'pass');
        });
    }

    return isValid;
}

// Text validation
function isValidTextField(inputElem, value) {
    var maxlength = inputElem.getAttribute('maxlength'),
        minlength = inputElem.getAttribute('minlength'),
        pattern,
        length = value.length;
    if (inputElem.hasAttribute('pattern')) {
        pattern = new RegExp(inputElem.getAttribute('pattern'));
    }

    return (!(maxlength && (length > maxlength)) && // Check value is less than maxlength
        !(minlength && (length < minlength)) && // Check value is greater than minlength
        !(pattern && !pattern.test(value))); // Check value matches pattern
}

function hasDangerousCharacters(value) {
    var pattern = /^[^%+&/\\`‘’'"“”<>]*$/;
    return !pattern.test(value.toString());
}

// Number validation
function isValidNumber(value) {
    var max = getAccountMax();
    var min = getAccountMin();
    return (!(max && (parseFloat(value) > (parseFloat(max)))) && // Check value is less than max
        !(min && (parseFloat(value) < parseFloat((min - 0.001))))); // Check value is greater than min
}

// Email validation
function isValidEmail(value) {
    var emailParts = value.split('.');
    var tld = emailParts[emailParts.length];
    return (tld.length >= 2);
}

// Zipcode validation
function isValidZip(zip, state) {
    if (!(/[0-9]{5}/.test(zip))) {
        return false;   //Can't be a zip code
    }

    // https://www.irs.gov/pub/irs-utl/zip_code_and_state_abbreviations.pdf

    // Slice once, use many times
    var first3 = zip.slice(0, 3);

    switch (state) {

        // States
        case 'AL':
            return ((first3 >= 350 && first3 <= 352) || (first3 >= 354 && first3 <= 369));
            break;
        case 'AK':
            return (first3 >= 995 && first3 <= 999);
            break;
        case 'AZ':
            return ((first3 >= 850 && first3 <= 853) || (first3 >= 855 && first3 <= 857) || (first3 >= 859 && first3 <= 860) || (first3 >= 863 && first3 <= 865));
            break;
        case 'AR':
            return (first3 >= 716 && first3 <= 729);
            break;
        case 'CA':
            return ((first3 >= 900 && first3 <= 908) || (first3 >= 910 && first3 <= 928) || (first3 >= 930 && first3 <= 961));
            break;
        case 'CO':
            return (first3 >= 800 && first3 <= 816);
            break;
        case 'CT':
            return ((first3 >= 60 && zip <= 6389) || (zip >= 6391 && first3 <= 69)); //Leading Zeros have to be removed
            break;
        case 'DE':
            return (first3 >= 197 && first3 <= 199);
            break;
        case 'DC':
            return (first3 == 200 || (first3 >= 202 && first3 <= 205) || first3 == 569);
            break;
        case 'FL':
            return ((first3 >= 320 && first3 <= 339) || first3 == 341 || first3 == 342 || first3 == 344 || first3 == 346 || first3 == 347 || first3 == 349);
            break;
        case 'GA':
            return ((first3 >= 300 && first3 <= 319) || first3 == 398 || first3 == 399);
            break;
        case 'HI':
            return (first3 == 967 || first3 == 968);
            break;
        case 'ID':
            return (first3 >= 832 && first3 <= 838);
            break;
        case 'IL':
            return ((first3 >= 600 && first3 <= 620) || (first3 >= 622 && first3 <= 629));
            break;
        case 'IN':
            return (first3 >= 460 && first3 <= 479);
            break;
        case 'IA':
            return ((first3 >= 500 && first3 <= 516) || (first3 >= 520 && first3 <= 528));
            break;
        case 'KS':
            return ((first3 >= 660 && first3 <= 662) || (first3 >= 664 && first3 <= 679));
            break;
        case 'KY':
            return (first3 >= 400 && first3 <= 427);
            break;
        case 'LA':
            return (first3 == 700 || first3 == 701 || (first3 >= 703 && first3 <= 708) || (first3 >= 710 && first3 <= 714));
            break;
        case 'ME':
            return (first3 >= 39 && first3 <= 49); //Leading Zeros have to be removed
            break;
        case 'MD':
            return ((first3 >= 206 && first3 <= 212) || (first3 >= 214 && first3 <= 219));
            break;
        case 'MA':
            return ((first3 >= 10 && first3 <= 27) || first3 == 55); //Leading Zeros have to be removed
            break;
        case 'MI':
            return (first3 >= 480 && first3 <= 499);
            break;
        case 'MN':
            return (first3 == 550 || first3 == 551 || (first3 >= 553 && first3 <= 567));
            break;
        case 'MS':
            return (first3 >= 386 && first3 <= 397);
            break;
        case 'MO':
            return (first3 == 630 || first3 == 631 || (first3 >= 633 && first3 <= 641) || (first3 >= 644 && first3 <= 658));
            break;
        case 'MT':
            return (first3 >= 590 && first3 <= 599);
            break;
        case 'NE':
            return (first3 == 680 || first3 == 681 || (first3 >= 683 && first3 <= 693));
            break;
        case 'NV':
            return ((first3 >= 889 && first3 <= 891) || (first3 >= 893 && first3 <= 895) || first3 == 897 || first3 == 898);
            break;
        case 'NH':
            return (first3 >= 30 && first3 <= 38); //Leading Zeros have to be removed
            break;
        case 'NJ':
            return (first3 >= 70 && first3 <= 89); //Leading Zeros have to be removed
            break;
        case 'NM':
            return (first3 == 870 || first3 == 871 || (first3 >= 873 && first3 <= 875) || (first3 >= 877 && first3 <= 884));
            break;
        case 'NY':
            return (first3 == 5 || zip == 6390 || (first3 >= 100 && first3 <= 149)); //Leading Zeros have to be removed
            break;
        case 'NC':
            return (first3 >= 270 && first3 <= 289);
            break;
        case 'ND':
            return (first3 >= 580 && first3 <= 588);
            break;
        case 'OH':
            return (first3 >= 430 && first3 <= 459);
            break;
        case 'OK':
            return (first3 == 730 || first3 == 731 || (first3 >= 734 && first3 <= 741) || (first3 >= 743 && first3 <= 749));
            break;
        case 'OR':
            return (first3 >= 970 && first3 <= 979);
            break;
        case 'PA':
            return (first3 >= 150 && first3 <= 196);
            break;
        case 'RI':
            return (first3 == 28 || first3 == 29); //Leading Zeros have to be removed
            break;
        case 'SC':
            return (first3 >= 290 && first3 <= 299);
            break;
        case 'SD':
            return (first3 >= 570 && first3 <= 577);
            break;
        case 'TN':
            return (first3 >= 370 && first3 <= 385);
            break;
        case 'TX':
            return (first3 == 733 || (first3 >= 750 && first3 <= 770) || (first3 >= 772 && first3 <= 799));
            break;
        case 'UT':
            return (first3 >= 840 && first3 <= 847);
            break;
        case 'VT':
            return ((first3 >= 50 && first3 <= 54) || (first3 >= 56 && first3 <= 59)); //Leading Zeros have to be removed
            break;
        case 'VA':
            return (first3 == 201 || (first3 >= 220 && first3 <= 246));
            break;
        case 'WA':
            return ((first3 >= 980 && first3 <= 986) || (first3 >= 988 && first3 <= 994));
            break;
        case 'WV':
            return (first3 >= 247 && first3 <= 268);
            break;
        case 'WI':
            return ((first3 >= 530 && first3 <= 532) || first3 == 534 || first3 == 535 || (first3 >= 537 && first3 <= 549));
            break;
        case 'WY':
            return ((first3 >= 820 && first3 <= 831) || first3 == 834);
            break;

        // Not States
        case 'AS':
            return (zip == 96799);
            break;
        case 'FM':
            return (first3 == 969);
            break;
        case 'GU':
            return (first3 == 969);
            break;
        case 'MH':
            return (first3 == 969);
            break;
        case 'MP':
            return (first3 == 969);
            break;
        case 'PW':
            return (first3 == 969);
            break;
        case 'PR':
            return (first3 == 6 || first3 == 7 || first3 == 9); //Leading Zeros have to be removed
            break;
        case 'VI':
            return (first3 == 8); //Leading Zeros have to be removed
            break;

        // Military Overseas
        case 'AA':
            return (first3 == 340);
            break;
        case 'AE':
            return (first3 >= 90 && first3 <= 98); //Leading Zeros have to be removed
            break;
        case 'AP':
            return (first3 >= 962 && first3 <= 966);
            break;

        default:
            return false; // Invalid state code
            break;
    }

}


// CC Number Validation
function isValidCC(ccNum, post) {
    post = post || newPostAction();
    var ccNumOnly = ccNum.replace(/\D/g, '');
    // Check length
    // If Amex
    if (/^3[47]/.test(ccNumOnly)) {
        if (!(ccNumOnly.length === 15)) {
            post.add(function () {
                document.getElementById('CCNumber').setAttribute('title', document.getElementById('trans-validate35').textContent);
            });
            return false;
        }
        // All other CCs
    } else if (!(ccNumOnly.length === 16)) {
        post.add(function () {
            document.getElementById('CCNumber').setAttribute('title', document.getElementById('trans-validate36').textContent);
        });
        return false;
    }
    // Check mod10 for non Diners Club USA cards
    if (!/^5[45]/.test(ccNumOnly)) {
        if (!passesChecksum(ccNumOnly)) {
            post.add(function () {
                document.getElementById('CCNumber').setAttribute('title', document.getElementById('trans-validate37').textContent);
            });
            return false;
        }
    }
    return true;
}

function isValidRoutingNumber(routingNumber) {
    var numOnly = routingNumber.replace(/\D/g, '');
    return numOnly.length === 9; // && ACHChecksum(numOnly);
}

// Checks if CC number passes mod10 checksum
function passesChecksum(ccNum) {
    var mod10 = ccNum.split('').reverse()
        .map(function (x, i) { return ((i % 2 === 1) ? (x * 2) : parseInt(x)) })
        .map(function (x) { return ((x > 9) ? (x - 9) : x) })
        .reduce(function (a, c) { return a + c }) % 10;
    return (mod10 === 0);
}

function ACHChecksum(num) {
    var mod10 = num.split('')
        .map(function (x, i) {
            if (i % 3 == 0) {
                return 3 * x;
            } else if (i % 3 == 1) {
                return 7 * x;
            } else {
                return parseInt(x);
            }
        })
        .reduce(function (a, c) { return a + c }) % 10;
    return (mod10 === 0);
}

// Exp Date Validation
function isValidExpDate(expDate) {
    return ((/^(0[1-9]|1[012])\/\d{2}$/.test(expDate)) && // Date is in form mm/yy with month between 1-12
        isFutureDate(expDate)); // Date is in future
}

// Checks if mm/yy is in future
function isFutureDate(expDate) {
    var expMonth = parseInt(expDate.replace(/\D/g, '').slice(0, 2)),
        expYear = parseInt(expDate.replace(/\D/g, '').slice(2)) + 2000,
        today = new Date(),
        currentMonth = today.getMonth() + 1,
        currentYear = today.getFullYear();
    return (expYear > currentYear || (expYear === currentYear && expMonth >= currentMonth));
}

function isValidRecurringTotal(iterations, post) {
    post = post || newPostAction();
    // Check if iterations * amount < account max
    if (document.getElementById('Amount').value) {
        if (iterations > 32000) {
            post.add(function () {
                document.getElementById('Iterations').setAttribute('title', document.getElementById('trans-validate10').textContent);
            });
            return false;
        } else if (document.getElementById('GiveAmount') && document.getElementById('GiveAmount').value) {
            var merchTotal = 0;
            let giveAmount = applyFactors(parseFloat(document.getElementById('GiveAmount').value));
            let amount = parseFloat(document.getElementById('Amount').value);
            if (amount > giveAmount) {
                merchTotal = amount - giveAmount;
            }

            let recurringTotal = iterations * giveAmount;
            if (parseFloat(merchTotal) + parseFloat(recurringTotal) > getAccountMax()) {
                post.add(function () {
                    document.getElementById('Iterations').setAttribute('title', document.getElementById('trans-validate11').textContent);
                });
                return false;
            }
        } else if ((iterations * document.getElementById('Amount').value) > getAccountMax()) {
            post.add(function () {
                document.getElementById('Iterations').setAttribute('title', document.getElementById('trans-validate21').textContent);
            })
            return false;
        }
    }

    return true;
}

// Iterations Number Validation
function isValidIterations(iterations, post) {
    post = post || newPostAction();

    if (iterations === 0) {
        post.add(function () {
            document.getElementById('Iterations').setAttribute('title', document.getElementById('trans-validate18').textContent);
        });
        return false;
    }

    // Check if iterations < exp date
    if (document.getElementById('ExpDate').value) {
        var timespan,
            interval,
            ms,
            term,
            mmyy = document.getElementById('ExpDate').value,
            max = 0,
            expMonthIndex = parseInt(mmyy.replace(/\D/g, '').slice(0, 2)) - 1,
            expYear = parseInt(mmyy.replace(/\D/g, '').slice(2)) + 2000,
            expDate = new Date(expYear, expMonthIndex + 1, 0),// retreives last day of exp month 
            today = new Date();
        // Get timespan
        if (document.getElementById('btnWeekly') && document.getElementById('btnWeekly').getAttribute('disabled')) {
            term = 'weeks';
            timespan = 7;
        } else if (document.getElementById('btnMonthly') && document.getElementById('btnMonthly').getAttribute('disabled')) {
            term = 'months';
            timespan = 30;
        } else if (document.getElementById('btnQuarterly') && document.getElementById('btnQuarterly').getAttribute('disabled')) {
            term = 'quarters';
            timespan = 90;
        } else if (document.getElementById('btnAnnually') && document.getElementById('btnAnnually').getAttribute('disabled')) {
            term = 'years';
            timespan = 365;
        } else {
            timespan = 1;
        }
        interval = timespan * 24 * 60 * 60 * 1000
        ms = interval * iterations;
        max = Math.floor((expDate.getTime() - today.getTime()) / interval);
        if ((today.getTime() + ms) > expDate.getTime()) {
            post.add(function () {
                //document.getElementById('Iterations').setAttribute('title', document.getElementById('trans-validate12').textContent);
                document.getElementById('Iterations').setAttribute('title', iterations + ' ' + term + ' of recurring donations are not allowed since your credit card will expire on ' + mmyy + '. Please adjust your number of recurring payments to a maximum of ' + max);
            });
            return false;
        }
    }

    if (!isValidRecurringTotal(iterations, post)) {
        return false;
    }

    return true;
}

function runIterationsValidation() {
    if (document.getElementById('Iterations') && document.getElementById('Iterations').value) {
        validateInput(document.getElementById('Iterations'));
        updateInputValidationStyle(document.getElementById('Iterations'));
    }
    //if (document.getElementById('max-amount-merch')) {
    //    if (document.getElementById('Iterations') && document.getElementById('Iterations').getAttribute('data-validate') === 'fail') {
    //        document.getElementById('max-amount-merch').style.display = 'block';
    //    } else {
    //        document.getElementById('max-amount-merch').style.display = 'none';
    //    }
    //}
}

function updateInputValidationStyle(inputElem) {
    if (inputElem) {
        var parentElem = document.getElementById(inputElem.id).parentNode,
            errorIconElem = parentElem.querySelector('.error-icon'),
            infoIconElem = parentElem.querySelector('.more-info-btn');

        if (inputElem.getAttribute('id') === 'OtherAmount') {
            var errorTooltipElem = document.querySelector('.efund_PaymentOptionList .error');
        } else {
            var errorTooltipElem = parentElem.querySelector('.error');
        }

        if (inputElem.getAttribute('data-validate') === 'pass') {
            // Valid Input
            updateValidInputStyle(inputElem, errorIconElem, infoIconElem, errorTooltipElem);


        } else if (inputElem.getAttribute('data-validate') === 'fail') {
            // Invalid Input
            updateInvalidInputStyle(inputElem, parentElem, errorIconElem, infoIconElem, errorTooltipElem);


        } else {
            // Empty & Not Required
            updateEmptyValidInputStyle(inputElem, errorIconElem, infoIconElem, errorTooltipElem);

        }
    }
}

function updateValidInputStyle(inputElem, errorIconElem, infoIconElem, errorTooltipElem) {
    inputElem.classList.add('valid');
    inputElem.classList.remove('invalid');
    if (errorTooltipElem) {
        errorTooltipElem.remove();
    }
    if (errorIconElem) {
        errorIconElem.remove();
    }
    if (infoIconElem) {
        infoIconElem.classList.remove('red');
    }
}

function updateInvalidInputStyle(inputElem, parentElem, errorIconElem, infoIconElem, errorTooltipElem) {
    inputElem.classList.remove('valid');
    inputElem.classList.add('invalid');
    // Error tooltip
    if (errorTooltipElem) {
        errorTooltipElem.remove();
    }
    const dataAttrStr = inputElem.hasAttribute('id') ?
        'data-errorfor="' + inputElem.getAttribute('id') + '" ' :
        '';
    var errorTooltipHTML = '<div ' + dataAttrStr + 'class="efund-tooltip error"><p>'
        + inputElem.getAttribute('data-validate-message')
        + '</p></div>';

    if (inputElem.getAttribute('id') === 'OtherAmount') {
        document.querySelector('.efund_PaymentOptionList').insertAdjacentHTML("beforeend", errorTooltipHTML);
    } else {
        parentElem.insertAdjacentHTML("beforeend", errorTooltipHTML);
    }

    // Error icon
    // Handle fields where info icon is already present
    if (infoIconElem) {
        infoIconElem.classList.add('red');
    } else {
        if (!errorIconElem) {
            var errorIconHTML = '<i class="fa fa-exclamation-circle error-icon" aria-hidden="true"></i>';
            if (inputElem.id === 'OtherAmount') {
                document.getElementById('OtherAmount').parentNode.insertAdjacentHTML("beforeend", errorIconHTML);
            } else {
                parentElem.insertAdjacentHTML("beforeend", errorIconHTML);
            }

        }
    }
}

function updateEmptyValidInputStyle(inputElem, errorIconElem, infoIconElem, errorTooltipElem) {
    inputElem.classList.remove('valid');
    inputElem.classList.remove('invalid');
    if (errorTooltipElem) {
        errorTooltipElem.remove();
    }
    if (errorIconElem) {
        errorIconElem.remove();
    }
    if (infoIconElem) {
        infoIconElem.classList.remove('red');
    }
}

function hideRecaptchaError() {
    if (document.getElementById('recaptcha-error')) {
        document.getElementById('recaptcha-error').style.display = 'none';
    }
}

function viewportWidth() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window)) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return e[a + 'Width'];
}

//Do stuff on start up after everything is defined
document.addEventListener("DOMContentLoaded", function () {
    //Fill in Phone
    if (document.getElementById('Phone')) {
        let phone = document.getElementById('Phone').value;
        if (phone !== '') {
            document.getElementById('Phone').dispatchEvent(new Event('input'));
        }
    }
});

function serializeForm(formElem) {
    const formData = new FormData(formElem),
        entries = [...formData.entries()],
        serializedEntries = entries
            .map(entry => `${encodeURIComponent(entry[0])}=${encodeURIComponent(entry[1])}`)
            .join('&');

    return serializedEntries;
}

function fadeIn(el, speed) {
    if (el) {
        if (el.classList.contains('row')) {
            el.style.display = 'flex';
        } else {
            el.style.display = 'block';
        }
    }
    //if (el) {
    //    el.style.opacity = 0;
    //    el.style.display = 'block';
    //    speed = speed || '';
    //    var time;

    //    if (speed === 'fast') {
    //        time = 200;
    //    } else if (speed === 'slow') {
    //        time = 600;
    //    } else if (typeof speed === 'number') {
    //        time = speed;
    //    } else {
    //        time = 400;
    //    }

    //    var last = +new Date();
    //    var tick = function () {
    //        el.style.opacity = +el.style.opacity + (new Date() - last) / time;
    //        last = +new Date();

    //        if (+el.style.opacity < 1) {
    //            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    //        }
    //    };

    //    tick();
    //}
}

function fadeOut(el, speed) {
    if (el) {
        el.style.display = 'none';
    }
    //if (el) {
    //    el.style.opacity = 1;
    //    speed = speed || '';
    //    var time;

    //    if (speed === 'fast') {
    //        time = 200;
    //    } else if (speed === 'slow') {
    //        time = 600;
    //    } else if (typeof speed === 'number') {
    //        time = speed;
    //    } else {
    //        time = 400;
    //    }

    //    var last = +new Date();
    //    var tick = function () {
    //        el.style.opacity = +el.style.opacity - (new Date() - last) / time;
    //        last = +new Date();

    //        if (+el.style.opacity > 0) {
    //            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    //        }
    //    };

    //    tick();
    //}
}

/* Helpers */
function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

/* PayPal functions that are called whether or not PayPal is enabled */

function resetPayPalContainer() {
    if (document.getElementById('paypal-column')) {
        document.getElementById('paypal-column').style.display = 'block';
    }
    if (document.getElementById('paypal-message')) {
        document.getElementById('paypal-message').style.display = 'none';
    }
}

function updatePayPalStatus() {
    if (getPayPalActions === undefined) {
        return;
    }
    if (isFormValid(document.querySelector('.efundForm'))) {
        getPayPalActions().enable();
    } else {
        getPayPalActions().disable();
    }
};
// Style Merged Input Fields when they break across lines
window.addEventListener('load', function () {
    document.querySelectorAll('.no-gutter-row .efund-form-col').forEach((formColumnElem) => {
        checkIfEndField(formColumnElem);
    });
});
window.addEventListener('resize', function () {
    document.querySelectorAll('.no-gutter-row .efund-form-col').forEach((formColumnElem) => {
        checkIfEndField(formColumnElem);
    });
});
if (document.getElementById('btnSecond')) {
    document.getElementById('btnSecond').addEventListener('click', function () {
        window.setTimeout(function () {
            checkIfEndField(document.getElementById('NameFirstOther').closest('.efund-form-col'));
            checkIfEndField(document.getElementById('NameLastOther').closest('.efund-form-col'));
        }, 200);
    });
}
if (document.getElementById('achNavButton')) {
    document.getElementById('achNavButton').addEventListener('click', function () {
        window.setTimeout(function () {
            checkIfEndField(document.getElementById('AchRouting').closest('.efund-form-col'));
            checkIfEndField(document.getElementById('AchAccount').closest('.efund-form-col'));
        }, 200);
    });
}
//document.querySelectorAll('.form-flow-btn').forEach((cbcpNextBtnElem) => {
//    cbcpNextBtnElem.addEventListener('click', function () {
//        window.setTimeout(function () {
//            document.querySelectorAll('.no-gutter-row .efund-form-col').forEach((formColumnElem) => {
//                checkIfEndField(formColumnElem);
//            });
//        }, 200);
//    });
//});
if (document.getElementById('modal-oneclick-container')) {
    document.getElementById('modal-oneclick-container').addEventListener('show.bs.modal', function (e) {
        window.setTimeout(function () {
            document.querySelectorAll('#apple-pay-popup .no-gutter-row .efund-form-col').forEach((formColumnElem) => {
                checkIfEndField(formColumnElem);
            });
        }, 200);
    });
}


function checkIfEndField(columnElem) {
    // Calculate field distance from left and right ends of row
    var leftPos, rightPos, id;
    leftPos = columnElem.offsetLeft - 28;
    rightPos = columnElem.parentNode.offsetWidth - (columnElem.offsetLeft + columnElem.offsetWidth) + 28;
    
    // If field at start of row, add start style
    if (leftPos < 10) {
        columnElem.classList.add('row-start');
    } else {
        columnElem.classList.remove('row-start');
    }
    // If field at end of row, add end style
    if (rightPos < 35) {
        columnElem.classList.add('row-end');
    } else {
        columnElem.classList.remove('row-end');
    }

    //id = columnElem.find('.form-control').attr('id');
}

window.addEventListener('load', function () {
    // Resize checkbox disclaimer box height
    if (document.querySelector('.checkbox-disclaimer-msg')) {
        resizeHeightToEqual(document.querySelector('.checkbox-disclaimer-msg'), 90);
    }
    
    //// Resize Dashboard transactions height
    //if (document.getElementById('transactions-list').length > 0) {
    //    var transactionsElem = document.getElementById('transactions-list'),
    //        tnMinHeight = transactionsElem.children('.row').eq(0).outerHeight() + transactionsElem.children('.row').eq(1).outerHeight();
    //    resizeHeightToEqual(transactionsElem, tnMinHeight);
    //}
    

    //resizeHeightToEqual(document.getElementById('transactions-list'), document.getElementById('transactions-list').find());

    // Resize DOM object height so two columns have equal height
    function resizeHeightToEqual(resizeObjElem, minHeight) {
        if ((document.getElementById('efund-form-col-2'))     // if on two-column page
            //&& (resizeObjElem.length > 0)              // and resize object is enabled
            && viewportWidth() > 991) {             // and large screen
            var colElem1 = document.getElementById('efund-form-col-1'),
                colElem2 = document.getElementById('efund-form-col-2'),
                col1Ht = colElem1.offsetHeight,
                col2Ht = colElem2.offsetHeight,
                resizeObjHt = getComputedStyle(resizeObjElem).getPropertyValue('height');
            // Resize object height if column 1 height is greater than column 2
            if ((col2Ht - resizeObjHt) < col1Ht) {
                var newResizeObjHt = Math.max(minHeight, col1Ht - (col2Ht - resizeObjHt));
                resizeObjElem.style.maxHeight = newResizeObjHt;
            }
        }
    }
    // Get viewport width
    function viewportWidth() {
        var e = window, a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return e[a + 'Width'];
    }
});
;
document.addEventListener("DOMContentLoaded", function () {
    // =======================
    // Merchandise
    // =======================
    if (document.getElementById('MerchandiseJSON')) {
        // Execute on page load
        updateFieldsIfProductServerData();

        document.querySelectorAll('.ticket .qty-field').forEach((qtyFieldElem) => {
            checkQtyMin(qtyFieldElem);
        });

        // Clear sold out fields
        document.querySelectorAll('.sold-out .qty-field').forEach((soldOutQtyFieldElem) => {
            soldOutQtyFieldElem.value = '0';
        });

        setupGiveAmount();

        updateTickets();

        updateDisplayedTotalAmount(document.getElementById('Amount').value);

        // Prevent recurring selection until amount selection
        if (!isNaN(parseFloat(document.getElementById('GiveAmount').value))) {
            allowRecurring();
            showCancel();
        }
        else {
            preventRecurring();
        }

        // =======================
        // Event Listeners

        // Update GiveAmount hidden field on amount button click
        document.querySelectorAll('.efund_PaymentOptionItem').forEach((paymentOptionItemElem) => {
            paymentOptionItemElem.addEventListener('click', function () {
                const giveAmountElem = document.getElementById('GiveAmount');
                giveAmountElem.value = this.getAttribute('data-amount');
                giveAmountElem.dispatchEvent(new Event('change'));
                // Allow recurring selection
                allowRecurring();
                // Show cancel button
                showCancel();
            });
        });

        document.getElementById('OtherAmount').addEventListener('blur', function () {
            //Only change amount if amount is not empty or there are no selected options
            const otherAmountValue = this.value;
            if (otherAmountValue !== "" || !document.querySelectorAll('.selectedOption')[0]) {
                const giveAmountElem = document.getElementById('GiveAmount');
                giveAmountElem.value = otherAmountValue;
                giveAmountElem.dispatchEvent(new Event('change'));
            }
            if (otherAmountValue !== "") {
                // Allow recurring selection
                allowRecurring();
                // Show cancel button
                showCancel();
            } else if (document.querySelectorAll('.efund_PaymentOptionItem.selectedOption').length === 0) {
                cancelContribution();
            }
        });

        document.getElementById('cancel-contribution-btn').addEventListener('click', function () {
            cancelContribution();
        });

        // Increment / decrement ticket quantity
        document.querySelectorAll('.qty-btn').forEach((qtyBtnElem) => {
            qtyBtnElem.addEventListener('click', function () {
                changeTicketQty(this, this.parentNode.querySelector('.qty-field'));
            });
        });

        // Update additional amount hidden ticket
        document.getElementById('GiveAmount').addEventListener('change', function () {
            updateTickets();
            runIterationsValidation();
                
            //addOtherAmountToTickets();
        });

        // Quantity Fields
        document.querySelectorAll('.ticket .qty-field').forEach((qtyFieldElem) => {
            qtyFieldElem.addEventListener('change', function () {
                updateTickets();

                // Check quantity against max and min
                checkQtyMin(this);
                checkQtyMax(this);

                runIterationsValidation();

                const productElem = qtyFieldElem.closest('.merchandise-item');
                updateProductVariantRequire(productElem);
            });
        });

        document.querySelectorAll('.ticket .product-variant-field').forEach((variantFieldElem) => {
            variantFieldElem.addEventListener('change', function () {
                updateTickets();
            });
        });

        document.getElementById('Amount').addEventListener('change', function () {
            handleAmountChangeWithMerch();
        });

        if (document.getElementById('Iterations')) {
            document.getElementById('Iterations').addEventListener('change', function () {
                handleAmountChangeWithMerch();
            });
        }
    }
    
});

// =======================
// Functions

function handleAmountChangeWithMerch() {
    //Update total amount display
    updateDisplayedTotalAmount(document.getElementById('Amount').value);

    // Check if quantity fields will exceed amount max
    document.querySelectorAll('.qty-field').forEach((qtyFieldElem) => {
        checkQtyMax(qtyFieldElem);
    });
    if (doesExceedMax()) {
        document.getElementById('total-amount-max-error').style.display = 'block';
        if (document.getElementById('total-amount-max-error-hero-1') && isHeroShotMultiPanel()) {
            document.getElementById('total-amount-max-error-hero-1').style.display = 'block';
        }
    } else {
        document.getElementById('total-amount-max-error').style.display = 'none';
        if (document.getElementById('total-amount-max-error-hero-1') && isHeroShotMultiPanel()) {
            document.getElementById('total-amount-max-error-hero-1').style.display = 'none';
        }
    }
    if (doesFailMin()) {
        document.getElementById('total-amount-min-error').style.display = 'block';
    } else {
        document.getElementById('total-amount-min-error').style.display = 'none';
    }

    // Hide missing amount error message
    if (parseFloat(document.getElementById('Amount').value)) {
        document.getElementById('missing-amount').style.display = 'none';
    }

    updateRequireAmount();
    if (document.getElementById('btnPayPal')) {
        updatePayPalStatus();
        if (document.getElementById('btnPayPal')) {
            resetPayPalContainer();
        }
    }
    updateFieldErrors();
}

function updateFieldsIfProductServerData() {
    const productsJSON = document.getElementById('MerchandiseJSON').value;

    if (productsJSON) {
        const products = JSON.parse(productsJSON);
        updateFieldsFromProductServerData(products);
    }
}

function updateFieldsFromProductServerData(products) {
    updateProductsFromServerData(products);
    updateGiveAmountFromProductServerData(products);
    
}

function updateProductsFromServerData(products) {
    if (haveNonzeroProductQuantities(products)) {
        updateProductQuantityFields(products);
    }
    updateProductVariants(products);
}

function updateGiveAmountFromProductServerData(products) {
    if (haveNonzeroProductAmounts(products)) {
        const giveAmount = calculateGiveAmountFromProductsAmount(products);

        if (giveAmount > 0) {
            document.getElementById('GiveAmount').value = giveAmount;
            setupSelectedPaymentOption(document.getElementById('GiveAmount'));
            setupSelectedOtherAmount(document.getElementById('GiveAmount'));
        }
    }
}

function haveNonzeroProductQuantities(products) {
    const totalProductsQuantity = sumProductQuantities(products);
    return totalProductsQuantity > 0;
}

function sumProductQuantities(products) {
    var productQuantities = extractproductQuantities(products);
    return sumElements(productQuantities);
}

function extractproductQuantities(products) {
    return products.map(product => parseInt(product.Count, 10));
}

function sumElements(elements) {
    return elements.reduce((total, value) => total + value);
}

function updateProductQuantityFields(products) {
    products.forEach(function (product, i) {
        updateProductQuantityField(product, i);
    });
}

function updateProductQuantityField(product, i) {
    const count = product.Count,
          quantityField = document.querySelectorAll('.qty-field')[i];
    quantityField.value = count;
}

function haveNonzeroProductAmounts(products) {
    const totalProductsAmount = sumProductAmounts(products);
    return totalProductsAmount > 0;
}

function sumProductAmounts(products) {
    return products.reduce((total, product) => total + (product.Count * product.Amount));
}

function calculateGiveAmountFromProductsAmount(products) {
    const totalProductsAmount = sumProductAmounts(products),
          totalAmount = parseFloat(document.getElementById('Amount').value);

    return totalAmount - totalProductsAmount;
}

function getProductsWithVariantsSelected(products) {
    return products.filter(hasVariantSelected);
}

function hasVariantSelected(product) {
    return product.SizeOption && (product.SizeOption.length > 0);
}

function updateProductVariants(products) {

    const variantProducts = getProductsWithVariantsSelected(products);

    variantProducts.forEach((product, i) => {
        updateProductVariant(product, i);
    });
}

function updateProductVariant(product, i) {

    const variant = product.SizeOption,
        variantField = document.querySelectorAll('.product-variant-field')[i];
    variantField.value = variant;
    
}

function updateProductVariantRequire(productElem) {
    const qtyFieldElem = productElem.querySelector('.qty-field'),
        qty = parseInt(qtyFieldElem.value),
        variantFieldElem = productElem.querySelector('.product-variant-field');

    if (variantFieldElem) {
        if (qty > 0) {
            variantFieldElem.required = true;
        } else {
            variantFieldElem.required = false;
            variantFieldElem.dispatchEvent(new Event('change'));
        }
    }
}


// =========================================================================================
// refactored functions up to this point -Alex 2/13/22

function updateDisplayedTotalAmount(amount) {
    const formattedTotalAmount = formatTotalAmount(amount)
    document.getElementById('totalAmount').textContent = formattedTotalAmount;
}

function formatTotalAmount(amount) {
    return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function getDonationAmount() {
    //Check if an amount is selected
    if (document.querySelector("li[class='efund_PaymentOptionItem selectedOption']")) {
        return document.querySelector("li[class='efund_PaymentOptionItem selectedOption']").getAttribute('data-amount');
    }
    else {
        //Get the other amount
        return document.getElementById('OtherAmount').value;
    }
}

function setupGiveAmount() {
    var donationAmount = getDonationAmount();
    if (donationAmount !== '' || donationAmount !== undefined) {
        document.getElementById('GiveAmount').value = donationAmount;
    }
}

function changeTicketQty(qtyBtnElem, qtyFieldElem) {
    var qty = parseInt(qtyFieldElem.value, 10),
        newQty;
    if (!qty) {
        newQty = 1;
    } else if (qtyBtnElem.value === 'plus') {
        newQty = qty + 1;
    } else {
        newQty = qty - 1;
    }
    qtyFieldElem.value = newQty.toString();
    qtyFieldElem.dispatchEvent(new Event('change'));
}

function createTicketArr(ticketElems) {
    var ticketArr = [...ticketElems].map((ticketElem) => {
        return saveProductOptions(ticketElem);
    });
    return ticketArr;
}

function saveProductOptions(productElem) {
    const name = productElem.getAttribute('data-name'),
        amount = productElem.getAttribute('data-amount'),
        qtyfieldElem = productElem.querySelector('.qty-field'),
        quantity = parseInt(qtyfieldElem.value, 10) ? qtyfieldElem.value : '0',
        variantFieldElem = productElem.querySelector('.product-variant-field'),
        updatedProduct = variantFieldElem ?
            {
                'Name': name,
                'Amount': amount,
                'Count': quantity,
                'SizeOption': variantFieldElem.value
            } :
            {
                'Name': name,
                'Amount': amount,
                'Count': quantity
            };

    return updatedProduct;
}

function sumItems(itemArr) {
    return itemArr.reduce(itemReducer, 0);
}

function itemReducer(sum, item) {
    return sum + (item.Amount * item.Count);
}

// Hide minus button if quantity is zero
function checkQtyMin(qtyFieldElem) {
    var qtyControlsElem = qtyFieldElem.parentNode,
        minusBtnElem = qtyControlsElem.querySelector('.qty-minus');
    if (!parseInt(qtyFieldElem.value, 10)) {
        minusBtnElem.setAttribute('disabled', '');
    } else {
        minusBtnElem.removeAttribute('disabled');
    }
}

// Hide plus button if value would exceed PersonLimit
function checkQtyMax(qtyFieldElem) {
    var qtyControlsElem = qtyFieldElem.parentNode,
        plusBtnElem = qtyControlsElem.querySelector('.qty-plus'),
        ticketElem = qtyControlsElem.closest('.ticket'),
        incAmount = parseFloat(ticketElem.getAttribute('data-amount')),
        qty = parseInt(qtyFieldElem.value, 10),
        maxQty = parseInt(qtyFieldElem.getAttribute('data-max'), 10),
        errorMsgElem = ticketElem.querySelector('.ticket-error');
    if (willExceedMax(incAmount)) {
        plusBtnElem.setAttribute('disabled', '');
    } else if (maxQty && (qty >= maxQty)) {
        plusBtnElem.setAttribute('disabled', '');
    } else {
        plusBtnElem.removeAttribute('disabled');
    }

    // Error message
    if (maxQty && (qty > maxQty)) {
        errorMsgElem.style.display = 'block';
;
    } else {
        errorMsgElem.style.display = 'none';
;
    }
}

function willExceedMax(incAmount) {
    const max = getAccountMax(),
        baseAmount = parseFloat(document.getElementById('BaseAmount').value),
        value = applyFactors(baseAmount + incAmount);
    return value > max;
}

function doesExceedMax() {
    const total = parseFloat(document.getElementById('Amount').value),
        max = getAccountMax();
    return total > max;
}

function doesFailMin() {
    var totalAmountElem = document.getElementById('totalAmount'),
        total = parseFloat(totalAmountElem.value),
        min = parseFloat(totalAmountElem.getAttribute('data-min'));
    // Return true if total is non-zero, and less than min
    return (total && (total < min));
}

function resetTotalAmount() {
    updateTotalAmount('0');
    updateSubmitButtonTextWithAmount('0');
}

function calcAdditionalMin(total, accountMin) {
    return Math.max((accountMin - total), 0);
}

function calcTotalProductsAmount() {
    const ticketElems = document.querySelectorAll('.ticket'),
          ticketArr = createTicketArr(ticketElems),
          totalProductsAmount = parseFloat(sumItems(ticketArr).toFixed(2).toString());

    return totalProductsAmount;
}

function updateTickets() {
    // Create array of ticket data
    var ticketElems = document.querySelectorAll('.ticket'),
        ticketArr = createTicketArr(ticketElems);

    // Store ticket data in JSON
    var ticketJSON = JSON.stringify(ticketArr);
    document.getElementById('MerchandiseJSON').value = ticketJSON;

    // Update amount total
    var totalProductsAmount = calcTotalProductsAmount();
    if (isNaN(totalProductsAmount)) {
        totalProductsAmount = 0;
    }
    var giveAmountElem = document.getElementById('GiveAmount'),
        donationAmount = parseFloat(giveAmountElem.value);
    if (isNaN(donationAmount)) {
        donationAmount = 0;
    }

    updateTotalAmount(totalProductsAmount + donationAmount);

    // Update count total
    var totalProductsQuantity = sumProductQuantities(ticketArr);
    updateTotalProductsQuantity(totalProductsQuantity);
}

function updateTotalProductsQuantity(totalProductsQuantity) {
    const totalProductsQuantityElem = document.getElementById('TotalCount');
    if (totalProductsQuantityElem) {
        totalProductsQuantityElem.value = totalProductsQuantity;
        totalProductsQuantityElem.dispatchEvent(new Event('change'));
    }
}

function preventRecurring() {
    document.getElementById('efund-recurring-btns').classList.add('prevent-recurring');
    const recurringBtnElems = document.querySelectorAll('#efund-recurring-btns .btn');
    recurringBtnElems.forEach((btn) => {
        btn.disabled = true;
    });
    // Handle force recurring case
    const iterationsElem = document.getElementById('Iterations');
    if (iterationsElem.getAttribute('data-required') === 'true') {
        iterationsElem.required = false;
        iterationsElem.disabled = true;
    } else {
        iterationsElem.parentNode.parentNode.parentNode.style.display = 'none';
    }
}

function allowRecurring() {
    if (document.querySelectorAll('#efund-recurring-btns.prevent-recurring').length !== 0) {
        document.getElementById('efund-recurring-btns').classList.remove('prevent-recurring');
        document.querySelectorAll('#efund-recurring-btns .btn').forEach((btn) => {
            btn.disabled = false
        });
        document.querySelectorAll('#efund-recurring-btns .btn-wrapper:first-child .btn').forEach((btn) => {
            btn.disabled = true
        });
    }
    // Handle force recurring case
    const iterationsElem = document.getElementById('Iterations');
    if (iterationsElem.getAttribute('data-required') === 'true') {
        iterationsElem.required = true;
        iterationsElem.disabled = false;
    }
}
function showCancel() {
    document.getElementById('cancel-contribution-row').classList.remove('d-none');
}
function cancelContribution() {
    if (document.querySelector('.efund_PaymentOptionItem.selectedOption')) {
        document.querySelector('.efund_PaymentOptionItem.selectedOption').classList.remove('selectedOption');
    }

    const otherAmountElem = document.getElementById('OtherAmount');
    otherAmountElem.value = '';
    otherAmountElem.dispatchEvent(new Event('change'));

    const giveAmountElem = document.getElementById('GiveAmount');
    giveAmountElem.value = '';
    giveAmountElem.dispatchEvent(new Event('change'));

    document.getElementById('Iterations').value = '1';
    HideRecurringMessages();
    preventRecurring();
    document.getElementById('cancel-contribution-row').classList.add('d-none');
    enablePayPal();
};
/*!
 * cleave.js - 1.4.7
 * https://github.com/nosir/cleave.js
 * Apache License Version 2.0
 *
 * Copyright (C) 2012-2018 Max Huang https://github.com/nosir/
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Cleave=t():e.Cleave=t()}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var n=r[i]={exports:{},id:i,loaded:!1};return e[i].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){(function(t){"use strict";var i=function(e,t){var r=this;if("string"==typeof e?r.element=document.querySelector(e):r.element="undefined"!=typeof e.length&&e.length>0?e[0]:e,!r.element)throw new Error("[cleave.js] Please check the element");t.initValue=r.element.value,r.properties=i.DefaultProperties.assign({},t),r.init()};i.prototype={init:function(){var e=this,t=e.properties;return t.numeral||t.phone||t.creditCard||t.time||t.date||0!==t.blocksLength||t.prefix?(t.maxLength=i.Util.getMaxLength(t.blocks),e.isAndroid=i.Util.isAndroid(),e.lastInputValue="",e.onChangeListener=e.onChange.bind(e),e.onKeyDownListener=e.onKeyDown.bind(e),e.onFocusListener=e.onFocus.bind(e),e.onCutListener=e.onCut.bind(e),e.onCopyListener=e.onCopy.bind(e),e.element.addEventListener("input",e.onChangeListener),e.element.addEventListener("keydown",e.onKeyDownListener),e.element.addEventListener("focus",e.onFocusListener),e.element.addEventListener("cut",e.onCutListener),e.element.addEventListener("copy",e.onCopyListener),e.initPhoneFormatter(),e.initDateFormatter(),e.initTimeFormatter(),e.initNumeralFormatter(),void((t.initValue||t.prefix&&!t.noImmediatePrefix)&&e.onInput(t.initValue))):void e.onInput(t.initValue)},initNumeralFormatter:function(){var e=this,t=e.properties;t.numeral&&(t.numeralFormatter=new i.NumeralFormatter(t.numeralDecimalMark,t.numeralIntegerScale,t.numeralDecimalScale,t.numeralThousandsGroupStyle,t.numeralPositiveOnly,t.stripLeadingZeroes,t.delimiter))},initTimeFormatter:function(){var e=this,t=e.properties;t.time&&(t.timeFormatter=new i.TimeFormatter(t.timePattern,t.timeFormat),t.blocks=t.timeFormatter.getBlocks(),t.blocksLength=t.blocks.length,t.maxLength=i.Util.getMaxLength(t.blocks))},initDateFormatter:function(){var e=this,t=e.properties;t.date&&(t.dateFormatter=new i.DateFormatter(t.datePattern),t.blocks=t.dateFormatter.getBlocks(),t.blocksLength=t.blocks.length,t.maxLength=i.Util.getMaxLength(t.blocks))},initPhoneFormatter:function(){var e=this,t=e.properties;if(t.phone)try{t.phoneFormatter=new i.PhoneFormatter(new t.root.Cleave.AsYouTypeFormatter(t.phoneRegionCode),t.delimiter)}catch(r){throw new Error("[cleave.js] Please include phone-type-formatter.{country}.js lib")}},onKeyDown:function(e){var t=this,r=t.properties,n=e.which||e.keyCode,a=i.Util,o=t.element.value;t.hasBackspaceSupport=t.hasBackspaceSupport||8===n,!t.hasBackspaceSupport&&a.isAndroidBackspaceKeydown(t.lastInputValue,o)&&(n=8),t.lastInputValue=o;var l=a.getPostDelimiter(o,r.delimiter,r.delimiters);8===n&&l?r.postDelimiterBackspace=l:r.postDelimiterBackspace=!1},onChange:function(){this.onInput(this.element.value)},onFocus:function(){var e=this,t=e.properties;i.Util.fixPrefixCursor(e.element,t.prefix,t.delimiter,t.delimiters)},onCut:function(e){this.copyClipboardData(e),this.onInput("")},onCopy:function(e){this.copyClipboardData(e)},copyClipboardData:function(e){var t=this,r=t.properties,n=i.Util,a=t.element.value,o="";o=r.copyDelimiter?a:n.stripDelimiters(a,r.delimiter,r.delimiters);try{e.clipboardData?e.clipboardData.setData("Text",o):window.clipboardData.setData("Text",o),e.preventDefault()}catch(l){}},onInput:function(e){var t=this,r=t.properties,n=i.Util,a=n.getPostDelimiter(e,r.delimiter,r.delimiters);return r.numeral||!r.postDelimiterBackspace||a||(e=n.headStr(e,e.length-r.postDelimiterBackspace.length)),r.phone?(!r.prefix||r.noImmediatePrefix&&!e.length?r.result=r.phoneFormatter.format(e):r.result=r.prefix+r.phoneFormatter.format(e).slice(r.prefix.length),void t.updateValueState()):r.numeral?(!r.prefix||r.noImmediatePrefix&&!e.length?r.result=r.numeralFormatter.format(e):r.result=r.prefix+r.numeralFormatter.format(e),void t.updateValueState()):(r.date&&(e=r.dateFormatter.getValidatedDate(e)),r.time&&(e=r.timeFormatter.getValidatedTime(e)),e=n.stripDelimiters(e,r.delimiter,r.delimiters),e=n.getPrefixStrippedValue(e,r.prefix,r.prefixLength,r.result),e=r.numericOnly?n.strip(e,/[^\d]/g):e,e=r.uppercase?e.toUpperCase():e,e=r.lowercase?e.toLowerCase():e,!r.prefix||r.noImmediatePrefix&&!e.length||(e=r.prefix+e,0!==r.blocksLength)?(r.creditCard&&t.updateCreditCardPropsByValue(e),e=n.headStr(e,r.maxLength),r.result=n.getFormattedValue(e,r.blocks,r.blocksLength,r.delimiter,r.delimiters,r.delimiterLazyShow),void t.updateValueState()):(r.result=e,void t.updateValueState()))},updateCreditCardPropsByValue:function(e){var t,r=this,n=r.properties,a=i.Util;a.headStr(n.result,4)!==a.headStr(e,4)&&(t=i.CreditCardDetector.getInfo(e,n.creditCardStrictMode),n.blocks=t.blocks,n.blocksLength=n.blocks.length,n.maxLength=a.getMaxLength(n.blocks),n.creditCardType!==t.type&&(n.creditCardType=t.type,n.onCreditCardTypeChanged.call(r,n.creditCardType)))},updateValueState:function(){var e=this,t=i.Util,r=e.properties;if(e.element){var n=e.element.selectionEnd,a=e.element.value,o=r.result;if(n=t.getNextCursorPosition(n,a,o,r.delimiter,r.delimiters),e.isAndroid)return void window.setTimeout(function(){e.element.value=o,t.setSelection(e.element,n,r.document,!1),e.callOnValueChanged()},1);e.element.value=o,t.setSelection(e.element,n,r.document,!1),e.callOnValueChanged()}},callOnValueChanged:function(){var e=this,t=e.properties;t.onValueChanged.call(e,{target:{value:t.result,rawValue:e.getRawValue()}})},setPhoneRegionCode:function(e){var t=this,r=t.properties;r.phoneRegionCode=e,t.initPhoneFormatter(),t.onChange()},setRawValue:function(e){var t=this,r=t.properties;e=void 0!==e&&null!==e?e.toString():"",r.numeral&&(e=e.replace(".",r.numeralDecimalMark)),r.postDelimiterBackspace=!1,t.element.value=e,t.onInput(e)},getRawValue:function(){var e=this,t=e.properties,r=i.Util,n=e.element.value;return t.rawValueTrimPrefix&&(n=r.getPrefixStrippedValue(n,t.prefix,t.prefixLength,t.result)),n=t.numeral?t.numeralFormatter.getRawValue(n):r.stripDelimiters(n,t.delimiter,t.delimiters)},getISOFormatDate:function(){var e=this,t=e.properties;return t.date?t.dateFormatter.getISOFormatDate():""},getISOFormatTime:function(){var e=this,t=e.properties;return t.time?t.timeFormatter.getISOFormatTime():""},getFormattedValue:function(){return this.element.value},destroy:function(){var e=this;e.element.removeEventListener("input",e.onChangeListener),e.element.removeEventListener("keydown",e.onKeyDownListener),e.element.removeEventListener("focus",e.onFocusListener),e.element.removeEventListener("cut",e.onCutListener),e.element.removeEventListener("copy",e.onCopyListener)},toString:function(){return"[Cleave Object]"}},i.NumeralFormatter=r(1),i.DateFormatter=r(2),i.TimeFormatter=r(3),i.PhoneFormatter=r(4),i.CreditCardDetector=r(5),i.Util=r(6),i.DefaultProperties=r(7),("object"==typeof t&&t?t:window).Cleave=i,e.exports=i}).call(t,function(){return this}())},function(e,t){"use strict";var r=function(e,t,i,n,a,o,l){var s=this;s.numeralDecimalMark=e||".",s.numeralIntegerScale=t>0?t:0,s.numeralDecimalScale=i>=0?i:2,s.numeralThousandsGroupStyle=n||r.groupStyle.thousand,s.numeralPositiveOnly=!!a,s.stripLeadingZeroes=o!==!1,s.delimiter=l||""===l?l:",",s.delimiterRE=l?new RegExp("\\"+l,"g"):""};r.groupStyle={thousand:"thousand",lakh:"lakh",wan:"wan",none:"none"},r.prototype={getRawValue:function(e){return e.replace(this.delimiterRE,"").replace(this.numeralDecimalMark,".")},format:function(e){var t,i,n=this,a="";switch(e=e.replace(/[A-Za-z]/g,"").replace(n.numeralDecimalMark,"M").replace(/[^\dM-]/g,"").replace(/^\-/,"N").replace(/\-/g,"").replace("N",n.numeralPositiveOnly?"":"-").replace("M",n.numeralDecimalMark),n.stripLeadingZeroes&&(e=e.replace(/^(-)?0+(?=\d)/,"$1")),i=e,e.indexOf(n.numeralDecimalMark)>=0&&(t=e.split(n.numeralDecimalMark),i=t[0],a=n.numeralDecimalMark+t[1].slice(0,n.numeralDecimalScale)),n.numeralIntegerScale>0&&(i=i.slice(0,n.numeralIntegerScale+("-"===e.slice(0,1)?1:0))),n.numeralThousandsGroupStyle){case r.groupStyle.lakh:i=i.replace(/(\d)(?=(\d\d)+\d$)/g,"$1"+n.delimiter);break;case r.groupStyle.wan:i=i.replace(/(\d)(?=(\d{4})+$)/g,"$1"+n.delimiter);break;case r.groupStyle.thousand:i=i.replace(/(\d)(?=(\d{3})+$)/g,"$1"+n.delimiter)}return i.toString()+(n.numeralDecimalScale>0?a.toString():"")}},e.exports=r},function(e,t){"use strict";var r=function(e){var t=this;t.date=[],t.blocks=[],t.datePattern=e,t.initBlocks()};r.prototype={initBlocks:function(){var e=this;e.datePattern.forEach(function(t){"Y"===t?e.blocks.push(4):e.blocks.push(2)})},getISOFormatDate:function(){var e=this,t=e.date;return t[2]?t[2]+"-"+e.addLeadingZero(t[1])+"-"+e.addLeadingZero(t[0]):""},getBlocks:function(){return this.blocks},getValidatedDate:function(e){var t=this,r="";return e=e.replace(/[^\d]/g,""),t.blocks.forEach(function(i,n){if(e.length>0){var a=e.slice(0,i),o=a.slice(0,1),l=e.slice(i);switch(t.datePattern[n]){case"d":"00"===a?a="01":parseInt(o,10)>3?a="0"+o:parseInt(a,10)>31&&(a="31");break;case"m":"00"===a?a="01":parseInt(o,10)>1?a="0"+o:parseInt(a,10)>12&&(a="12")}r+=a,e=l}}),this.getFixedDateString(r)},getFixedDateString:function(e){var t,r,i,n=this,a=n.datePattern,o=[],l=0,s=0,c=0,u=0,d=0,m=0,p=!1;return 4===e.length&&"y"!==a[0].toLowerCase()&&"y"!==a[1].toLowerCase()&&(u="d"===a[0]?0:2,d=2-u,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),o=this.getFixedDate(t,r,0)),8===e.length&&(a.forEach(function(e,t){switch(e){case"d":l=t;break;case"m":s=t;break;default:c=t}}),m=2*c,u=l<=c?2*l:2*l+2,d=s<=c?2*s:2*s+2,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+4),10),p=4===e.slice(m,m+4).length,o=this.getFixedDate(t,r,i)),n.date=o,0===o.length?e:a.reduce(function(e,t){switch(t){case"d":return e+n.addLeadingZero(o[0]);case"m":return e+n.addLeadingZero(o[1]);default:return e+(p?n.addLeadingZeroForYear(o[2]):"")}},"")},getFixedDate:function(e,t,r){return e=Math.min(e,31),t=Math.min(t,12),r=parseInt(r||0,10),(t<7&&t%2===0||t>8&&t%2===1)&&(e=Math.min(e,2===t?this.isLeapYear(r)?29:28:30)),[e,t,r]},isLeapYear:function(e){return e%4===0&&e%100!==0||e%400===0},addLeadingZero:function(e){return(e<10?"0":"")+e},addLeadingZeroForYear:function(e){return(e<10?"000":e<100?"00":e<1e3?"0":"")+e}},e.exports=r},function(e,t){"use strict";var r=function(e,t){var r=this;r.time=[],r.blocks=[],r.timePattern=e,r.timeFormat=t,r.initBlocks()};r.prototype={initBlocks:function(){var e=this;e.timePattern.forEach(function(){e.blocks.push(2)})},getISOFormatTime:function(){var e=this,t=e.time;return t[2]?e.addLeadingZero(t[0])+":"+e.addLeadingZero(t[1])+":"+e.addLeadingZero(t[2]):""},getBlocks:function(){return this.blocks},getTimeFormatOptions:function(){var e=this;return"12"===String(e.timeFormat)?{maxHourFirstDigit:1,maxHours:12,maxMinutesFirstDigit:5,maxMinutes:60}:{maxHourFirstDigit:2,maxHours:23,maxMinutesFirstDigit:5,maxMinutes:60}},getValidatedTime:function(e){var t=this,r="";e=e.replace(/[^\d]/g,"");var i=t.getTimeFormatOptions();return t.blocks.forEach(function(n,a){if(e.length>0){var o=e.slice(0,n),l=o.slice(0,1),s=e.slice(n);switch(t.timePattern[a]){case"h":parseInt(l,10)>i.maxHourFirstDigit?o="0"+l:parseInt(o,10)>i.maxHours&&(o=i.maxHours+"");break;case"m":case"s":parseInt(l,10)>i.maxMinutesFirstDigit?o="0"+l:parseInt(o,10)>i.maxMinutes&&(o=i.maxMinutes+"")}r+=o,e=s}}),this.getFixedTimeString(r)},getFixedTimeString:function(e){var t,r,i,n=this,a=n.timePattern,o=[],l=0,s=0,c=0,u=0,d=0,m=0;return 6===e.length&&(a.forEach(function(e,t){switch(e){case"s":l=2*t;break;case"m":s=2*t;break;case"h":c=2*t}}),m=c,d=s,u=l,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+2),10),o=this.getFixedTime(i,r,t)),4===e.length&&n.timePattern.indexOf("s")<0&&(a.forEach(function(e,t){switch(e){case"m":s=2*t;break;case"h":c=2*t}}),m=c,d=s,t=0,r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+2),10),o=this.getFixedTime(i,r,t)),n.time=o,0===o.length?e:a.reduce(function(e,t){switch(t){case"s":return e+n.addLeadingZero(o[2]);case"m":return e+n.addLeadingZero(o[1]);case"h":return e+n.addLeadingZero(o[0])}},"")},getFixedTime:function(e,t,r){return r=Math.min(parseInt(r||0,10),60),t=Math.min(t,60),e=Math.min(e,60),[e,t,r]},addLeadingZero:function(e){return(e<10?"0":"")+e}},e.exports=r},function(e,t){"use strict";var r=function(e,t){var r=this;r.delimiter=t||""===t?t:" ",r.delimiterRE=t?new RegExp("\\"+t,"g"):"",r.formatter=e};r.prototype={setFormatter:function(e){this.formatter=e},format:function(e){var t=this;t.formatter.clear(),e=e.replace(/[^\d+]/g,""),e=e.replace(/^\+/,"B").replace(/\+/g,"").replace("B","+"),e=e.replace(t.delimiterRE,"");for(var r,i="",n=!1,a=0,o=e.length;a<o;a++)r=t.formatter.inputDigit(e.charAt(a)),/[\s()-]/g.test(r)?(i=r,n=!0):n||(i=r);return i=i.replace(/[()]/g,""),i=i.replace(/[\s-]/g,t.delimiter)}},e.exports=r},function(e,t){"use strict";var r={blocks:{uatp:[4,5,6],amex:[4,6,5],diners:[4,6,4],discover:[4,4,4,4],mastercard:[4,4,4,4],dankort:[4,4,4,4],instapayment:[4,4,4,4],jcb15:[4,6,5],jcb:[4,4,4,4],maestro:[4,4,4,4],visa:[4,4,4,4],mir:[4,4,4,4],unionPay:[4,4,4,4],general:[4,4,4,4],generalStrict:[4,4,4,7]},re:{uatp:/^(?!1800)1\d{0,14}/,amex:/^3[47]\d{0,13}/,discover:/^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,diners:/^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,mastercard:/^(5[1-5]\d{0,2}|22[2-9]\d{0,1}|2[3-7]\d{0,2})\d{0,12}/,dankort:/^(5019|4175|4571)\d{0,12}/,instapayment:/^63[7-9]\d{0,13}/,jcb15:/^(?:2131|1800)\d{0,11}/,jcb:/^(?:35\d{0,2})\d{0,12}/,maestro:/^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,mir:/^220[0-4]\d{0,12}/,visa:/^4\d{0,15}/,unionPay:/^62\d{0,14}/},getInfo:function(e,t){var i=r.blocks,n=r.re;t=!!t;for(var a in n)if(n[a].test(e)){var o;return o=t?i.generalStrict:i[a],{type:a,blocks:o}}return{type:"unknown",blocks:t?i.generalStrict:i.general}}};e.exports=r},function(e,t){"use strict";var r={noop:function(){},strip:function(e,t){return e.replace(t,"")},getPostDelimiter:function(e,t,r){if(0===r.length)return e.slice(-t.length)===t?t:"";var i="";return r.forEach(function(t){e.slice(-t.length)===t&&(i=t)}),i},getDelimiterREByDelimiter:function(e){return new RegExp(e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"),"g")},getNextCursorPosition:function(e,t,r,i,n){return t.length===e?r.length:e+this.getPositionOffset(e,t,r,i,n)},getPositionOffset:function(e,t,r,i,n){var a,o,l;return a=this.stripDelimiters(t.slice(0,e),i,n),o=this.stripDelimiters(r.slice(0,e),i,n),l=a.length-o.length,0!==l?l/Math.abs(l):0},stripDelimiters:function(e,t,r){var i=this;if(0===r.length){var n=t?i.getDelimiterREByDelimiter(t):"";return e.replace(n,"")}return r.forEach(function(t){t.split("").forEach(function(t){e=e.replace(i.getDelimiterREByDelimiter(t),"")})}),e},headStr:function(e,t){return e.slice(0,t)},getMaxLength:function(e){return e.reduce(function(e,t){return e+t},0)},getPrefixStrippedValue:function(e,t,r,i){if(e.slice(0,r)!==t)if(e.length<i.length)e=e.length>r?i:t;else{var n=this.getFirstDiffIndex(t,e.slice(0,r));e=t+e.slice(n,n+1)+e.slice(r+1)}return e.slice(r)},getFirstDiffIndex:function(e,t){for(var r=0;e.charAt(r)===t.charAt(r);)if(""===e.charAt(r++))return-1;return r},getFormattedValue:function(e,t,r,i,n,a){var o,l="",s=n.length>0;return 0===r?e:(t.forEach(function(t,c){if(e.length>0){var u=e.slice(0,t),d=e.slice(t);o=s?n[a?c-1:c]||o:i,a?(c>0&&(l+=o),l+=u):(l+=u,u.length===t&&c<r-1&&(l+=o)),e=d}}),l)},fixPrefixCursor:function(e,t,r,i){if(e){var n=e.value,a=r||i[0]||" ";if(e.setSelectionRange&&t&&!(t.length+a.length<n.length)){var o=2*n.length;setTimeout(function(){e.setSelectionRange(o,o)},1)}}},setSelection:function(e,t,r){if(e===this.getActiveElement(r)&&!(e&&e.value.length<=t))if(e.createTextRange){var i=e.createTextRange();i.move("character",t),i.select()}else try{e.setSelectionRange(t,t)}catch(n){console.warn("The input element type does not support selection")}},getActiveElement:function(e){var t=e.activeElement;return t&&t.shadowRoot?this.getActiveElement(t.shadowRoot):t},isAndroid:function(){return navigator&&/android/i.test(navigator.userAgent)},isAndroidBackspaceKeydown:function(e,t){return!!(this.isAndroid()&&e&&t)&&t===e.slice(0,-1)}};e.exports=r},function(e,t){(function(t){"use strict";var r={assign:function(e,r){return e=e||{},r=r||{},e.creditCard=!!r.creditCard,e.creditCardStrictMode=!!r.creditCardStrictMode,e.creditCardType="",e.onCreditCardTypeChanged=r.onCreditCardTypeChanged||function(){},e.phone=!!r.phone,e.phoneRegionCode=r.phoneRegionCode||"AU",e.phoneFormatter={},e.time=!!r.time,e.timePattern=r.timePattern||["h","m","s"],e.timeFormat=r.timeFormat||"24",e.timeFormatter={},e.date=!!r.date,e.datePattern=r.datePattern||["d","m","Y"],e.dateFormatter={},e.numeral=!!r.numeral,e.numeralIntegerScale=r.numeralIntegerScale>0?r.numeralIntegerScale:0,e.numeralDecimalScale=r.numeralDecimalScale>=0?r.numeralDecimalScale:2,e.numeralDecimalMark=r.numeralDecimalMark||".",e.numeralThousandsGroupStyle=r.numeralThousandsGroupStyle||"thousand",e.numeralPositiveOnly=!!r.numeralPositiveOnly,e.stripLeadingZeroes=r.stripLeadingZeroes!==!1,e.numericOnly=e.creditCard||e.date||!!r.numericOnly,e.uppercase=!!r.uppercase,e.lowercase=!!r.lowercase,e.prefix=e.creditCard||e.date?"":r.prefix||"",e.noImmediatePrefix=!!r.noImmediatePrefix,e.prefixLength=e.prefix.length,e.rawValueTrimPrefix=!!r.rawValueTrimPrefix,e.copyDelimiter=!!r.copyDelimiter,e.initValue=void 0!==r.initValue&&null!==r.initValue?r.initValue.toString():"",e.delimiter=r.delimiter||""===r.delimiter?r.delimiter:r.date?"/":r.time?":":r.numeral?",":(r.phone," "),e.delimiterLength=e.delimiter.length,e.delimiterLazyShow=!!r.delimiterLazyShow,e.delimiters=r.delimiters||[],e.blocks=r.blocks||[],e.blocksLength=e.blocks.length,e.root="object"==typeof t&&t?t:window,e.document=r.document||e.root.document,e.maxLength=0,e.backspace=!1,e.result="",e.onValueChanged=r.onValueChanged||function(){},e}};e.exports=r}).call(t,function(){return this}())}])});;
