Please enter valid numbers in all fields.
';
if (dtiChart) dtiChart.destroy();
return;
}
const monthlyIncome = annualIncome / 12;
const maxMonthlyPaymentAllowed = (monthlyIncome * (configData.maxDtiRatio / 100)) - monthlyDebt;
// Estimate PITI from the max payment
const estimatedAnnualTax = (maxMonthlyPaymentAllowed * 12) / (1/ (configData.propertyTaxRate / 100)); // Simplified estimation
const estimatedHomeValueForTaxes = (maxMonthlyPaymentAllowed * 12 * 0.2) / (configData.propertyTaxRate/100);
const annualPropertyTax = estimatedHomeValueForTaxes * (configData.propertyTaxRate / 100);
const annualInsurance = estimatedHomeValueForTaxes * (configData.homeInsuranceRate / 100);
const monthlyTaxesAndInsurance = (annualPropertyTax + annualInsurance) / 12;
const maxPrincipalAndInterest = maxMonthlyPaymentAllowed - monthlyTaxesAndInsurance;
// Calculate loan amount based on max P&I
const monthlyInterestRate = (configData.interestRate / 100) / 12;
const numberOfPayments = loanTermYears * 12;
const loanAmount = maxPrincipalAndInterest * ( (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1) / (monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments)) );
const affordableHomePrice = loanAmount + downPayment;
const estimatedMonthlyMortgage = maxPrincipalAndInterest + monthlyTaxesAndInsurance;
renderResults(affordableHomePrice, estimatedMonthlyMortgage, monthlyIncome, monthlyDebt);
updateChart(monthlyIncome, monthlyDebt, estimatedMonthlyMortgage);
}
function renderResults(price, mortgage, income, debt) {
resultsContent.innerHTML = `
Affordable Home Price
$${price.toLocaleString('en-US', {maximumFractionDigits: 0})}
Estimated Monthly Mortgage
$${mortgage.toLocaleString('en-US', {maximumFractionDigits: 0})}
(Principal, Interest, Taxes & Insurance)
`;
}
function updateChart(monthlyIncome, monthlyDebt, estimatedMortgage) {
const ctx = document.getElementById('dtiChart').getContext('2d');
const totalDebt = monthlyDebt + estimatedMortgage;
const dtiRatio = (totalDebt / monthlyIncome) * 100;
if (dtiChart) {
dtiChart.destroy();
}
dtiChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Mortgage', 'Other Debts', 'Remaining Income'],
datasets: [{
data: [estimatedMortgage, monthlyDebt, monthlyIncome - totalDebt],
backgroundColor: ['#1A237E', '#FFB300', '#CFD8DC'],
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'top' },
title: { display: true, text: `Debt-to-Income (DTI): ${dtiRatio.toFixed(1)}%` }
}
}
});
}
function renderConfig() {
configTbody.innerHTML = `
| Mortgage Interest Rate (%) | |
| Annual Property Tax Rate (%) | |
| Annual Home Insurance Rate (%) | |
| Max Debt-to-Income Ratio (%) | |
`;
}
window.updateConfig = function(element) {
const { prop } = element.dataset;
const value = parseFloat(element.value);
if (isNaN(value)) return;
configData[prop] = value;
calculateEligibility();
}
// --- TAB & NAVIGATION ---
window.openTab = function(evt, tabName) {
const tabContents = document.getElementsByClassName("tab-content");
Array.from(tabContents).forEach(tab => tab.style.display = "none");
const tabButtons = document.getElementsByClassName("tab-btn");
Array.from(tabButtons).forEach(btn => btn.classList.remove("active"));
document.getElementById(tabName).style.display = "block";
if (evt) {
evt.currentTarget.classList.add("active");
} else {
const btnToActivate = Array.from(tabButtons).find(btn => btn.getAttribute('onclick').includes(`'${tabName}'`));
if (btnToActivate) btnToActivate.classList.add("active");
}
updateNavButtons();
}
window.navigateTabs = function(direction) {
const tabs = Array.from(document.querySelectorAll('.tab-btn'));
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'));
let newIndex = (direction === 'next')
? (activeTabIndex + 1) % tabs.length
: (activeTabIndex - 1 + tabs.length) % tabs.length;
tabs[newIndex].click();
}
function updateNavButtons() {
const tabs = Array.from(document.querySelectorAll('.tab-btn'));
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'));
document.getElementById('prev-btn').style.visibility = activeTabIndex === 0 ? 'hidden' : 'visible';
document.getElementById('next-btn').style.visibility = activeTabIndex === tabs.length - 1 ? 'hidden' : 'visible';
}
// --- PDF DOWNLOAD ---
if(downloadPdfBtn) {
downloadPdfBtn.addEventListener('click', function() {
const { jsPDF } = window.jspdf;
const contentToDownload = document.getElementById('results-to-download');
if (!contentToDownload || !document.querySelector('.value')) {
console.warn("Please calculate an estimate before downloading.");
return;
}
const originalButtonText = downloadPdfBtn.innerHTML;
downloadPdfBtn.innerHTML = 'Generating...';
downloadPdfBtn.disabled = true;
html2canvas(contentToDownload, { scale: 2, useCORS: true }).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const imgProps = pdf.getImageProperties(imgData);
const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 10, 10, pdfWidth - 20, imgHeight > 0 ? imgHeight - 20 : 0);
pdf.save('Home-Loan-Eligibility.pdf');
}).catch(err => {
console.error("Error generating PDF:", err);
}).finally(() => {
downloadPdfBtn.innerHTML = originalButtonText;
downloadPdfBtn.disabled = false;
});
});
}
// --- INITIALIZATION ---
function initializeTool() {
calculateEligibility();
renderConfig();
updateNavButtons();
}
initializeTool();
});