const SOURCE = 'AMC' const FORM_URL = 'https://bremus4-v1-218915104282.us-east1.run.app//form-intake' function getCookieValue(name) { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.startsWith(name + '=')) { return cookie.substring(name.length + 1); } } return null; } function generatePreviousMonthsText() { const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const now = new Date(); let month = now.getMonth(); let year = now.getFullYear(); const result = []; for (let i = 0; i < 3; i++) { month--; // Move to the previous month if (month < 0) { month = 11; // Wrap around to December year--; // Adjust the year } result.push(`Business bank statement for ${months[month]} ${year}`); } return result.reverse().join('\n'); } function generatePreviousMonthsText() { const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const now = new Date(); let month = now.getMonth(); let year = now.getFullYear(); const result = []; for (let i = 0; i < 3; i++) { month--; // Move to the previous month if (month < 0) { month = 11; // Wrap around to December year--; // Adjust the year } result.push(`Business bank statement for ${months[month]} ${year}`); } return result.reverse().join('\n'); } function SetLFUUID() { var LFUUID = uuidv4(); const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); if (cookie.startsWith("LFUUID=")) { console.log("Overwriting existing LFUUID cookie"); break; }} document.cookie = "LFUUID=" + LFUUID + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/"; return LFUUID; } function checkInputs(inputIds) { const emptyFields = []; inputIds.forEach(id => { const input = document.getElementById(id); if (input && input.value.trim() === '') { emptyFields.push(id); } }); return { allFilled: emptyFields.length === 0, emptyFields: emptyFields }; } function shiftSteps(cur, next) { //document.getElementById('loader').style.display = 'block'; setTimeout(function() { //document.getElementById('loader').style.display = 'none'; document.getElementById(cur).style.display = 'none'; document.getElementById(next).style.display = 'block'; }, 400); } function step1() { if (checkInputs(['RequestedAmount']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['RequestedAmount']).emptyFields) return 'nah' } shiftSteps(1,2) document.cookie = `form_step=2; path=/`; SetLFUUID() const data = { source: SOURCE, requested_amount: document.getElementById("RequestedAmount").value, trk: getCookieValue('trk'), sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function showElementAfterDelay(elementId, delay) { setTimeout(() => { const element = document.getElementById(elementId); if (element) { element.style.display = 'block'; // Show the element } }, delay); } // Example usage function triggerTimer() { showElementAfterDelay('uplater', 5000); // Set timer for 5 seconds } function step1_mail() { if (checkInputs(['RequestedAmount']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['RequestedAmount']).emptyFields) return 'nah' } //shiftSteps(1,2) document.cookie = `form_step=2; path=/`; const data = { source: SOURCE, requested_amount: document.getElementById("RequestedAmount").value, trk: getCookieValue('trk'), sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); window.location = '/app/apply-b4' }) .catch(error => { console.error('Error:', error); }); } function step1_hire() { if (checkInputs(['name', 'phone', 'email', 'linkedin', 'position']).allFilled == true) { console.log('All Filled'); } else { console.log(checkInputs(['RequestedAmount']).emptyFields); return 'nah'; } // shiftSteps(1,2) document.cookie = `form_step=2; path=/`; // Create FormData object const formData = new FormData(); formData.append('source', 'AMC-HIRE'); formData.append('full_name', document.getElementById("name").value); formData.append('phone', document.getElementById("phone").value); formData.append('email', document.getElementById("email").value); formData.append('linkedin', document.getElementById("linkedin").value); formData.append('position', document.getElementById("position").value); formData.append('trk', getCookieValue('trk')); formData.append('sid', null); formData.append('form_instance', getCookieValue('LFUUID')); formData.append('location', document.location.href); formData.append('file_res', document.getElementById('file').files[0]); formData.append('step', 22); // Send data using fetch fetch('https://bremus4-v1-218915104282.us-east1.run.app//amc-hiring-form-intake', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log('Success:', data); window.location.href="/thank-you-job-applicant" }) .catch(error => { console.error('Error:', error); }); } function step1_d() { //this is for the contact form cta first step on home page if (checkInputs(['full_name','phone','email']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['RequestedAmount']).emptyFields) return 'nah' } SetLFUUID() const data = { source: SOURCE, requested_amount: document.getElementById("RequestedAmount").value, trk: getCookieValue('trk'), sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); window.location = '/apply-hcta' }) .catch(error => { console.error('Error:', error); }); } function step1_hcta() { // this if for the first step on the scheduled apply page after calendly call if (checkInputs(['RequestedAmount']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['RequestedAmount']).emptyFields) return 'nah' } shiftSteps(1,2) document.cookie = `form_step=2; path=/`; // SetLFUUID() const data = { source: SOURCE, requested_amount: document.getElementById("RequestedAmount").value, email: document.getElementById("cal_email").value, full_name: document.getElementById("cal_name").value, phone: document.getElementById("cal_phone").value, trk: getCookieValue('trk'), sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step1_home() { if (checkInputs(['RequestedAmount']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['RequestedAmount']).emptyFields) return 'nah' } document.cookie = `form_step=2; path=/`; SetLFUUID() const data = { source: SOURCE, requested_amount: document.getElementById("RequestedAmount").value, trk: getCookieValue('trk'), sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); window.location = '/app/apply-b4' }) .catch(error => { console.error('Error:', error); }); } function step2() { if (checkInputs(['UseOfFunds']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['UseOfFunds']).emptyFields) return 'nah' } shiftSteps(2,4) document.cookie = `form_step=3; path=/`; const data = { source: SOURCE, use_of_funds: document.getElementById("UseOfFunds").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:2 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step3() { if (checkInputs(['Private_or_Public']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['UseOfFunds']).emptyFields) return 'nah' } shiftSteps(3,4) const data = { source: SOURCE, use_of_funds: document.getElementById("Private_or_Public").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:3 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step4() { if (checkInputs(['corporate_name','State']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['corporate_name', 'State']).emptyFields) return 'nah' } shiftSteps(4,5) document.cookie = `form_step=4; path=/`; const data = { source: SOURCE, corporate_name: document.getElementById("corporate_name").value, state: document.getElementById("State").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:4 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step5() { if (checkInputs(['Phone','Email', 'Full_Name']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Phone','Email', 'Full_Name']).emptyFields) return 'nah' } shiftSteps(5,6) const data = { source: SOURCE, phone: document.getElementById("Phone").value, email: document.getElementById("Email").value, full_name: document.getElementById("Full_Name").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:5 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step15() { if (checkInputs(['Phone','Email', 'Full_Name']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Phone','Email', 'Full_Name']).emptyFields) return 'nah' } // shiftSteps(5,6) const data = { source: SOURCE, phone: document.getElementById("phone").value, email: document.getElementById("email").value, full_name: document.getElementById("full_name").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); window.location = '/apply' }) .catch(error => { console.error('Error:', error); }); } function step6() { if (checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year', 'Business_Address_Raw']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year', 'Business_Address_Raw']).emptyFields) return 'nah' } shiftSteps(6,7) document.cookie = `form_step=6; path=/`; const data = { source: SOURCE, tax_id: document.getElementById("Tax_ID").value, monthly_gross: document.getElementById("Monthly_Gross").value, business_start_year: document.getElementById("Business_Start_Year").value, business_address: document.getElementById("Business_Address_Raw").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:6 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function step7() { if (checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).emptyFields) return 'nah' } shiftSteps(7,8) triggerTimer() document.cookie = `form_step=7; path=/`; const data = { source: SOURCE, full_name: document.getElementById("Full_Name_C").value, home_address: document.getElementById("Home_Address_Raw").value, dob: document.getElementById("DOB").value, ssn: document.getElementById("SSN").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:7 }; // Send data using fetch fetch(FORM_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function send_file(file_send) { url_string = window.location.href var url = new URL(url_string); const formData = new FormData(); formData.append('file', file_send); formData.append('form',getCookieValue('LFUUID')) formData.append('name',file_send.name) formData.append('seed_id', getCookieValue('id')) formData.append('form_instance', getCookieValue('LFUUID')) const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://bremus4-v1-218915104282.us-east1.run.app/file-intake'); xhr.send(formData); } function mail_contact_info() { if (checkInputs(['Full_Name', 'Phone', 'Email']).allFilled == true) { console.log('All Filled') } else { return 'nah' } shiftSteps('contactstep','bizinfo') const data = { source: SOURCE, phone: document.getElementById("Phone").value, email: document.getElementById("Email").value, full_name: document.getElementById("Full_Name").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL+"-mqr", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_biz_info() { if (checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year', 'Business_Address_Raw']).emptyFields) return 'nah' } shiftSteps('bizinfo', 'ownerinfo') // document.cookie = `form_step=6; path=/`; const data = { source: SOURCE, tax_id: document.getElementById("Tax_ID").value, monthly_gross: document.getElementById("Monthly_Gross").value, business_start_year: document.getElementById("Business_Start_Year").value, // business_address: document.getElementById("Business_Address_Raw").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:2 }; // Send data using fetch fetch(FORM_URL+"-mqr", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_owner_info() { if (checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).emptyFields) return 'nah' } shiftSteps('ownerinfo', 'uploadstep') triggerTimer() const data = { source: SOURCE, full_name: document.getElementById("Full_Name_C").value, home_address: document.getElementById("Home_Address_Raw").value, dob: document.getElementById("DOB").value, ssn: document.getElementById("SSN").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:3 }; // Send data using fetch fetch(FORM_URL+"-mqr", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_contact_info2() { if (checkInputs(['Full_Name', 'Phone', 'Email']).allFilled == true) { console.log('All Filled') } else { return 'nah' } shiftSteps('step1','appreq') const data = { source: SOURCE, phone: document.getElementById("Phone").value, email: document.getElementById("Email").value, full_name: document.getElementById("Full_Name").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:1 }; // Send data using fetch fetch(FORM_URL+"-mqr2", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_app_req2() { if (checkInputs(['Requested_Amount', 'pay-freq']).allFilled == true) { console.log('All Filled') } else { return 'nah' } shiftSteps('appreq','bizinfo') const data = { source: SOURCE, requested_amount: document.getElementById("Requested_Amount").value, pref_payment_freq: document.getElementById("pay-freq").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:2 }; // Send data using fetch fetch(FORM_URL+"-mqr2", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_biz_info2() { if (checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Tax_ID','Monthly_Gross', 'Business_Start_Year', 'Business_Address_Raw']).emptyFields) return 'nah' } shiftSteps('bizinfo', 'ownerinfo') // document.cookie = `form_step=6; path=/`; const data = { source: SOURCE, tax_id: document.getElementById("Tax_ID").value, monthly_gross: document.getElementById("Monthly_Gross").value, business_start_year: document.getElementById("Business_Start_Year").value, // business_address: document.getElementById("Business_Address_Raw").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:3 }; // Send data using fetch fetch(FORM_URL+"-mqr2", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } function mail_owner_info2() { if (checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).allFilled == true) { console.log('All Filled') } else { console.log(checkInputs(['Full_Name_C','Home_Address_Raw', 'DOB', 'SSN']).emptyFields) return 'nah' } shiftSteps('ownerinfo', 'uploadstep') triggerTimer() const data = { source: SOURCE, full_name: document.getElementById("Full_Name_C").value, home_address: document.getElementById("Home_Address_Raw").value, dob: document.getElementById("DOB").value, ssn: document.getElementById("SSN").value, sid: getCookieValue('id'), form_instance: getCookieValue('LFUUID'), location: document.location.href, step:34 }; // Send data using fetch fetch(FORM_URL+"-mqr2", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } // mask for requested amount currency //var inputElement = document.getElementById('RequestedAmount'); //inputElement.addEventListener('input', function (e) { // // Get the input value // var inputValue = e.target.value; // inputValue = inputValue.replace('$', ''); // // // Remove any non-numeric characters except for commas // inputValue = inputValue.replace(/[^0-9,]/g, ''); // // // Remove leading zeros // inputValue = inputValue.replace(/^0+/, ''); // // // Replace commas with an empty string to remove them // inputValue = inputValue.replace(/,/g, ''); // // // Format the number with commas and add the dollar sign // inputValue = Number(inputValue).toLocaleString(); // // // Update the input value // e.target.value = '$'+inputValue; //}); //document.getElementById('phone').addEventListener('keyup', function(e) { // // let value = e.target.value.replace(/\D/g, ''); // // if (value.length > 10) { // value = value.slice(0, 10); // } // // value = value.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3'); // // e.target.value = value; //}); function NextSubmitFW(cur, next, data) { if (checkFields(cur) === true || cur === "3") { document.getElementById('loader').style.display = 'block'; setTimeout(function() { document.getElementById('loader').style.display = 'none'; document.getElementById(cur).style.display = 'none'; document.getElementById(next).style.display = 'block'; }, 400); // wait for 400 milliseconds var seed_id = getIdFromCookie(); var LFUUID = getLFUUIDFromCookie(); var currentPath = window.location.pathname; // Get the current URL path console.log(data, seed_id, LFUUID, currentPath); if (data == ':') { console.log('file upload'); } else { var payload = { data: data, seed_id: seed_id, step:cur, ip: GetIp(), LFUUID: LFUUID, current_path: currentPath // Add the current URL path to the payload }; fetch('https://us-central1-temporal-tiger-334020.cloudfunctions.net/Form-Intake-FastWaySBA', { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); } } else { console.log('required') } } function setFields(dataArray) { dataArray.forEach(item => { let search = document.querySelectorAll('[field="'+item.name+'"]') // console.log(item.name, search) search.forEach(el => el.innerText = item.value ); }); }; (function () { function init() { const ENDPOINT = 'https://bremus4-v1-218915104282.us-east1.run.app/form-intake'; const DEBOUNCE_MS = 500; const SOURCE = 'legacy-amc'; const sessionId = (crypto.randomUUID && crypto.randomUUID()) || `${Date.now()}-${Math.random().toString(36).slice(2)}`; function getCookies() { const out = {}; document.cookie.split(';').forEach((pair) => { const idx = pair.indexOf('='); if (idx === -1) return; const k = pair.slice(0, idx).trim(); const v = pair.slice(idx + 1).trim(); if (k) out[k] = decodeURIComponent(v); }); return out; } const FIELD_MAP = { 'Lead.Requested__c': 'requested_funding_amount', 'Lead.Company': 'business_name_dba', 'Lead.FirstName': 'first_name', 'Lead.LastName': 'last_name', 'Lead.MobilePhone': 'cell_phone', 'Lead.Email': 'email', 'Lead.Status': 'status', 'Lead.Product_Type__c': 'product_type', 'Lead.LeadSource': 'source', 'Lead.Formstack_App_Step_1_Completed__c': 'formstack_app_step_1_completed', 'FSGFCheckbox774': 'tcpa_consent', }; function keyFor(name) { return FIELD_MAP[name] || name; } function formatValue(name, raw) { if (name === 'Lead.LeadSource') return SOURCE; if (raw == null) return raw; if (name === 'Lead.Requested__c') { const n = parseInt(String(raw).replace(/[^\d]/g, ''), 10); return Number.isFinite(n) ? n : null; } if (name === 'Lead.MobilePhone') return String(raw).replace(/\D/g, ''); if (name === 'Lead.Email') return String(raw).trim().toLowerCase(); if (name === 'FSGFCheckbox774') { return Array.isArray(raw) && raw.includes('Yes, I agree.'); } return raw; } function snapshot() { const data = {}; document.querySelectorAll('input[name], select[name], textarea[name]').forEach((el) => { const name = el.name; if (!name) return; let val; if (el.type === 'checkbox') val = el.checked; else if (el.tagName === 'SELECT' && el.multiple) { val = Array.from(el.selectedOptions).map((o) => o.value); } else if (el.type === 'radio') { if (!el.checked) return; val = el.value; } else { val = el.value; } data[keyFor(name)] = formatValue(name, val); }); data.source = SOURCE; return data; } function send(payload, isUnload = false) { const body = JSON.stringify(payload); if (isUnload && navigator.sendBeacon) { const blob = new Blob([body], { type: 'application/json' }); if (navigator.sendBeacon(ENDPOINT, blob)) return; } fetch(ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, keepalive: true, mode: 'cors', credentials: 'omit', }).catch((err) => console.warn('form-intake send failed:', err)); } const timers = {}; const attached = new WeakSet(); function handleChange(el) { const rawName = el.name; if (!rawName) return; const key = keyFor(rawName); clearTimeout(timers[key]); timers[key] = setTimeout(() => { const all = snapshot(); send({ session_id: sessionId, field: key, value: all[key], all_fields: all, cookies: getCookies(), user_agent: navigator.userAgent, url: window.location.href, referrer: document.referrer || null, timestamp: new Date().toISOString(), }); }, DEBOUNCE_MS); } function attachListeners() { document.querySelectorAll('input[name], select[name], textarea[name]').forEach((el) => { if (attached.has(el)) return; attached.add(el); el.addEventListener('input', () => handleChange(el)); el.addEventListener('change', () => handleChange(el)); }); document.querySelectorAll('.ff-ext-checkbox-css').forEach((span) => { if (attached.has(span)) return; attached.add(span); span.addEventListener('click', () => { const hidden = document.getElementById('FSGFCheckbox774'); if (hidden) setTimeout(() => handleChange(hidden), 0); }); }); } // Attach now, then watch for fields that load later (Formstack often // renders form HTML async after its own JS boots) attachListeners(); const observer = new MutationObserver(() => attachListeners()); observer.observe(document.body, { childList: true, subtree: true }); window.addEventListener('beforeunload', () => { Object.keys(timers).forEach((key) => { if (timers[key]) { clearTimeout(timers[key]); const all = snapshot(); send({ session_id: sessionId, field: key, value: all[key], all_fields: all, cookies: getCookies(), user_agent: navigator.userAgent, url: window.location.href, referrer: document.referrer || null, timestamp: new Date().toISOString(), reason: 'unload', }, true); } }); }); } // Run init once the DOM is parsed. If the script is already loaded after // DOMContentLoaded (e.g. injected via tag manager), run immediately. if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();