const monthsSaved = currentMortgageData.totalMonths – schedule.length;
const yearsSaved = Math.floor(monthsSaved / 12);
const remainingMonths = monthsSaved % 12;
const standardSchedule = calculateAmortizationSchedule(0);
const interestSaved = extra > 0 ? standardSchedule[standardSchedule.length – 1].totalInterest – totalInterest : 0;
const scenarioDiv = document.createElement(‘div’);
scenarioDiv.className = ‘scenario-card’;
scenarioDiv.innerHTML = `
${extra === 0 ? ‘Standard Payment’ : `+€${extra} Extra Monthly`}
${monthsSaved > 0 ? `
` : ”}
${extra > 0 ? `
` : ”}
`;
resultsContainer.appendChild(scenarioDiv);
});
}
// Tab functionality
function showTab(tabName, clickedElement = null) {
// Hide all tab contents
document.querySelectorAll(‘.tab-content’).forEach(content => {
content.classList.remove(‘active’);
});
// Remove active class from all tabs
document.querySelectorAll(‘.tab’).forEach(tab => {
tab.classList.remove(‘active’);
});
// Show selected tab content
document.getElementById(tabName).classList.add(‘active’);
// Add active class to clicked tab
if (clickedElement) {
clickedElement.classList.add(‘active’);
} else {
// Find the appropriate tab button and make it active
const tabs = document.querySelectorAll(‘.tab’);
tabs.forEach(tab => {
if ((tabName === ‘yearly’ && tab.textContent.includes(‘Yearly’)) ||
(tabName === ‘monthly’ && tab.textContent.includes(‘Monthly’)) ||
(tabName === ‘interactive’ && tab.textContent.includes(‘Interactive’)) ||
(tabName === ‘scenarios’ && tab.textContent.includes(‘Scenarios’))) {
tab.classList.add(‘active’);
}
});
}
}
// Format currency for display
function formatCurrency(amount) {
return new Intl.NumberFormat(‘en-US’, {
style: ‘currency’,
currency: ‘EUR’,
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(amount);
}
// Format percentage for display
function formatPercentage(rate) {
return (rate * 100).toFixed(2) + ‘%’;
}
// Lead capture functionality (WordPress integration ready)
function captureLeadData() {
return {
loanAmount: currentMortgageData.loanAmount,
interestRate: parseFloat(document.getElementById(‘interestRate’).value),
loanTerm: parseInt(document.getElementById(‘loanTerm’).value),
extraPayment: parseFloat(document.getElementById(‘extraPayment’).value) || 0,
monthlyPayment: currentMortgageData.monthlyPayment,
totalExtraPayments: calculateWithCustomExtra().totalExtraPayments,
interestSaved: calculateAmortizationSchedule()[calculateAmortizationSchedule().length – 1].totalInterest – calculateWithCustomExtra().totalInterest,
calculatedAt: new Date().toISOString(),
userAgent: navigator.userAgent,
pageUrl: window.location.href
};
}
// WordPress AJAX integration function
function sendLeadToWordPress(emailData) {
if (typeof jQuery !== ‘undefined’) {
jQuery.ajax({
url: ajax_object.ajax_url, // WordPress AJAX URL
type: ‘POST’,
data: {
action: ‘save_mortgage_lead’,
nonce: ajax_object.nonce,
email: emailData.email,
lead_data: JSON.stringify(captureLeadData())
},
success: function(response) {
console.log(‘Lead saved successfully:’, response);
},
error: function(xhr, status, error) {
console.error(‘Error saving lead:’, error);
}
});
}
}
// Export functionality for leads
function exportCalculation() {
const data = captureLeadData();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: ‘application/json’ });
const url = URL.createObjectURL(blob);
const a = document.createElement(‘a’);
a.href = url;
a.download = `mortgage-calculation-${new Date().toISOString().split(‘T’)[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Print functionality
function printCalculation() {
const printContent = document.querySelector(‘.mortgage-calculator’).innerHTML;
const printWindow = window.open(”, ‘_blank’);
printWindow.document.write(`
Mortgage Calculation Report
Generated on: ${new Date().toLocaleDateString()}
${printContent}
`);
printWindow.document.close();
printWindow.print();
}
// Keyboard shortcuts
document.addEventListener(‘keydown’, function(e) {
if (e.ctrlKey || e.metaKey) {
switch(e.key) {
case ‘Enter’:
e.preventDefault();
calculateMortgage();
break;
case ‘r’:
e.preventDefault();
resetAllExtra();
break;
case ‘e’:
e.preventDefault();
exportCalculation();
break;
case ‘p’:
e.preventDefault();
printCalculation();
break;
}
}
});
// Auto-save functionality for WordPress
function autoSaveCalculation() {
const data = captureLeadData();
localStorage.setItem(‘mortgageCalculation’, JSON.stringify(data));
}
// Load saved calculation
function loadSavedCalculation() {
const saved = localStorage.getItem(‘mortgageCalculation’);
if (saved) {
try {
const data = JSON.parse(saved);
document.getElementById(‘loanAmount’).value = data.loanAmount;
document.getElementById(‘interestRate’).value = data.interestRate;
document.getElementById(‘loanTerm’).value = data.loanTerm;
document.getElementById(‘extraPayment’).value = data.extraPayment;
calculateMortgage();
} catch (e) {
console.log(‘Error loading saved calculation:’, e);
}
}
}
// Initialize auto-save
setInterval(autoSaveCalculation, 30000); // Save every 30 seconds
// Validation functions
function validateInputs() {
const loanAmount = parseFloat(document.getElementById(‘loanAmount’).value);
const interestRate = parseFloat(document.getElementById(‘interestRate’).value);
const loanTerm = parseInt(document.getElementById(‘loanTerm’).value);
if (loanAmount < 50000 || loanAmount > 2000000) {
alert(‘Loan amount must be between €50,000 and €2,000,000’);
return false;
}
if (interestRate < 0.1 || interestRate > 15) {
alert(‘Interest rate must be between 0.1% and 15%’);
return false;
}
if (loanTerm < 1 || loanTerm > 40) {
alert(‘Loan term must be between 1 and 40 years’);
return false;
}
return true;
}
// Add validation to inputs
document.addEventListener(‘DOMContentLoaded’, function() {
const inputs = document.querySelectorAll(‘input[type=”number”]’);
inputs.forEach(input => {
input.addEventListener(‘blur’, validateInputs);
});
// Load any saved calculation on page load
loadSavedCalculation();
});
// Responsive helper functions
function adjustForMobile() {
if (window.innerWidth <= 768) {
// Adjust table for mobile
const tables = document.querySelectorAll('.data-table');
tables.forEach(table => {
table.style.fontSize = ‘0.8em’;
});
}
}
window.addEventListener(‘resize’, adjustForMobile);
document.addEventListener(‘DOMContentLoaded’, adjustForMobile);
// Analytics tracking (ready for Google Analytics integration)
function trackCalculatorUsage(action, value = null) {
// Google Analytics 4 tracking
if (typeof gtag !== ‘undefined’) {
gtag(‘event’, action, {
event_category: ‘Mortgage Calculator’,
event_label: ‘Calculator Usage’,
value: value
});
}
// WordPress/custom analytics
if (typeof jQuery !== ‘undefined’ && typeof ajax_object !== ‘undefined’) {
jQuery.ajax({
url: ajax_object.ajax_url,
type: ‘POST’,
data: {
action: ’track_calculator_usage’,
nonce: ajax_object.nonce,
event: action,
value: value,
timestamp: new Date().toISOString()
}
});
}
}
// Track events
document.getElementById(‘loanAmount’).addEventListener(‘change’, () => trackCalculatorUsage(‘loan_amount_changed’));
document.getElementById(‘interestRate’).addEventListener(‘change’, () => trackCalculatorUsage(‘interest_rate_changed’));
document.getElementById(‘extraPayment’).addEventListener(‘change’, () => trackCalculatorUsage(‘extra_payment_added’));
// Share functionality
function shareCalculation() {
const data = captureLeadData();
const shareText = `Check
🏠 Mortgage Overview & Analysis
Plan your mortgage payments and discover potential savings
Loan Amount
Monthly Payment
Interest Rate
Loan Term
Mortgage Details
Extra Payment Calculator
Yearly Payment Breakdown
| Year | Starting Balance | Principal Paid | Interest Paid | Ending Balance | Cumulative Interest |
|---|
Monthly Payment Schedule (First 24 Months)
| Month | Payment | Principal | Interest | Balance |
|---|
Interactive Month-by-Month Planner
📊 Impact Summary
€0
€0
0 months
–
| Month | Date | Regular Payment | Extra Payment | Total Payment | Principal | Interest | Balance |
|---|
Extra Payment Impact Scenarios
