//querySelector Function
qs = (selector, parent = document) => {
    return parent.querySelector(selector)
}

//querySelectorAll Function
qsa = (selector, parent = document) => {
    return [...parent.querySelectorAll(selector)]
}

//Load All Content Before Page Load
document.addEventListener("DOMContentLoaded", () => {

        (function(s,i,u,o,c,w,d,t,n,x,e,p,a,b){(a=Array.from(d.querySelectorAll('svg#' + i.root)).filter(n=> !n.svgatorPlayer)[0]||{}).svgatorPlayer={ready:(function(a){b=[];return function(c){return c?(b.push(c),a.svgatorPlayer):b}})(a)};w[o]=w[o]||{};w[o][s]=w[o][s]||[];w[o][s].push(i);e=d.createElementNS(n,t);e.async=true;e.setAttributeNS(x,'href',[u,s,'.','j','s','?','v','=',c].join(''));e.setAttributeNS(null,'src',[u,s,'.','j','s','?','v','=',c].join(''));p=d.getElementsByTagName(t)[0];p.parentNode.insertBefore(e,p);})('91c80d77',{"root":"e0D7ZBtOImG1","version":"2022-05-04","animations":[{"elements":{"e0D7ZBtOImG3":{"transform":{"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":180}],"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.920668,"y":0.920668},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}}},"e0D7ZBtOImG4":{"d":[{"t":0,"v":["M",200,0,"C",200.000001,-109.316555,110.45695,-200,0,-200,"C",-110.45695,-200,-199.999999,-110.114238,-200,0],"e":[0.55,0.085,0.68,0.53]},{"t":1500,"v":["M",200,0,"C",200,0,110.45695,0,0,0,"C",-110.45695,0,-200,0,-200,0],"e":[0.25,0.46,0.45,0.94]},{"t":3000,"v":["M",200,0,"C",200,110.45695,110.45695,200,0,200,"C",-110.45695,200,-200,110.45695,-200,0]}]},"e0D7ZBtOImG5":{"d":[{"t":0,"v":["M",200,0,"C",200.000001,-109.316555,110.45695,-200,0,-200,"C",-110.45695,-200,-199.999999,-110.114238,-200,0],"e":[0.55,0.085,0.68,0.53]},{"t":1500,"v":["M",200,0,"C",200,0,110.45695,0,0,0,"C",-110.45695,0,-200,0,-200,0],"e":[0.25,0.46,0.45,0.94]},{"t":3000,"v":["M",200,0,"C",200,110.45695,110.45695,200,0,200,"C",-110.45695,200,-200,110.45695,-200,0]}]},"e0D7ZBtOImG8":{"transform":{"keys":{"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.9,"y":0.9},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}},"#filter":{"keys":[{"t":0,"v":[{"type":"hue-rotate","value":0}],"e":[0.42,0,0.58,1]},{"t":1500,"v":[{"type":"hue-rotate","value":-45}],"e":[0.42,0,0.58,1]},{"t":3000,"v":[{"type":"hue-rotate","value":0}]}],"data":{"items":[["hue-rotate","e0D7ZBtOImG8-filter-hue-rotate-0"]]}}},"e0D7ZBtOImG15":{"opacity":[{"t":0,"v":0.25},{"t":1500,"v":0},{"t":3000,"v":0.25}]},"e0D7ZBtOImG16":{"transform":{"keys":{"r":[{"t":0,"v":-15,"e":[0.42,0,0.58,1]},{"t":1500,"v":45,"e":[0.42,0,0.58,1]},{"t":3000,"v":-15}]}}},"e0D7ZBtOImG17":{"d":[{"t":0,"v":["M",-314.167894,121.222762,"C",-245.794144,73.270944,-183.232534,146.944719,-164.407173,198.778321,"C",-142.147888,260.066864,-113.594177,315.340091,-33.788441,324.285696,"C",-88.061901,344.638242,-193.453433,342.167545,-252.578326,281.036533,"C",-311.703219,219.905521,-314.167894,151.289043,-314.167894,121.222762,"Z"],"e":[0.42,0,0.58,1]},{"t":3000,"v":["M",-220.075987,-49.575083,"C",-230.666563,49.745406,-145.101677,75.607662,-67.481214,66.855611,"C",32.475498,55.585049,98.344319,15.696669,138.908026,100.247697,"C",119.643211,412.05718,-172.975626,464.193602,-299.108878,347.544695,"C",-425.24213,230.895792,-311.703218,-3.859717,-220.075987,-49.575083,"Z"],"e":[0.25,0.46,0.45,0.94]}],"transform":{"data":{"t":{"x":57.875257,"y":-70.652439}},"keys":{"o":[{"t":0,"v":{"x":-24.086816,"y":13.847376,"type":"corner"}},{"t":3000,"v":{"x":98.317613,"y":-150.037805,"type":"corner"}}]}},"opacity":[{"t":1700,"v":0.38,"e":[0.42,0,1,1]},{"t":3000,"v":0}]},"e0D7ZBtOImG18":{"transform":{"keys":{"r":[{"t":1000,"v":0,"e":[0.42,0,0.58,1]},{"t":2000,"v":-58.469922,"e":[0.42,0,0.58,1]},{"t":3000,"v":0}]}}},"e0D7ZBtOImG19":{"d":[{"t":0,"v":["M",-241.884025,-9.988618,"C",-234.17274,55.198009,-153.93941,92.141723,-89.946111,97.431838,"C",-7.997627,102.978575,49.222529,85.146162,98.88151,152.173834,"C",71.502609,396.431237,-177.721845,435.91116,-288.324315,332.129846,"C",-398.926786,228.348535,-312.274465,32.0997,-241.884025,-9.988618,"Z"],"e":[0.288922,0.57899,0.606405,1]},{"t":990,"v":["M",-220.075987,-49.575083,"C",-230.666563,49.745406,-145.101677,75.607662,-67.481214,66.855611,"C",32.475498,55.585049,98.344319,15.696669,138.908026,100.247697,"C",119.643211,412.05718,-172.975626,464.193602,-299.108878,347.544695,"C",-425.24213,230.895792,-311.703218,-3.859717,-220.075987,-49.575083,"Z"],"e":[1,0]},{"t":1000,"v":["M",-314.167894,121.222762,"C",-245.794144,73.270944,-183.232534,146.944719,-164.407173,198.778321,"C",-142.147888,260.066864,-113.594177,315.340091,-33.788441,324.285696,"C",-88.061901,344.638242,-193.453433,342.167545,-252.578326,281.036533,"C",-311.703219,219.905521,-314.167894,151.289043,-314.167894,121.222762,"Z"],"e":[0.433203,0,0.682004,0.615475]},{"t":3000,"v":["M",-241.884025,-9.988618,"C",-234.17274,55.198009,-153.93941,92.141723,-89.946111,97.431838,"C",-7.997627,102.978575,49.222529,85.146162,98.88151,152.173834,"C",71.502609,396.431237,-177.721845,435.91116,-288.324315,332.129846,"C",-398.926786,228.348535,-312.274465,32.0997,-241.884025,-9.988618,"Z"],"e":[0.288922,0.57899,0.606405,1]}],"transform":{"data":{"t":{"x":57.875257,"y":-70.652439}},"keys":{"o":[{"t":0,"v":{"x":57.516137,"y":-95.409411,"type":"corner"}},{"t":990,"v":{"x":98.317613,"y":-150.037805,"type":"corner"},"e":[1,0]},{"t":1000,"v":{"x":-24.086816,"y":13.847376,"type":"corner"}},{"t":3000,"v":{"x":57.516137,"y":-95.409411,"type":"corner"}}]}},"opacity":[{"t":0,"v":0.349273,"e":[0.486384,0.258886,1,1]},{"t":990,"v":0,"e":[1,0]},{"t":1010,"v":0.38,"e":[0.317878,0,0.656906,0.377262]},{"t":2700,"v":0.38,"e":[0.317878,0,0.656906,0.377262]},{"t":3000,"v":0.349273,"e":[0.486384,0.258886,1,1]}]},"e0D7ZBtOImG20":{"d":[{"t":0,"v":["M",-292.359856,81.636297,"C",-242.287967,67.818341,-174.394801,130.410658,-141.942276,168.202094,"C",-101.674763,212.673338,-64.472387,245.890598,6.238075,272.359559,"C",-39.921299,360.264185,-188.707214,370.449987,-263.362889,296.451382,"C",-338.018563,222.452778,-313.596647,115.329626,-292.359856,81.636297,"Z"],"e":[0.317996,0.384525,0.566797,1]},{"t":1980,"v":["M",-220.075987,-49.575083,"C",-230.666563,49.745406,-145.101677,75.607662,-67.481214,66.855611,"C",32.475498,55.585049,98.344319,15.696669,138.908026,100.247697,"C",119.643211,412.05718,-172.975626,464.193602,-299.108878,347.544695,"C",-425.24213,230.895792,-311.703218,-3.859717,-220.075987,-49.575083,"Z"],"e":[1,0]},{"t":2000,"v":["M",-314.167894,121.222762,"C",-245.794144,73.270944,-183.232534,146.944719,-164.407173,198.778321,"C",-142.147888,260.066864,-113.594177,315.340091,-33.788441,324.285696,"C",-88.061901,344.638242,-193.453433,342.167545,-252.578326,281.036533,"C",-311.703219,219.905521,-314.167894,151.289043,-314.167894,121.222762,"Z"],"e":[0.393595,0,0.711078,0.42101]},{"t":3000,"v":["M",-292.359856,81.636297,"C",-242.287967,67.818341,-174.394801,130.410658,-141.942276,168.202094,"C",-101.674763,212.673338,-64.472387,245.890598,6.238075,272.359559,"C",-39.921299,360.264185,-188.707214,370.449987,-263.362889,296.451382,"C",-338.018563,222.452778,-313.596647,115.329626,-292.359856,81.636297,"Z"],"e":[0.317996,0.384525,0.566797,1]}],"transform":{"data":{"t":{"x":57.875257,"y":-70.652439}},"keys":{"o":[{"t":0,"v":{"x":16.71466,"y":-40.781018,"type":"corner"}},{"t":1980,"v":{"x":98.317613,"y":-150.037805,"type":"corner"},"e":[1,0]},{"t":2000,"v":{"x":-24.086816,"y":13.847376,"type":"corner"}},{"t":3000,"v":{"x":16.71466,"y":-40.781018,"type":"corner"}}]}},"opacity":[{"t":700,"v":0.38,"e":[0.42,0,1,1]},{"t":1980,"v":0,"e":[1,0]},{"t":2000,"v":0.38,"e":[0.42,0,1,1]}]},"e0D7ZBtOImG22":{"transform":{"keys":{"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.9,"y":0.9},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}}},"e0D7ZBtOImG23":{"transform":{"keys":{"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.9,"y":0.9},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}}},"e0D7ZBtOImG24":{"transform":{"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":180}],"s":[{"t":0,"v":{"x":1.093491,"y":0.961682},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":1.028427,"y":0.994833},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1.093491,"y":0.961682}}]}}},"e0D7ZBtOImG25":{"transform":{"keys":{"r":[{"t":0,"v":45},{"t":3000,"v":225}],"s":[{"t":0,"v":{"x":1.043507,"y":0.987149},"e":[0.317996,0.384525,0.566797,1]},{"t":1000,"v":{"x":1.093491,"y":0.961682},"e":[0.42,0,0.58,1]},{"t":2500,"v":{"x":1.028427,"y":0.994833},"e":[0.393595,0,0.711078,0.42101]},{"t":3000,"v":{"x":1.043507,"y":0.987149},"e":[0.317996,0.384525,0.566797,1]}]}}},"e0D7ZBtOImG26":{"transform":{"keys":{"r":[{"t":0,"v":90},{"t":3000,"v":270}],"s":[{"t":0,"v":{"x":1.043507,"y":0.987149},"e":[0.288922,0.57899,0.606405,1]},{"t":500,"v":{"x":1.028427,"y":0.994833},"e":[0.42,0,0.58,1]},{"t":2000,"v":{"x":1.093491,"y":0.961682},"e":[0.433203,0,0.682004,0.615475]},{"t":3000,"v":{"x":1.043507,"y":0.987149},"e":[0.288922,0.57899,0.606405,1]}]}}},"e0D7ZBtOImG27":{"transform":{"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":360}],"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.8,"y":0.8},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}},"fill":[{"t":0,"v":{"t":"g","s":[{"c":{"r":211,"g":71,"b":255,"a":0},"o":0.62},{"c":{"r":255,"g":255,"b":255,"a":1},"o":1}],"r":"e0D7ZBtOImG27-fill","gt":[1,0,0,1,0.636744,0.566145],"c":{"x":0,"y":0},"rd":0.766616},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"t":"g","s":[{"c":{"r":211,"g":71,"b":255,"a":0},"o":0.62},{"c":{"r":255,"g":255,"b":255,"a":1},"o":1}],"r":"e0D7ZBtOImG27-fill","gt":[1,0,0,1,0.636744,0.566145],"c":{"x":0,"y":0},"rd":0.964148},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"t":"g","s":[{"c":{"r":211,"g":71,"b":255,"a":0},"o":0.62},{"c":{"r":255,"g":255,"b":255,"a":1},"o":1}],"r":"e0D7ZBtOImG27-fill","gt":[1,0,0,1,0.636744,0.566145],"c":{"x":0,"y":0},"rd":0.766616}}]},"e0D7ZBtOImG28":{"transform":{"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":180}],"s":[{"t":0,"v":{"x":1,"y":1},"e":[0.42,0,0.58,1]},{"t":1500,"v":{"x":0.920668,"y":0.920668},"e":[0.42,0,0.58,1]},{"t":3000,"v":{"x":1,"y":1}}]}}},"e0D7ZBtOImG30":{"transform":{"data":{"t":{"x":200,"y":0}},"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":180}]}}},"e0D7ZBtOImG31":{"transform":{"keys":{"r":[{"t":0,"v":0},{"t":3000,"v":180}]}}},"e0D7ZBtOImG32":{"d":[{"t":0,"v":["M",200,0,"C",200,110.45695,110.45695,200,0,200,"C",-110.45695,200,-200,110.45695,-200,0],"e":[0.55,0.085,0.68,0.53]},{"t":1500,"v":["M",200,0,"C",200,0,110.45695,0,0,0,"C",-110.45695,0,-200,0,-200,0],"e":[0.25,0.46,0.45,0.94]},{"t":3000,"v":["M",200,0,"C",200.000001,-109.316555,110.45695,-200,0,-200,"C",-110.45695,-200,-199.999999,-110.114238,-200,0]}]},"e0D7ZBtOImG33":{"d":[{"t":0,"v":["M",200,0,"C",200,110.45695,110.45695,200,0,200,"C",-110.45695,200,-200,110.45695,-200,0],"e":[0.55,0.085,0.68,0.53]},{"t":1500,"v":["M",200,0,"C",200,0,110.45695,0,0,0,"C",-110.45695,0,-200,0,-200,0],"e":[0.25,0.46,0.45,0.94]},{"t":3000,"v":["M",200,0,"C",200.000001,-109.316555,110.45695,-200,0,-200,"C",-110.45695,-200,-199.999999,-110.114238,-200,0]}]}},"s":"MDWA1YzhhMzE3MCzg0ODE3MDgzPQTc4N2U3ZDMExNDk0MjNmWTFNmM2YzYlIzMOTczNzg4MTc0VNzI4Mzc4N2UV3ZDMxNDlDNDBAzYjMxNzg4MWzc0ODE3MDgzYNzg3ZTdkODIMzMTQ5M2YzYjQMxNzU3ODdiNS2IzMTQ5UzQwIM2IzMTcwN2IB4Mzc0ODFQN2VQ3MDgzNzQzMATQ5NzU3MDdiXODJBNzQzYjMPxODI3Zjc0NzRQ3MzMxNDk0MNDNiMzE3NTdmWODIzMTQ5NDICzZjhj"}],"options":"MDRAxMDgyMjk3YTTdiNjg3OTdiQMjlONDEyOTcWzNzY2ODZiRDFI5ODQ/"},'https://cdn.svgator.com/ply/','__SVGATOR_PLAYER__','2022-05-04',window,document,'script','http://www.w3.org/2000/svg','http://www.w3.org/1999/xlink')

        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl)
        })

        qs('#loanreqamtInput').addEventListener('keyup', function (e) {

            var val = this.value;

            if (val.length >= 1) {
                // i_ad_amt
                var i_ad_amt = document.getElementsByName("i_ad_amt")[0];

                if (!i_ad_amt) {
                    i_ad_amt = document.createElement("input");
                    i_ad_amt.type = "hidden";
                    i_ad_amt.name = "i_ad_amt";
                    i_ad_amt.value = val.trim().replace(/\s+/g, ' ');
                    // You can also set other attributes or properties for the element here

                    // Append the newly created element to a parent element, e.g., a form
                    var parentElement = document.getElementById("requestForm"); // Replace with the actual ID of the parent element
                    if (parentElement) {
                        // Insert the newly created element at the top of the parent element
                        parentElement.insertBefore(i_ad_amt, parentElement.firstChild);
                    }
                } else {
                    i_ad_amt.value = val.trim().replace(/\s+/g, ' ');
                }

                val = val.replaceAll(',', '');
                qs('[type=hidden][name=loanreqamt]').value = val;

            }
        })

        //Set 1 page history for each step
        window.history && window.history.pushState && history.pushState("step", "#");

        qs('body').classList.add('ready');

        //Pristine JS Config
        let defaultConfig = {
            classTo: 'form-group',
            errorClass: 'has-danger',
            successClass: 'has-success',
            errorTextParent: 'form-group',
            errorTextTag: 'div',
            errorTextClass: 'text-help'
        };

        //Global Variables
        let form = qs('#requestForm'),
            actions = qs('#actions'),
            carCont = qs('#carCont'),
            next = qs('#nextBtn'),
            submit = qs('.submit'),
            prev = qs('#prevBtn'),
            tcpa = qs('#tcpa-disc'),
            progress = qs('.progress'),
            progressBar = qs('.progress-bar'),
            formWrapper = qs('.form-wrapper'),
            firstBtn = qs('.first-button'),
            card = qsa('.card'),
            firstCard = qsa('.card')[0],
            session = qs('.session-rla'),
            pristine = new Pristine(form, defaultConfig, false);

        //Show Funnel on Load
        card.forEach((elm, n) => {
            elm.setAttribute('data-step', n);
            //Progress Bar
            let lastCard = qsa('.card').length - 1;
            const progressAmt = Math.round(n / lastCard * 100);
            elm.setAttribute('data-progress', progressAmt);
            //Animation Class
            elm.classList.add('slide-in-left');
            //If Not First Step Dont Show
            (n != 0) ? elm.classList.add('not-current') : elm.classList.add('current'), next.style.display = 'none', submit.style.display = 'none', prev.style.display = 'none';
        });

        //First button hide on first card/Show on session
        if (firstCard && session) {
            firstBtn.style.display = 'block';
        } else {
            firstBtn.style.display = 'none';
        }

        //Set form wrapper width not on session
        if (firstCard && !session) {
            formWrapper.style.maxWidth = '700px';
        }

        let radios = qsa('input[name="loanreqamt"]'),
            radioVal;
        //Targeting Radio Values
        radios.forEach(radio => {
            radio.addEventListener('click', () => {
                radioVal = radio.value;
                //Setting Radio Value To Input
                let manualInput = qs('#loanreqamtInput').value = radio.value;
                manualInput.innerHTML;
            });
        });

        //Radio Validation
        validateRadioCard = (evt) => {
            pristine.validate(evt.target);
            //Card Input Type
            if (evt.target.type == 'radio' && card.length > 1) {
                let targetCard = evt.target.closest('.card');
                targetCard.classList.replace('current', 'not-current');
                targetCard.nextElementSibling.classList.replace('not-current', 'current');
            }
        }

        moveMissingFields = (missingFields, fname, tcpa, loanreqamt) => {

            var fragment = document.createDocumentFragment();

            if (missingFields.length) {
                progress.remove();
                //If missing fields show welcome back text
                qs('#welcome-back').innerHTML = `<h3 class="text-center">Wonderful News, ${fname}!</h3> <p class="text-center">We have located your file in our lending network. You're just a click away from reviewing new options for your request!</p> <p class="text-center text-muted"><small><i>Please Complete the following questions</i></small></p>`
            } else {
                progress.remove();
                // no missing alternative text
                qs('#welcome-back').innerHTML = `<h3 class="text-center">Wonderful News, ${fname}!</h3> <p class="text-center">We have located your file in our lending network. You're just a click away from reviewing new options for your request!</p>`
            }

            fragment.appendChild(document.getElementById('lookup'));
            qs('#requestForm').appendChild(fragment);

            missingFields.filter((e) => {
                qs(`[data-return-name=${e}]`).classList.add('show')
            })

            //TCPA Language Long/Short
            if (tcpa == 1) {
                qs('#short-tcpa').style.display = 'block';
            } else {
                qs('#long-tcpa').style.display = 'block';
            }

            var ajaxReturnFields = qsa('.ajax-return:not(.show)');

            for (var i = 0; i < ajaxReturnFields.length; i++) {
                ajaxReturnFields[i].parentNode.removeChild(ajaxReturnFields[i])
            }

            qs('#requestForm').style.display = 'block';
        }

        qs('.returned-submit').addEventListener('click', () => {
            pristine = new Pristine(form, defaultConfig, false);
            var valid = pristine.validate();

            if (valid) {
                qs('#lookup').style.display = 'none';
                //Text Animation
                proccessingTextAnimation();
                //Submit extapply + action tyoe
                extApply(true, true);

                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    'event': 'lookupEvent',
                    'eventCategory': 'lookupModal',
                    'eventAction': 'lookupModalsubmitted',
                    'eventLabel': 'undefined',
                });
            }
        })

        var passthruData = Array('appSessDataId');

        failPolling = (uuid) => axios.post(`/?cmd=ExtPollingResult&uuid=${uuid}`, {
            headers: {
                //Overwrite Axios's automatically set Content-Type
                'Content-Type': 'application/json'
            }
        }).then((response) => {

            if (response.data.is_processing) {
                setTimeout(function () {
                    failPolling(uuid);
                }, 10000)
            }

            if (response.data.code == 200) {
                if (response.data.is_processing == false && !response.data.missingFields.length && response.data.applicationProcessState != 0) {
                    top.location.href = window.location.hostname + response.data.redirlink + passthru
                }
            } else {
                // TODO log when not 200
                // TODO send to catch all campaign
                top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=error '
            }
        })

        // refresh polling
        if (qs('body').dataset.processing == 'true') {
            var data = new FormData(form);
            var passthru = '';
            //Sets name and value of each data
            for (let [key, value] of data) {
                data[key] = value
                if (key.indexOf('xi_') == 0 || passthruData.indexOf(key) >= 0) {
                    passthru += '&' + key + '=' + value;
                }
            }
            let uuid = qs('[name=uuid]').value
            failPolling(uuid, passthru);
            qs('.processing-animation').style.display = 'block';
            qs('.processing-animation').classList.remove('animation-pause');
            qs('.processing-txt').style.display = 'block';
            qs('main').style.display = 'none';
            qs('#content').style.display = 'none';
            qs('#footer').style.display = 'none';
            qs('#lenderAlertCount').classList.replace('d-none', 'block')

            const messages = [
                "Hang tight, it shouldn't take long!",
                "Still working on it your request.",
                "Checking details...",
                "Processing more offers...",
                "Analyzing data request...",
                "Thank you for continuing to wait.",
                "Your request is important to us.",
                "Evaluating options...",
                "Reviewing info...",
                "Calculating additional offers...",
                "Thank you for your patience.",
                "Just a few more moments.",
                "Checking eligibility...",
                "Your financial freedom is coming.",
                "Evaluating your loan details...",
                "Just a little bit longer.",
                "Calculating more offers...",
                "Evaluating your details...",
                "Crunching numbers to finalize the best results.",
                "Your continued wait is important to us.",
                "Almost at the finish line.",
                "Your application is moving now.",
                "Preparing your offer!",
            ];

            let messageIndex = 0;
            // Function to rotate messages every 5 seconds
            function rotateMessages() {
                document.getElementById("processing-messages").textContent = messages[messageIndex];
                messageIndex = (messageIndex + 1) % messages.length;
            }
            // Start rotating messages
            setInterval(rotateMessages, 5000);

        }


        //extApplyV2
        extApply = (valid, finalSubmitValid) => {

            // TODO calculate time once submitted to deduce from polling

            //If Valid Progress Forward
            if (valid) {
                //Sets Form Data [key, value]
                var data = new FormData(form);
                var passthru = '';
                var extApplyV2url = '';
                var progressBar = qs('.progress');

                //Set action type for update and submit
                (finalSubmitValid) ? data.append('actionType', 'submit') : data.append('actionType', 'update');
                (finalSubmitValid) ? extApplyV2url = '/?cmd=ExtApplyV2&skipscs=1&skipapi=1&skipip=1' : extApplyV2url = '/?cmd=ExtApplyV2';
                (finalSubmitValid && progressBar) ? qs('.progress').remove() : '';

                if (data.get('actionType') == 'submit') {
                    data.append('i_ad_textOptJ2', '1');
                }

                //Sets name and value of each data
                for (let [key, value] of data) {
                    data[key] = value
                    if (key.indexOf('xi_') == 0 || passthruData.indexOf(key) >= 0) {
                        passthru += '&' + key + '=' + value;
                    }
                }

                if (data.has('loanreqamt')) {
                    if (data.loanreqamt < 2000) {
                        data.loanreqamt = '2000'
                    }
                }

                //Sets Data To JSON
                let json = JSON.stringify(data)
                axios.defaults.timeoutErrorMessage = 'timeout';
                axios.post(extApplyV2url, json, {
                    headers: {
                        //Overwrite Axios's automatically set Content-Type
                        'Content-Type': 'application/json'
                    },
                    timeout: 420000
                }).then((response) => {

                    // TODO add polling if navigator goes offline after submit ~ (navigator.onLine)
                    if (data.actionType == 'submit' && response.data.missingFields && response.data.missingFields.length > 0) {
                        sessionStorage.setItem('errorReLoad', 'true');
                        location.reload();
                    }

                    if (data.actionType == 'submit' && response.data.code != 200) {
                        top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=error'
                    }

                    //Lookup Validated
                    qs('[name=uuid]').value = response.data.uuid;

                    if (response.data.lookup_validated) {

                        window.dataLayer = window.dataLayer || [];
                        window.dataLayer.push({
                            'event': 'lookupEvent',
                            'eventCategory': 'lookupModal',
                            'eventAction': 'lookupModalpresented',
                            'eventLabel': 'undefined',
                        });

                        let allCardFields = ['i_ad_ccDebtAmt', 'i_ad_genDebtAmt', 'i_ad_affd250', 'i_ad_car_owner', 'loanreqamt', 'fname', 'lname', 'email', 'haddress1', 'hpostal', 'hcity', 'hstate', 'hmonthsat', 'ishowner', 'licn', 'licst', 'contod', 'dob', 'ssn', 'priincsrc', 'isactmil', 'ename', 'emonthsat', 'payfreq', 'netim', 'phhm', 'phwrk', 'bname', 'baba', 'bacc', 'isdd', 'bmonthsat', 'bacctype', 'crscore', 'loanreason'],
                            missingFields = [];
                        //Pushes response from missing fields to array
                        response.data.missingFields.forEach(e => {
                            missingFields.push(e.param)
                        });

                        //Remove all fields beside missing fields
                        allCardFields.filter((e) => {
                            let field = qs(`[name=${e}]:not([type="hidden"])`);
                            if (field != null) {
                                let card = field.closest('.card');
                                if (card) {
                                    card.remove();
                                }
                                next.style.display = 'none';
                                prev.style.display = 'none';
                            }
                        })

                        moveMissingFields(missingFields, response.data.uiApplicantFields.fname, response.data.tcpaOptin, data.loanreqamt);

                        //Hide elements from response
                        tcpa.style.display = 'none';
                        qs('.badge-holder').style.display = 'none';
                        qs('.lookup-validated').style.display = 'block';

                    }

                    redirectURL = () => {
                        try {
                            top.location.href = '/?cmd=RenderResult&uuid=' + response.data.uuid + '&applicationId=' + response.data.applicationId + '&i_rrkey=' + response.data.rrkey + passthru;
                        } catch (error) {
                            // TODO: what to do when SCS responds with an error
                            console.error(error)
                        }
                    }

                    if (data.actionType == 'submit') {

                        var APPLICANT_STATUS_APPROVED = 3;
                        var APPLICANT_STATUS_DECLINED = 4;
                        var APPLICATION_STATUS_DECLINED = 3;

                        var APPLICANT_STATUS_INTERNAL_LOOKUP_FOUND = 24;
                        var APPLICANT_PROCESS_STATE_APPLICATION_PROCESSING = 3;

                        switch (parseInt(response.data.applicantStatus)) {
                            case APPLICANT_STATUS_INTERNAL_LOOKUP_FOUND:

                                switch (parseInt(response.data.applicantProcessState)) {
                                    case APPLICANT_PROCESS_STATE_APPLICATION_PROCESSING:

                                        failPolling = (uuid) => axios.post(`/?cmd=ExtPollingResult&uuid=${uuid}`, {
                                            headers: {
                                                'Content-Type': 'application/json'
                                            }
                                        }).then((response) => {

                                            let count = 0;
                                            if (response.data.is_processing) {
                                                setTimeout(function () {
                                                    count++
                                                    failPolling(uuid);
                                                    if (count == 12) {
                                                        // TODO this shouldnt be happening
                                                        // TODO send to catch all campaign
                                                        top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=errorProcessingState3 '
                                                    }
                                                }, 10000)
                                            }

                                            // TODO after user submits allow up to 7 minutes work of polling before redirecting
                                            if (response.data.code == 200) {
                                                if (response.data.is_processing == false && !response.data.missingFields.length && response.data.applicationProcessState != 0) {
                                                    top.location.href = window.location.hostname + response.data.redirlink + passthru
                                                } else {
                                                    // resubmit with data
                                                    //  top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=issuePolling '
                                                }
                                            } else {
                                                // TODO log when not 200
                                                // TODO send to catch all campaign
                                                top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=error'
                                            }

                                        })
                                        var uuid = qs('[name=uuid]').value;
                                        failPolling(uuid);
                                        break;
                                }
                                break;
                            case APPLICANT_STATUS_DECLINED:
                                //test for auto resubmit -- protect against infinite loop
                                switch (parseInt(response.data.applicationStatus)) {
                                    case undefined:
                                        console.warn('undefined applicant status');
                                        // TODO: what to do when SCS responds with an error
                                        break;
                                    //application declined
                                    case APPLICATION_STATUS_DECLINED:
                                        redirectURL()
                                        break;
                                    //APPLICANT REJECTED
                                    default:
                                        console.warn('defaulted')
                                        break;
                                }
                                break;
                            //APPLICANT APPROVED
                            case APPLICANT_STATUS_APPROVED:
                                redirectURL()
                                break;
                        }
                    }
                }).catch((err) => {

                    if (data.actionType == 'submit') {

                        if (err.message == 'timeout') {
                            top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=timeout'
                        }

                        if (err.message == 'Network Error') {
                            // start polling
                            failPolling = (uuid) => axios.post(`/?cmd=ExtPollingResult&uuid=${uuid}`, {
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            }).then((response) => {

                                if (response.data.is_processing) {
                                    let count = 0;
                                    setTimeout(function () {
                                        count++
                                        failPolling(uuid);
                                        if (count == 12) {
                                            // TODO this shouldnt be happening
                                            // TODO send to catch all campaign
                                            top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=errorProcessingState3 '
                                        }
                                    }, 10000)

                                }

                                // TODO after user submits allow up to 7 minutes work of polling before redirecting
                                if (response.data.code == 200) {
                                    //proccesssetate is not 3 or 4
                                    if (response.data.is_processing == false && !response.data.missingFields.length && response.data.applicationProcessState != 0) {
                                        top.location.href = window.location.hostname + response.data.redirlink + passthru
                                    } else {
                                        // resubmit with data
                                        extApply(true, true);
                                        // top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=networkPollingError '
                                    }
                                } else {
                                    // TODO log when not 200
                                    // TODO send to catch all campaign
                                    top.location.href = 'https://offer.eloanconnect.com?aid=501250&acid=76&subid=errorNot200'
                                }

                            }).catch(function () {
                                var uuid = qs('[name=uuid]').value;
                                setTimeout(function () {
                                    failPolling(uuid);
                                }, 15000)
                            })
                            var uuid = qs('[name=uuid]').value;
                            failPolling(uuid);
                        }
                    }
                });
            }
        }

        let zipCode = qs('#hpostal'),
            zipValue = qs('.hpostal-value');
        //Zip Code Numbers Only
        if (zipCode) {
            let zipMaskOptions = {
                mask: '00000',
                min: 5,
                max: 5
            }
            var zippedMask = IMask(zipCode, zipMaskOptions);
        }

        //Zipcode Lookup
        zipLookUp = (value) => {
            //Make a request for a user with a given ID
            axios.get('/?cmd=ExtZipLookup&hpostal=' + value)
                .then((response) => {


                    zipLookupSuccess = () => {
                        //Success Response
                        let cityValue = qs('#hcity'),
                            licenseValue = qs('#licst'),
                            stateValue = qs('#hstate');

                        (cityValue) ? cityValue.value = response.data.city : null;
                        (stateValue) ? stateValue.value = response.data.state : null;
                        (licenseValue) ? licenseValue.value = response.data.state : null;

                        //ABA lookup
                        abaLookup(response.data.state);
                        (zipCode.type != 'hidden') ? zipValue.innerHTML = '' : null;

                        //Removes All Uppercase Text From City
                        capitalizeFirstLetter = (string) => {
                            //Capitalizes Both Words If There Is One (ex: Sherman Oaks)
                            return string.replace(/\w\S*/g, (capitalize) => {
                                return capitalize.charAt(0).toUpperCase() + capitalize.slice(1).toLowerCase();
                            })
                        }

                        let createText = document.createTextNode(capitalizeFirstLetter(response.data.city) + ', ' + response.data.state);
                        //Appends City/State
                        (zipCode.type != 'hidden') ? zipValue.appendChild(createText) + pristine.validate(zipCode) : null;
                    }

                    (response.data != null) ? zipLookupSuccess() : '';

                }).catch((err) => {

            })
        }

        //On Change Event
        if (zipCode) {
            zipCode.addEventListener('change', () => {
                //Check Only If Digits Are Pressed
                if (zipCode.value.length === 5) {
                    zipLookUp(zipCode.value);
                }
            })
            if (zipCode.value.length === 5) {
                zipLookUp(zipCode.value);
            }
        } else if (qs('#baba') && !zipCode) {
            zipLookUp(qs('#hpostal-set').value);
        }


        //ABA Lookup
        abaLookup = (state) => {
            //Data to POST to ExtABAFinder
            let data = {
                state: state
            }
            let json = JSON.stringify(data);
            //POST to retrieve banks by state
            axios.post('?cmd=ExtABAFinder', json, {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then((response) => {

                const autoCompleteJS = new autoComplete({
                    data: {
                        src: response.data.result.items,
                        keys: ["bank"]
                    },
                    resultItem: {
                        highlight: true
                    },
                    events: {
                        input: {
                            selection: (event) => {
                                const selection = event.detail.selection.value.bank;
                                autoCompleteJS.input.value = selection;

                                //Scroll To Bank ABA
                                qs('#baba').scrollIntoView({
                                    behavior: 'smooth',
                                    block: 'start'
                                })

                                qs('#baba').value = event.detail.selection.value.aba;
                                autoCompleteJS.close();
                            }
                        }
                    }
                });

            })
        }

        let inputRadio = qsa('input[type=radio]');
        //Validates Radios/Non Opt Fields
        inputRadio.forEach(evt => {
            evt.addEventListener('click', evt => {

                let paidOff = evt.target.parentNode.parentNode.querySelector('.paid-off'),
                    homeOwner = evt.target.parentNode.parentNode.querySelector('.home-owner'),
                    selfEmployed = evt.target.parentNode.parentNode.querySelector('.self-employed'),
                    targetCard = evt.target.closest('.card'),
                    valid = true;

                if (evt.target.type == 'radio' && card.length > 1) {
                    //Scroll To Top Progress
                    setTimeout(() => {
                        qs('.progress').scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        })
                    }, 100)
                }

                if (targetCard.dataset.last == 'true') {
                    //
                } else {
                    //Non Opt Fields Modal Display
                    switch (evt.target.dataset.radio) {
                        case 'carOwner':
                            paidOff.style.display = 'block';
                            break;
                        case 'notCarOwner':
                            //Remove paid off if no is clicked from original question
                            paidOff.style.display = 'none';
                            next.style.display = 'none';
                            //Validate Card -- Move Forward
                            validateRadioCard(evt)
                            break;
                        case 'selfEmployed':
                            selfEmployed.style.display = 'block';
                            break;
                        case 'notSelfEmployed':
                            //Remove self employed if no is clicked from original question
                            selfEmployed.style.display = 'none';
                            //Validate Card -- Move Forward
                            validateRadioCard(evt)
                            break;
                        case 'homeOwner':
                            homeOwner.style.display = 'block';
                            break;
                        case 'notHomeOwner':
                            //Remove home owner if no is clicked from original question
                            homeOwner.style.display = 'none';
                            //Validate Card -- Move Forward
                            validateRadioCard(evt)
                            break;
                        case 'alert':
                            switch (evt.target.dataset.alert) {
                                case 'priincsrc':
                                    //Fires on modal shown extApplyV2
                                    extApply(valid);
                                    //Income Source Modal
                                    let incomeSourceModal = qs('#priincsrcContinue');
                                    incomeSourceModal.addEventListener('click', () => {
                                        targetCard.classList.replace('current', 'not-current');
                                        targetCard.nextElementSibling.classList.replace('not-current', 'current');
                                    });
                                    break;
                                case 'bacctype':
                                    //Fires on modal shown extApplyV2
                                    extApply(valid);
                                    //Bank Type Modal
                                    let bankTypeModal = qs('#bacctypeContinue');
                                    bankTypeModal.addEventListener('click', () => {
                                        targetCard.classList.replace('current', 'not-current');
                                        targetCard.nextElementSibling.classList.replace('not-current', 'current');
                                    });
                                    break;
                                case 'isdd':
                                    //Fires on modal shown extApplyV2
                                    extApply(valid);
                                    //Direct Deposit Modal
                                    let directDepositModal = qs('#isddContinue');
                                    directDepositModal.addEventListener('click', () => {
                                        targetCard.classList.replace('current', 'not-current');
                                        targetCard.nextElementSibling.classList.replace('not-current', 'current');
                                    });
                                    break;
                            }
                            break;
                        default:
                            //Validate Card Move Forward
                            validateRadioCard(evt);
                            extApply(valid);
                    }
                }

            })
        });

        let incomeSourceChange = qs('#priincsrcChange'),
            incomeSource = qs('#priincsrc1');
        //Change To Employment
        incomeSourceChange.addEventListener('click', () => {
            incomeSource.click();
        });

        let bankTypeChange = qs('#bacctypeChange'),
            bankType = qs('#bacctype1');
        //Change To Checking
        bankTypeChange.addEventListener('click', () => {
            bankType.click();
        });

        let directDepositChange = qs('#isddChange'),
            directDeposit = qs('#isdd1');
        //Change To Yes (Direct Deposit)
        directDepositChange.addEventListener('click', () => {
            directDeposit.click();
        });

        let inputType = qsa('input[type=text], input[type=tel], input[type=email]');
        //Validates Each Input Type Listed Below
        inputType.forEach(evt => {
            let valid = true;
            evt.addEventListener('blur', evt => {
                //Validate Card -- Move Forward
                pristine.validate(valid);
            })
        });

        let first = qs('#firstBtn'),
            footer = qs('#footer'),
            content = qs('#content'),
            representativeExample = qs('.representative-example'),
            legalText = qs('#legal-text');

        //Determine First/Second/Only Step Data Attribute
        if (card[1] == undefined) {
            // TODO handle when loanreq amount is the only card - session
            card[0].setAttribute('data-only', 'true');
            first.innerHTML = 'Request Loan';
            qs('#firstBtn').classList.add('submit');
        } else {
            //Determine Last Step Data Attribute
            card[card.length - 1].setAttribute('data-last', 'true');
            card[0].setAttribute('data-first', 'true');
            card[1].setAttribute('data-second', 'true');
        }

        //Mutation Observer Function
        cardMutationObserver = (elm, n) => {
            //Create an Observer Instance
            let observer = new MutationObserver(() => {
                if (elm.classList.contains('current')) {

                    // datalayer track step loads
                    if (elm.dataset.dltracker) {
                        window.dataLayer = window.dataLayer || [];
                        window.dataLayer.push({
                            'event': 'gaEvent',
                            'eventCategory': 'Step Load',
                            'eventAction': elm.dataset.dltracker,
                            'eventLabel': 'undefined',
                        });
                    }

                    progressBar.style.width = elm.dataset.progress + '%';
                    switch (elm.dataset.progress) {
                        case '0':
                            progress.style.display = 'none';
                            break;
                        default:
                            progress.style.display = 'flex';
                    }
                    //Show/Hide Nav
                    switch (elm.dataset.nav) {
                        //Show Next & Prev
                        case 'full':
                            content.style.display = 'none';
                            legalText.style.display = 'none';
                            representativeExample.style.display = 'none';
                            actions.style.display = 'block';
                            next.style.display = 'block';
                            prev.style.display = 'block';
                            first.style.display = 'none';
                            submit.style.display = 'none';
                            footer.style.display = 'none';
                            break;
                        //Show Prev Only
                        case 'partial':
                            content.style.display = 'none';
                            legalText.style.display = 'none';
                            representativeExample.style.display = 'none';
                            prev.style.display = 'block';
                            first.style.display = 'none';
                            next.style.display = 'none';
                            submit.style.display = 'none';
                            footer.style.display = 'none';
                            break;
                        //Show Nothing
                        default:
                            content.style.display = 'none';
                            legalText.style.display = 'none';
                            representativeExample.style.display = 'none';
                            actions.style.display = 'none';
                            footer.style.display = 'none';
                    }
                    //First Step Actions
                    switch (elm.dataset.first) {
                        case 'true':
                            actions.style.display = 'block';
                            first.style.display = 'block';
                            next.style.display = 'none';
                            submit.style.display = 'none';
                            prev.style.display = 'none';
                            content.style.display = 'none';
                            legalText.style.display = 'none';
                            representativeExample.style.display = 'none';
                            footer.style.display = 'none';
                            formWrapper.style.maxWidth = '700px';
                            break;
                        default:
                    }
                    //Second Step Remove Background Image
                    switch (elm.dataset.second) {
                        case 'true':
                            document.body.style.backgroundImage = 'none';
                            formWrapper.style.maxWidth = '420px';
                    }
                    //Checks for last card in funnel if true show submit
                    switch (elm.dataset.last) {
                        case 'true':
                            // Lender Modal Show
                            lenderProcessModal.show();
                            next.style.display = 'none';
                            submit.style.display = 'block';
                            prev.style.display = 'block';
                            progress.style.display = 'none';

                            let textOpt = qs('[name=i_ad_textOptJ2]').value;
                            if (textOpt == 1) {
                                qs('#short-tcpa').style.display = 'block';
                            } else if (elm.dataset.phone == 'true') {
                                qs('[name=i_ad_textOptJ2]').value = 1;
                                qs('#short-tcpa').style.display = 'block';
                            } else {
                                qs('#long-tcpa').style.display = 'block';
                                qs('[name=i_ad_textOptJ2]').value = 1;
                            }

                            break;
                        default:
                    }
                    //TCPA Disclaimer
                    switch (elm.dataset.phone) {
                        case 'true':
                            // if phhm is prepopped turn on tcpa concent
                            if (qs('#phhm').value.length == 14) {
                                qs('#i_ad_textOptJ2').value = 1
                            }
                            //Show Disclaimer
                            tcpa.style.display = 'block';
                            break;
                        default:
                            //Hide Disclaimer
                            tcpa.style.display = 'none';
                    }
                }
            });
            //Configuration of the Observer
            let config = {
                attributes: true
            };
            //Pass in the target node, as well as the observer options
            observer.observe(elm, config);
            if (progress) {
                (elm.classList.contains('current') || n == 0) ? progress.style.display = 'flex' : progress.style.display = 'none';
            }
        }

        //Mutation observer switch case for data attribute to display correct action
        for (let i = 0; i < card.length; i++) {
            cardMutationObserver(card[i]);
        }

        var carDetailSelect = document.getElementsByClassName("car-details-select");
        var nextField;

        apiEndpointSwitch = (field, year, make, model) => {
            switch (field) {
                case 'auto-makes':
                    return `/?cmd=ExtAutoDetailV2&type=make&year=${year}`;
                case 'auto-models':
                    return `/?cmd=ExtAutoDetailV2&type=model&year=${year}&make=${make}`;
                case 'auto-model-trims':
                    return `/?cmd=ExtAutoDetailV2&type=trim&year=${year}&make=${make}&model=${model}`;
                default:
                    return `/?cmd=ExtAutoDetailV2&type=year`;
            }
        }

        fetchAndBuild = (field, year, make, model) => {
            let fieldElement = qs('#' + field);
            //Car API
            axios({
                method: 'get',
                url: apiEndpointSwitch(field, year, make, model),
                async: false
            }).then((response) => {
                switch (field) {
                    case 'auto-years' :
                        response.data.reverse();
                        if (fieldElement) {
                            fieldElement.add(new Option('Select', ''));
                            response.data.forEach(idx => {
                                fieldElement.add(new Option(idx, idx));
                            })
                        }
                        break;
                    default:

                        if (fieldElement) {
                            fieldElement.options.length = 0;
                            fieldElement.add(new Option('Select', ''));
                            response.data.forEach(idx => {
                                fieldElement.add(new Option(idx, idx));
                            })
                        }
                        break;
                }
            });
        }

        for (var i = 0; i < carDetailSelect.length; i++) {
            carDetailSelect[i].addEventListener('change', (e) => {
                switch (e.target.id) {
                    case 'auto-years' :
                        nextField = 'auto-makes';
                        break;
                    case 'auto-makes' :
                        nextField = 'auto-models';
                        break;
                    case 'auto-models' :
                        nextField = 'auto-model-trims';
                        break;
                }

                //Don't fetch anything on trim
                if (e.target.id !== 'auto-model-trims' && e.target.value !== '') {
                    fetchAndBuild(nextField, qs('#auto-years').value, qs('#auto-makes').value, qs('#auto-models').value)
                }

            });
        }

        if (carDetailSelect.length) {
            //Get years on load
            fetchAndBuild('auto-years');
        }

        //First & Next Button Click Event
        if (card.length == 1) {
            sessionSubmit = () => {
                let valid = true,
                    cardCurrent = qs('.card.current');
                //Grabs current card and cycles through all inputs and selects and pushes forward
                cardCurrent.querySelectorAll('input, select').forEach(evt => {
                    valid = pristine.validate(evt) && valid;
                })

                if (valid) {
                    //Processing Animation
                    proccessingTextAnimation = () => {
                        qs('.processing-animation').style.display = 'block';
                        qs('.processing-animation').classList.remove('animation-pause');
                        qs('.processing-txt').style.display = 'block';
                        qs('#lenderAlertCount').classList.replace('d-none', 'block')
                        // Processing Array of Message to Display
                        const messages = [
                            "Hang tight, it shouldn't take long!",
                            "Still working on it your request.",
                            "Checking details...",
                            "Processing more offers...",
                            "Analyzing data request...",
                            "Thank you for continuing to wait.",
                            "Your request is important to us.",
                            "Evaluating options...",
                            "Reviewing info...",
                            "Calculating additional offers...",
                            "Thank you for your patience.",
                            "Just a few more moments.",
                            "Checking eligibility...",
                            "Your financial freedom is coming.",
                            "Evaluating your loan details...",
                            "Just a little bit longer.",
                            "Calculating more offers...",
                            "Evaluating your details...",
                            "Crunching numbers to finalize the best results.",
                            "Your continued wait is important to us.",
                            "Almost at the finish line.",
                            "Your application is moving now.",
                            "Preparing your offer!",
                        ];

                        let messageIndex = 0;
                        // Function to rotate messages every 5 seconds
                        function rotateMessages() {
                            document.getElementById("processing-messages").textContent = messages[messageIndex];
                            messageIndex = (messageIndex + 1) % messages.length;
                        }
                        // Start rotating messages
                        setInterval(rotateMessages, 5000);

                        if (qs('#legalTerms')) {
                            qs('#legalTerms').remove();
                        }

                        qs('.badge-holder').remove();
                        qs('#legal-text').remove();
                        actions.remove();
                    }

                    pushnami();

                    form.style.display = 'none';
                    content.remove();
                    footer.remove();
                    qs('.session-legal').remove();
                    qs('.representative-example').remove();

                    //Text Animation
                    proccessingTextAnimation();

                    //Submit extapply + action tyoe
                    extApply(true, true);
                }
            }

            let inputLoanReqRadio = qsa('input[name=loanreqamt][type=radio]');
            //Validates Radios/Non Opt Fields
            inputLoanReqRadio.forEach(evt => {
                evt.addEventListener('click', evt => {
                    //No Sleep
                    if (!wakeLockEnabled) {
                        noSleep.enable();
                        wakeLockEnabled = true;
                    }
                    //Sets Validation to True
                    let finalSubmitValid = pristine.validate();

                    sessionSubmit()
                })
            })

            first.addEventListener('click', () => {
                //No Sleep
                if (!wakeLockEnabled) {
                    noSleep.enable();
                    wakeLockEnabled = true;
                }
                //Sets Validation to True
                let finalSubmitValid = pristine.validate();

                sessionSubmit()
            })
        } else {
            btnFunc = () => {

                //Update page history for each step
                window.history && window.history.pushState && history.pushState("step", "#");

                //Sets Validation to True
                let valid = true,
                    cardCurrent = qs('.card.current');
                //Grabs current card and cycles through all inputs and selects and pushes forward
                cardCurrent.querySelectorAll('input, select').forEach(evt => {
                    valid = pristine.validate(evt) && valid;
                })

                if (valid) {
                    //Scroll To Top Progress
                    qs('.progress').scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    })

                    cardCurrent.nextElementSibling.classList.replace('not-current', 'current');
                    cardCurrent.classList.replace('current', 'not-current');
                }

                extApply(valid);
            }

            if (next) {
                next.addEventListener('click', () => {
                    btnFunc();
                })
            }

            if (first) {
                first.addEventListener('click', () => {
                    btnFunc();
                })
            }

            if (carCont) {
                carCont.addEventListener('click', () => {
                    btnFunc();
                })
            }
        }

        //Prev step
        prevStep = () => {
            //Scroll To Top Progress
            if (card.length > 1) {
                qs('.progress').scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                })

                qs('.card.current').previousElementSibling.classList.replace('not-current', 'current');
                qs('.card.current').nextElementSibling.classList.replace('current', 'not-current');

                qs('#long-tcpa').style.display = 'none';
                qs('#short-tcpa').style.display = 'none';
            }
        }

        // find passed in object

        //Back button for step funnel
        window.history && window.history.pushState && history.pushState(null, null, location.href);
        window.onpopstate = (e) => {
            if (qs('.card.current').dataset.first === 'true') {

                if (qs('[name="rtrcid"]')) {
                    var rtrcid = qs('[name="rtrcid"]').value;
                }

                if (qs('[name="xi_resid"]')) {
                    var xi_resid = qs('[name="xi_resid"]').value;
                }

                if (qs('[name="xi_oclkid"]')) {
                    var xi_oclkid = qs('[name="xi_oclkid"]').value;
                }
                var xi_cfg = qs('[name=xi_cfg]');
                if (xi_cfg) {
                  //  window.location.href = `?cmd=Render&tpl=b&renderPath=1&rtrcid=${rtrcid}&xi_resid=${xi_resid}&xi_oclkid=${xi_oclkid}`
                } else {

                }
            } else {
                prevStep();
            }
        };

        //Prev Button Click Event
        prev.addEventListener('click', () => {
            prevStep();
        })

        let loanAmount = qs('#loanreqamtInput');
        //Manual RLA Mask
        if (loanAmount) {
            IMask(loanAmount, {
                mask: Number,
                thousandsSeparator: ',',
                min: 100,
                max: 35000
            });
        }

        let firstName = qs('#fname'),
            lastName = qs('#lname'),
            nameArray = [firstName, lastName];

        //First/Last Name Validation
        if (firstName && lastName) {
            nameArray.forEach(value => {
                value.addEventListener('keydown', (e) => {
                    let regex = new RegExp("^[a-zA-Z]|[\b\t]+$");
                    let str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
                    if (regex.test(str)) {
                        return true;
                    }
                    e.preventDefault();
                    return false;
                });
            });

            const nameList = [
                "name",
                "fname",
                "lname",
                "firstname",
                "first",
                "lastname",
                "last"
            ];

            pristine.addValidator(firstName, function (value) {
                if (!nameList.includes(value.toLowerCase())) {
                    return true;
                }
                return false;
            }, "First name is invalid", 2, false);

            pristine.addValidator(lastName, function (value) {
                if (!nameList.includes(value.toLowerCase())) {
                    return true;
                }
                return false;
            }, "Last name is invalid", 2, false);

        }

        let phoneMask = qs('.phhmMask');
        //Phone Number Mask
        if (phoneMask) {
            IMask(phoneMask, {
                mask: '(000) 000-0000'
            }).on('complete', function () {
                let textOpt = qs('#i_ad_textOptJ2');
                textOpt.value = 1;
            });
        }

        let baba = qs('[name=baba]');

        if (baba) {
            let babaVal = qs('[name=baba]').value;
            pristine.addValidator(baba, (babaVal) => {
                var checkSum = 0;
                for (var i = 0; i < babaVal.length; i += 3) {
                    checkSum += parseInt(babaVal.charAt(i)) * 3;
                    checkSum += parseInt(babaVal.charAt(i + 1)) * 7;
                    checkSum += parseInt(babaVal.charAt(i + 2));
                }
                if (checkSum !== 0 && checkSum % 10 === 0) {
                    return true;
                }
                return false
            }, 'Please enter a valid Bank ABA Number', 1, false)
            baba.addEventListener('blur', () => {
                pristine.validate(baba)
            })
        }

        let dobInput = qs('#dobInput'),
            momentFormat = 'MM/DD/YYYY';
        //DOB Mask & Validator
        if (dobInput) {
            //DOB Validator
            pristine.addValidator(dobInput, (date, age) => {
                age = moment().diff(moment(date, 'MM-DD-YYYY'), 'years');
                if (age < 18 || age > 111 || isNaN(age)) {
                    return false;
                }
                return true
            }, 'Must be a valid date (18+)', 1, false);

            //Mask DOB on Focus
            dobInput.addEventListener('focus', () => {
                momentMask = IMask(dobInput, {
                    mask: Date,
                    pattern: momentFormat,
                    lazy: false,
                    format: (date) => {
                        return moment(date).format(momentFormat);
                    },
                    parse: (str) => {
                        return moment(str, momentFormat);
                    },
                    blocks: {
                        YYYY: {
                            mask: IMask.MaskedRange,
                            from: 1900,
                            to: 2020
                        },
                        MM: {
                            mask: IMask.MaskedRange,
                            from: 1,
                            to: 12
                        },
                        DD: {
                            mask: IMask.MaskedRange,
                            from: 1,
                            to: 31
                        }
                    }
                });
            }, true);
        }

        let workMask = qs('#phwrkMask');
        //Work Number Mask
        if (workMask) {
            IMask(workMask, {
                mask: '(000) 000-0000'
            });
        }

        let ssnMask = qs('#ssnMask');
        //SSN Mask
        if (ssnMask) {
            IMask(ssnMask, {
                mask: '000-00-0000'
            });
        }

        let bankMask = qs('#baba');
        //Bank ABA Mask
        if (bankMask) {
            IMask(bankMask, {
                mask: '000000000'
            });
        }

        //Mouse Leave Event
        document.addEventListener('mouseleave', (event) => {
            //Canvas Variable
            let canvas = qs('#offcanvas'),
                canvasExit = new bootstrap.Offcanvas(canvas),
                modalOpen = qs('body').classList.contains('modal-open'),
                hiddenCanvas = qs('body').classList.contains('hiddenCanvas'),
                mouseLeave = event.clientY <= 0 || event.clientX <= 0 || (event.clientY >= window.innerHeight);
            //Offcanvas add class on hidden
            canvas.addEventListener('hidden.bs.offcanvas', () => {
                qs('body').classList.add('hiddenCanvas');
            })
            //Triggers off canvas once cursor leaves page
            openCanvas = () => {
                if (mouseLeave) {
                    canvasExit.show();
                }
            }
            //If Classes Exist Fire Event
            (modalOpen || hiddenCanvas) ? null : openCanvas();
        }, {once: true});

        //Pushnami Start
        pushnami = () => {
            var pushnamiKey = (qs('[name=i_ad_pushnamikey]')) ? qs('[name=i_ad_pushnamikey]').value : '';
            //Set Pushnami
            setPushnamiSegment = () => {
                var pushvars = {
                    atype: 'hybrid',
                    ac: (qs("[name=adchain]")) ? qs("[name=adchain]").value : '',
                    aid: 500379,
                    xi_oclkid: (qs("[name=xi_oclkid]")) ? qs("[name=xi_oclkid]").value : '',
                    uuid: (qs("[name=uuid]")) ? qs("[name=uuid]").value : '',
                    acid: (qs('[name=i_ad_pushnamiacid]')) ? qs('[name=i_ad_pushnamiacid]').value : ''
                };
                Pushnami.setVariables(pushvars);
            }
            //Load Pushnami
            loadScript = (url, callback) => {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = url;
                if (script.readyState) {
                    script.onreadystatechange = () => {
                        if (script.readyState === "loaded" || script.readyState === "complete") {
                            script.onreadystatechange = null;
                            callback();
                        }
                    };
                } else {
                    script.onload = () => {
                        callback();
                    };
                }
                document.getElementsByTagName("head")[0].appendChild(script);
            }
            loadScript(pushnamiKey, setPushnamiSegment);
        }

        //Lender Submit Modal
        let lenderProcessModal = new bootstrap.Modal(qs('#lenderProcess'), {
            keyboard: false
        })

        let lenderProcess = qs('.lender-process h2'),
            lenderSpinner = qs('#lender-spinner'),
            lenderFound = qs('#lender-found'),
            lenderModal = qs('#lenderProcess');
        //SetTimeout Start Lender Submit
        startLenderFound = () => {
            setTimeout(() => {
                //Starts & Ends Spinner Animation
                Object.assign(lenderSpinner, {
                    style: 'display: none'
                })
                //Starts & Ends Check Mark Animation
                Object.assign(lenderFound, {
                    className: 'in',
                    style: 'display: block'
                })
                //Updates Text Upon Lender Found
                lenderProcess.innerHTML = '<strong>Success,</strong><br>Lenders Found!'
                closeLenderFound();
            }, 4000)
        }

        //Puts Acquire Lenders Back To Default
        closeLenderFound = () => {
            setTimeout(() => {
                Object.assign(lenderFound, {
                    className: 'out',
                    style: 'display: none'
                })
                //Starts & Ends Spinner Animation
                Object.assign(lenderSpinner, {
                    style: 'display: block'
                })
                //Reverts Text
                lenderProcess.innerHTML = 'Attempting to<br>acquire lenders'
                lenderProcessModal.hide();
            }, 1200)
        }

        //Fires On Modal Shown
        lenderModal.addEventListener('show.bs.modal', () => {
            startLenderFound();
            //Fire Off Pushnami
            pushnami();
        })

        const legalModals = qsa('.legal-links a');
        //Legal forEach Of
        for (const legal of legalModals) {
            legal.addEventListener('click', (e) => {
                var legalModal = e.target.dataset.legal
                getInfo(legalModal);
            })
        }

        //Dynamic Legal Switch/Case
        getInfo = (legalModal) => {
            //Legal Modals
            switch (legalModal) {
                case 'terms':
                    var link = '?cmd=Render&tpl=common/legal/terms&renderPath=1'
                    var title = 'Terms & Conditions'
                    break;
                case 'lending':
                    var link = '?cmd=Render&tpl=common/legal/lending-policy&renderPath=1'
                    var title = 'Lending Policy'
                    break;
                case 'dont-sell':
                    var link = '?cmd=Render&tpl=common/legal/privacy-policy&renderPath=1'
                    var title = 'Privacy Policy'
                    break;
                case 'rates':
                    var link = '?cmd=Render&tpl=common/legal/fees&renderPath=1'
                    var title = 'Rates & Fees'
                    break;
                case 'credit-auth':
                    var link = '?cmd=Render&tpl=common/legal/credit-authorization&renderPath=1'
                    var title = 'Credit Authorization'
                    break;
                case 'privacy':
                    var link = '?cmd=Render&tpl=common/legal/privacy-policy&renderPath=1'
                    var title = 'Privacy Policy'
                    break;
                case 'consent':
                    var link = '?cmd=Render&tpl=common/legal/e-consent&renderPath=1'
                    var title = 'E-Consent'
                    break;
                case 'partners':
                    var link = '?cmd=Render&tpl=common/legal/partner-list&renderPath=1'
                    var title = 'Network Partners'
                    break;
                default:
            }

            //Shows Modal Title At All Times
            qs("#legal-modal .modal-title").innerHTML = title;
            //Dynamic Legal Get Request
            qs('#legal-modal').addEventListener('shown.bs.modal', () => {
                axios({
                    method: 'get',
                    url: link
                }).then(response => {
                    qs('#legalLoad').style.display = 'none';
                    qs("#legal-modal .modal-body").innerHTML = response.data;
                    //Scroll To Dont Sell Info
                    if (legalModal === 'dont-sell') {
                        if (response.status = 200) {
                            const scroll = qs('.mailto');
                            //Scroll To Element
                            scroll.parentElement.parentElement.scrollIntoView({
                                behavior: 'smooth',
                                block: 'start',
                                inline: 'nearest'
                            });
                        }
                    }
                })
            }, {once: true});

            //Legal Hidden Loader
            let legalClose = qs('#legal-modal');
            legalClose.addEventListener('hidden.bs.modal', () => {
                qs("#legal-modal .modal-body").innerHTML = '';
                qs("#legal-modal .modal-title").innerHTML = '';
                qs('#legalLoad').style.display = 'block';
            })
        }

        //Scroll To Form
        qsa('button.apply').forEach(elm => {
            elm.addEventListener('click', () => {
                qs('#requestForm').scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                })
            })
        })

        let noSleep = new NoSleep(),
            wakeLockEnabled = false;
        //Submit Form
        submit.addEventListener('click', () => {
            //No Sleep
            if (!wakeLockEnabled) {
                noSleep.enable();
                wakeLockEnabled = true;
            }
            //Sets Validation to True
            let finalSubmitValid = pristine.validate();

            if (finalSubmitValid) {
                progress.style.display = 'none';
                form.style.display = 'none';
                //Text Animation
                proccessingTextAnimation();
                //Submit extapply + action tyoe
                extApply(true, true);
            }
        })

        //Processing Animation
        proccessingTextAnimation = () => {
            qs('.processing-animation').style.display = 'block';
            qs('.processing-animation').classList.remove('animation-pause');
            qs('.processing-txt').style.display = 'block';
            qs('#legalTerms').remove();
            qs('.badge-holder').remove();
            qs('#lenderAlertCount').classList.replace('d-none', 'block')

            // Processing Array of Message to Display
            const messages = [
                "Hang tight, it shouldn't take long!",
                "Still working on it your request.",
                "Checking details...",
                "Processing more offers...",
                "Analyzing data request...",
                "Thank you for continuing to wait.",
                "Your request is important to us.",
                "Evaluating options...",
                "Reviewing info...",
                "Calculating additional offers...",
                "Thank you for your patience.",
                "Just a few more moments.",
                "Checking eligibility...",
                "Your financial freedom is coming.",
                "Evaluating your loan details...",
                "Just a little bit longer.",
                "Calculating more offers...",
                "Evaluating your details...",
                "Crunching numbers to finalize the best results.",
                "Your continued wait is important to us.",
                "Almost at the finish line.",
                "Your application is moving now.",
                "Preparing your offer!",
                // Add more messages as needed
            ];
            let messageIndex = 0;
            // Function to rotate messages every 5 seconds
            function rotateMessages() {
                document.getElementById("processing-messages").textContent = messages[messageIndex];
                messageIndex = (messageIndex + 1) % messages.length;
            }
            // Start rotating messages
            setInterval(rotateMessages, 5000);
            actions.remove();
        }

        var missingFields = sessionStorage.getItem('errorReLoad');

        if (missingFields == "true") {
            alert('There was a problem processing your information, please confirm the following questions.')
            sessionStorage.setItem('errorReLoad', 'false');
        }
    }
);

function createAmt(elm) {

    var val = elm.nextElementSibling.textContent

    // i_ad_amt
    var i_ad_amt = document.getElementsByName("i_ad_amt")[0];

    if (!i_ad_amt) {
        i_ad_amt = document.createElement("input");
        i_ad_amt.type = "hidden";
        i_ad_amt.name = "i_ad_amt";
        i_ad_amt.value = val.trim().replace(/\s+/g, ' ');
        // You can also set other attributes or properties for the element here

        // Append the newly created element to a parent element, e.g., a form
        var parentElement = document.getElementById("requestForm"); // Replace with the actual ID of the parent element
        if (parentElement) {
            // Insert the newly created element at the top of the parent element
            parentElement.insertBefore(i_ad_amt, parentElement.firstChild);
        }
    } else {
        i_ad_amt.value = val.trim().replace(/\s+/g, ' ');
    }
}

function uncheckCheckedRadios() {
    // Get all radio buttons in the specified group
    var radios = document.querySelectorAll('[name=loanreqamt][type=radio]');

    // Loop through the radio buttons
    for (var i = 0; i < radios.length; i++) {
        // Check if the radio button is checked
        if (radios[i].checked) {
            // Uncheck the radio button
            radios[i].checked = false;
        }
    }
}

//Skipped Steps Array
function countSkip(skipStepValue) {

    if (skipStepValue === 'phwrk'){

        let phhmNumber = document.querySelector('[name=phhm]').value;

        function formatPhoneNumber(number) {
            // Remove all non-digit characters from the number
            const cleaned = ('' + number).replace(/\D/g, '');

            // Check if the number is valid
            const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);

            if (match) {
                // If the number is valid, format it
                return '(' + match[1] + ') ' + match[2] + '-' + match[3];
            }
            // If the number is not valid, return null
            return null;
        }

        const formattedNumber = formatPhoneNumber(phhmNumber);

        document.querySelector('[name=phwrk]').value = formattedNumber;
    }

    //Check if the hidden input already exists
    var hiddenInput = document.querySelector('#requestForm input[name="i_ad_skipped_steps"]');

    //Skipped Steps Hidden Input Creation
    if (!hiddenInput) {
        var form = document.getElementById('requestForm');
        if (form) {
            hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'i_ad_skipped_steps';
            form.insertBefore(hiddenInput, form.firstChild);
        } else {
            console.error("Form with ID 'requestForm' not found.");
            return;
        }
    }

    //Convert the value to an array if it's not already
    var skippedSteps = hiddenInput.value ? JSON.parse(hiddenInput.value) : [];

    //Add the new skip step value to the array
    skippedSteps.push(skipStepValue);

    //Update the value of the hidden input
    hiddenInput.value = JSON.stringify(skippedSteps);

    //Trigger the click event on the next button
    var nextBtn = document.getElementById('nextBtn');
    if (nextBtn) {
        nextBtn.click();
    }
}
