function calculateMortgageOffset() {
const loanAmount = parseFloat(document.getElementById(‘loanAmount’).value);
const interestRate = parseFloat(document.getElementById(‘interestRate’).value) / 100;
const loanTerm = parseFloat(document.getElementById(‘loanTerm’).value);
const offsetAmount = parseFloat(document.getElementById(‘offsetAmount’).value);
const extraRepayments = parseFloat(document.getElementById(‘extraRepayments’).value);
if (isNaN(loanAmount) || isNaN(interestRate) || isNaN(loanTerm) || isNaN(offsetAmount) || isNaN(extraRepayments)) {
alert(“Please enter valid positive values for all fields.”);
return;
}
const monthlyInterestRate = interestRate / 12;
const numberOfPayments = loanTerm * 12;
let principalRemaining = loanAmount – offsetAmount;
const monthlyPayment = (principalRemaining * monthlyInterestRate) / (1 – Math.pow(1 + monthlyInterestRate, -numberOfPayments));
let totalPayments = monthlyPayment * numberOfPayments;
const adjustedMonthlyPayment = monthlyPayment + extraRepayments;
const adjustedNumberOfPayments = Math.log(adjustedMonthlyPayment / (adjustedMonthlyPayment – principalRemaining * monthlyInterestRate)) / Math.log(1 + monthlyInterestRate);
const newLoanTerm = adjustedNumberOfPayments / 12;
const totalInterestSaved = totalPayments – (adjustedMonthlyPayment * adjustedNumberOfPayments);
const loanTermSaved = loanTerm – newLoanTerm;
document.getElementById(‘monthlyRepayment’).value = (adjustedMonthlyPayment).toFixed(2);
document.getElementById(‘totalInterestSaved’).value = totalInterestSaved.toFixed(2);
document.getElementById(‘loanTermSaved’).value = loanTermSaved.toFixed(2);
}