// CONFIG: Zapier Catch Hook URLs
const STEP1_ENDPOINT = "https://hooks.zapier.com/hooks/catch/20342722/ugl5gad/";
const STEP5_ENDPOINT = "https://hooks.zapier.com/hooks/catch/20342722/ug0kc0i/";
// 🔑 ONE unique ID per application
const SUBMISSION_ID = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
// Store Step 1 data (keep for Step 5)
const step1Data = { submissionId: SUBMISSION_ID };
/* -----------------------------
PROGRESS BAR
------------------------------ */
function updateProgress(stepNumber) {
const totalSteps = 5;
const indicator = document.getElementById("progressText");
const fill = document.getElementById("progressFill");
if (indicator) indicator.textContent = `Step ${stepNumber} of ${totalSteps}`;
if (fill) fill.style.width = (stepNumber / totalSteps) * 100 + "%";
}
/* -----------------------------
STEP DISPLAY
------------------------------ */
function showStep(stepNumber) {
document.querySelectorAll(".form-step").forEach(step => {
step.style.display = step.dataset.step === String(stepNumber) ? "block" : "none";
});
updateProgress(stepNumber);
}
/* -----------------------------
VALIDATION FOR EACH STEP
------------------------------ */
function validateStep(stepNumber) {
const step = document.querySelector(`.form-step[data-step="${stepNumber}"]`);
if (!step) return true;
const requiredFields = step.querySelectorAll("[required]");
for (const field of requiredFields) {
if (!field.value || field.value.trim() === "") {
field.focus();
alert("Please complete all required fields on this step.");
return false;
}
}
return true;
}
/* -----------------------------
STATE → COUNTY LOADER (RESTORED)
------------------------------ */
function initStateCountyLoader() {
const stateSelect = document.getElementById("stateFiling");
const countySelect = document.getElementById("countyFiling");
const countyRow = document.getElementById("countyRow");
if (!stateSelect || !countySelect || !countyRow) {
console.log("State/county elements not found.");
return;
}
stateSelect.addEventListener("change", async function () {
const state = (this.value || "").trim().toUpperCase();
countySelect.innerHTML = ``;
countyRow.style.display = "none";
if (!state) return;
const url = `https://irp.cdn-website.com/1a363b46/files/uploaded/${state}.txt?cb=${Date.now()}`;
console.log("Fetching county file:", url);
try {
const response = await fetch(url, { cache: "no-cache" });
if (!response.ok) {
console.error("County file fetch failed:", response.status, response.statusText);
countySelect.innerHTML = ``;
countyRow.style.display = "block";
return;
}
let text = await response.text();
text = text.replace(/^\uFEFF/, "");
const counties = text
.split(/\r?\n/)
.map(c => c.trim())
.filter(c => c.length > 0);
if (counties.length === 0) {
countySelect.innerHTML = ``;
countyRow.style.display = "block";
return;
}
countySelect.innerHTML = ``;
counties.forEach(county => {
const opt = document.createElement("option");
opt.value = county;
opt.textContent = county;
countySelect.appendChild(opt);
});
countyRow.style.display = "block";
} catch (err) {
console.error("Error loading counties:", err);
countySelect.innerHTML = ``;
countyRow.style.display = "block";
}
});
}
/* -----------------------------
MONEY INPUT FIX (ONLY 2 FIELDS)
- courtOrderAmount
- courtOrderChangedAmount
------------------------------ */
function sanitizeWholeDollars(raw) {
if (!raw) return "";
// remove everything except digits
const digits = String(raw).replace(/[^\d]/g, "");
if (!digits) return "";
const intVal = parseInt(digits, 10);
if (!Number.isFinite(intVal) || intVal < 0) return "";
return String(intVal);
}
function formatUSDWhole(intString) {
if (!intString) return "";
const n = parseInt(intString, 10);
if (!Number.isFinite(n)) return "";
return "$" + n.toLocaleString("en-US", { maximumFractionDigits: 0 });
}
function attachWholeDollarBehavior(inputId) {
const el = document.getElementById(inputId);
if (!el) return;
// reduce decimal stepping / enforce whole dollars behavior
el.setAttribute("step", "1");
el.setAttribute("min", "0");
el.setAttribute("inputmode", "numeric");
// While typing: digits only
el.addEventListener("input", function () {
const cleaned = sanitizeWholeDollars(this.value);
this.value = cleaned ? cleaned : "";
});
// On blur: format as $X,XXX
el.addEventListener("blur", function () {
const cleaned = sanitizeWholeDollars(this.value);
this.value = cleaned ? formatUSDWhole(cleaned) : "";
});
}
function initMoneyInputFixes() {
attachWholeDollarBehavior("courtOrderAmount");
attachWholeDollarBehavior("courtOrderChangedAmount");
}
/* -----------------------------
MULTI-STEP LOGIC
------------------------------ */
function initMultiStepForm() {
showStep(1);
const step1Next = document.getElementById("step1Next");
if (step1Next) {
step1Next.addEventListener("click", function (e) {
e.preventDefault();
if (!validateStep(1)) return;
const firstName = document.getElementById("applicantFirstName")?.value || "";
const lastName = document.getElementById("applicantLastName")?.value || "";
const email = document.getElementById("email")?.value || "";
const phone = document.getElementById("phone")?.value || "";
const street = document.getElementById("street")?.value || "";
const city = document.getElementById("city")?.value || "";
const state = document.getElementById("state")?.value || "";
const zip = document.getElementById("zip")?.value || "";
// store for step 5
step1Data.firstName = firstName;
step1Data.lastName = lastName;
step1Data.email = email;
step1Data.phone = phone;
step1Data.street = street;
step1Data.city = city;
step1Data.state = state;
step1Data.zip = zip;
// send step 1 (FormData so Zapier captures fields)
const fd = new FormData();
fd.append("SUBMISSION_ID", SUBMISSION_ID);
fd.append("FIRST_NAME", firstName);
fd.append("LAST_NAME", lastName);
fd.append("EMAIL", email);
fd.append("TEXT", phone);
fd.append("STREET", street);
fd.append("CITY", city);
fd.append("STATE", state);
fd.append("ZIP", zip);
fetch(STEP1_ENDPOINT, { method: "POST", body: fd, keepalive: true });
showStep(2);
});
}
document.querySelectorAll(".nextBtn").forEach(btn => {
btn.addEventListener("click", function () {
const next = this.dataset.next;
const current = parseInt(this.closest(".form-step").dataset.step, 10);
if (validateStep(current)) showStep(next);
});
});
document.querySelectorAll(".prevBtn").forEach(btn => {
btn.addEventListener("click", function () {
showStep(this.dataset.prev);
});
});
/* -----------------------------
FINAL SUBMISSION — STEP 5
------------------------------ */
const finalSubmit = document.getElementById("finalSubmit");
if (finalSubmit) {
finalSubmit.addEventListener("click", function () {
if (!validateStep(5)) return;
// STEP 1 values (from memory as primary)
const applicantFirstName = step1Data.firstName || document.getElementById("applicantFirstName")?.value || "";
const applicantLastName = step1Data.lastName || document.getElementById("applicantLastName")?.value || "";
const applicantEmail = step1Data.email || document.getElementById("email")?.value || "";
const applicantPhone = step1Data.phone || document.getElementById("phone")?.value || "";
const applicantStreet = step1Data.street || document.getElementById("street")?.value || "";
const applicantCity = step1Data.city || document.getElementById("city")?.value || "";
const applicantState = step1Data.state || document.getElementById("state")?.value || "";
const applicantZip = step1Data.zip || document.getElementById("zip")?.value || "";
// STEP 2 — CASE DETAILS
const causeNumber = document.getElementById("causeNumber")?.value || "";
const stateFiling = document.getElementById("stateFiling")?.value || "";
const countyFiling = document.getElementById("countyFiling")?.value || "";
const opposingName = document.getElementById("opposingName")?.value || "";
const children = document.getElementById("children")?.value || "";
const priorName = document.getElementById("priorName")?.value || "";
const publicAssistance = document.getElementById("publicAssistance")?.value || "";
const courtOrderDate = document.getElementById("courtOrderDate")?.value || "";
// ✅ ONLY money fields adjusted (normalize + whole-dollar USD formatting)
const courtOrderAmountRaw = document.getElementById("courtOrderAmount")?.value || "";
const courtOrderChanged = document.getElementById("courtOrderChanged")?.value || "";
const courtOrderChangedAmountRaw = document.getElementById("courtOrderChangedAmount")?.value || "";
const courtOrderAmount = formatUSDWhole(sanitizeWholeDollars(courtOrderAmountRaw));
const courtOrderChangedAmount = formatUSDWhole(sanitizeWholeDollars(courtOrderChangedAmountRaw));
const courtOrderUpload = document.getElementById("courtOrderUpload")?.value || "";
// STEP 3 — OBLIGOR INFO
const obligorFirstName = document.getElementById("obligorFirstName")?.value || "";
const obligorLastName = document.getElementById("obligorLastName")?.value || "";
const obligorDOB = document.getElementById("obligorDOB")?.value || "";
const obligorSSN = document.getElementById("obligorSSN")?.value || "";
const obligorStreet = document.getElementById("obligorStreet")?.value || "";
const obligorCity = document.getElementById("obligorCity")?.value || "";
const obligorState = document.getElementById("obligorState")?.value || "";
const obligorZip = document.getElementById("obligorZip")?.value || "";
const obligorRemarried = document.getElementById("obligorRemarried")?.value || "";
const obligorLumpSum = document.getElementById("obligorLumpSum")?.value || "";
const obligorFacebook = document.getElementById("obligorFacebook")?.value || "";
const obligorTwitter = document.getElementById("obligorTwitter")?.value || "";
const obligorLinkedIn = document.getElementById("obligorLinkedIn")?.value || "";
// STEP 4 — DYNAMIC CHILDREN
const childNameInputs = document.querySelectorAll("[name$='Name']");
const childDOBInputs = document.querySelectorAll("[name$='DOB']");
const childNames = Array.from(childNameInputs).map(i => i.value.trim()).filter(v => v).join(", ");
const childDOBs = Array.from(childDOBInputs).map(i => i.value.trim()).filter(v => v).join(", ");
// STEP 5 — PERMISSION
const contactPermission = document.getElementById("contactPermission")?.value || "";
// Send Step 5 via FormData (Zapier friendly)
const fd5 = new FormData();
fd5.append("SUBMISSION_ID", SUBMISSION_ID);
fd5.append("CASE #", causeNumber);
fd5.append("STATE OF FILING", stateFiling);
fd5.append("COUNTY", countyFiling);
fd5.append("Opposing Party Name", opposingName);
fd5.append("Are there minor children", children);
fd5.append("Prior Name", priorName);
fd5.append("Public Assistance", publicAssistance);
fd5.append("COURT ORDER DATE", courtOrderDate);
fd5.append("COURT ORDER $", courtOrderAmount);
fd5.append("COURT ORDER CHANGED", courtOrderChanged);
fd5.append("Amount Court Order Changed to", courtOrderChangedAmount);
/* ✅✅✅ ONLY CHANGE FOR REAL FILE UPLOADS (DOCS RECEIVED) ✅✅✅ */
const fileInput = document.getElementById("courtOrderUpload");
if (fileInput && fileInput.files && fileInput.files.length) {
// send actual file bytes so Zapier can upload to Drive
Array.from(fileInput.files).forEach(f => fd5.append("DOCS RECEIVED", f));
} else {
// keep old behavior if no file selected
fd5.append("DOCS RECEIVED", "");
}
/* ✅✅✅ END ONLY CHANGE ✅✅✅ */
fd5.append("Children Names (comma seperated)", childNames);
fd5.append("CHILDREN DOB Comma Seperated", childDOBs);
fd5.append("obligors name", `${obligorFirstName} ${obligorLastName}`.trim());
fd5.append("obligors dob", obligorDOB);
fd5.append("obligors social", obligorSSN);
fd5.append("Obligor Remarried", obligorRemarried);
fd5.append("obligors street address", obligorStreet);
fd5.append("obligors city", obligorCity);
fd5.append("obligors state", obligorState);
fd5.append("obligors zip", obligorZip);
fd5.append("Obligor Received Lump Sum", obligorLumpSum);
fd5.append("obligorsfb", obligorFacebook);
fd5.append("obligorstwitter", obligorTwitter);
fd5.append("Obligors Linkedin", obligorLinkedIn);
// Step 1 fields again (so Step 5 has everything + can match by SUBMISSION_ID in Zap)
fd5.append("FIRST_NAME", applicantFirstName);
fd5.append("LAST_NAME", applicantLastName);
fd5.append("EMAIL", applicantEmail);
fd5.append("TEXT", applicantPhone);
fd5.append("STREET", applicantStreet);
fd5.append("CITY", applicantCity);
fd5.append("STATE", applicantState);
fd5.append("ZIP", applicantZip);
fd5.append("Permission", contactPermission);
fetch(STEP5_ENDPOINT, { method: "POST", body: fd5, keepalive: true });
// ✅ Redirect to arrears calculator with prefilled values
const arrearsUrl =
"https://www.childsupport2collect.com/arrears-calculator" +
`?case=${encodeURIComponent(causeNumber)}` +
`&monthly=${encodeURIComponent(courtOrderAmount)}` +
`&modified=${encodeURIComponent(courtOrderChanged)}` +
`&modifiedAmount=${encodeURIComponent(courtOrderChangedAmount)}` +
`&orderDate=${encodeURIComponent(courtOrderDate)}`;
window.location.href = arrearsUrl;
alert("Application submitted successfully.");
});
}
}
/* -----------------------------
CHILDREN + LUMP SUM LOGIC (RESTORED)
------------------------------ */
function initDynamicFields() {
let childCount = 0;
const maxChildren = 10;
const addChildBtn = document.getElementById("addChildBtn");
const childrenContainer = document.getElementById("childrenContainer");
if (addChildBtn && childrenContainer) {
addChildBtn.addEventListener("click", function () {
if (childCount >= maxChildren) return;
childCount++;
const block = document.createElement("div");
block.className = "child-block";
block.innerHTML = `
Child ${childCount}
`;
childrenContainer.appendChild(block);
});
}
const lumpSumSelect = document.getElementById("obligorLumpSum");
const lumpSumContainer = document.getElementById("lumpSumExplainContainer");
if (lumpSumSelect && lumpSumContainer) {
lumpSumSelect.addEventListener("change", function () {
lumpSumContainer.innerHTML = "";
if (this.value === "yes") {
const row = document.createElement("div");
row.className = "form-row";
row.innerHTML = `
`;
lumpSumContainer.appendChild(row);
}
});
}
// Court Order Changed Logic (restored)
const courtOrderChanged = document.getElementById("courtOrderChanged");
const changedAmountRow = document.getElementById("courtOrderChangedAmountRow");
const changedAmountInput = document.getElementById("courtOrderChangedAmount");
if (courtOrderChanged && changedAmountRow && changedAmountInput) {
courtOrderChanged.addEventListener("change", function () {
if (this.value === "yes") {
changedAmountRow.style.display = "block";
changedAmountInput.setAttribute("required", "required");
} else {
changedAmountRow.style.display = "none";
changedAmountInput.removeAttribute("required");
changedAmountInput.value = "";
}
});
}
}
/* -----------------------------
DUDA-SAFE BOOTSTRAP (RESTORED)
------------------------------ */
function bootFormLogic() {
const step1Next = document.getElementById("step1Next");
if (!step1Next) {
setTimeout(bootFormLogic, 400);
return;
}
initMultiStepForm();
initDynamicFields();
initStateCountyLoader();
initMoneyInputFixes(); // ✅ ONLY initializes the two money input fixes
}
bootFormLogic();