-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1641 lines (1431 loc) · 89.1 KB
/
Copy pathindex.html
File metadata and controls
1641 lines (1431 loc) · 89.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smart Mortgage Prepayment Calculator</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='0.9em' font-size='90'>🏠</text></svg>">
<style>
.gradient-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.loading-spinner {
border: 3px solid #f3f4f6;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.camera-input {
display: none;
}
</style>
</head>
<body class="bg-gray-50 text-gray-900">
<div class="min-h-screen">
<!-- Header -->
<header class="gradient-bg text-white py-8 shadow-lg">
<div class="container mx-auto px-4">
<h1 class="text-4xl font-bold mb-2 flex items-center gap-3">
<span>🏠</span>
<span>Mortgage Prepayment Calculator</span>
</h1>
<p class="text-purple-100">Calculate when your loan will be paid off and how much interest you'll save</p>
</div>
</header>
<div class="container mx-auto px-4 py-8 max-w-6xl">
<!-- Manual Input Section - Primary Focus -->
<div class="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 class="text-2xl font-bold mb-4">📊 Enter Loan Information</h2>
<div class="space-y-6">
<!-- Basic Loan Information Section -->
<div>
<h4 class="font-semibold text-gray-700 mb-3 text-lg">1. Basic Loan Information *</h4>
<div class="grid md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Current Principal Balance *</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" id="principal" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 244553" value="" required>
</div>
<p class="text-xs text-gray-500 mt-1">Current amount you owe</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Interest Rate (Annual) *</label>
<div class="relative">
<input type="number" step="0.01" id="rate" class="w-full pr-10 pl-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 3.875" value="" required>
<span class="absolute right-3 top-3 text-gray-500">%</span>
</div>
<p class="text-xs text-gray-500 mt-1">Annual interest rate</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Remaining Term (Years) *</label>
<input type="number" id="years" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 15" value="" required>
<p class="text-xs text-gray-500 mt-1">Years remaining on loan</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Monthly Escrow (Optional)</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" id="escrow" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 500" value="0">
</div>
<p class="text-xs text-gray-500 mt-1">Taxes & insurance (doesn't affect payoff)</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Current Statement Date *</label>
<input type="date" id="statement-date" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" value="" required>
<p class="text-xs text-gray-500 mt-1">Date of your current mortgage statement (used as reference date)</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Loan Start Date (Optional)</label>
<input type="date" id="loan-start-date" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" value="">
<p class="text-xs text-gray-500 mt-1">When the loan was originally started</p>
</div>
</div>
</div>
<!-- Current Payment Information Section -->
<div>
<h4 class="font-semibold text-gray-700 mb-3 text-lg">2. Current Payment Information (Optional)</h4>
<p class="text-sm text-gray-600 mb-3">Enter your current monthly payment breakdown to help calculate more accurately</p>
<div class="grid md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Principal Portion This Month</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" step="0.01" id="current-principal" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 1572.85" value="">
</div>
<p class="text-xs text-gray-500 mt-1">From your latest statement</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Interest Portion This Month</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" step="0.01" id="current-interest" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. 794.78" value="">
</div>
<p class="text-xs text-gray-500 mt-1">From your latest statement</p>
</div>
</div>
</div>
<!-- Additional Principal Payments Section -->
<div>
<h4 class="font-semibold text-gray-700 mb-3 text-lg">3. Additional Principal Payments</h4>
<p class="text-sm text-gray-600 mb-3">Enter any extra principal payments you plan to make (leave as 0 if none)</p>
<div class="grid md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Additional Monthly Principal Payment</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" id="extra" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="0" value="0">
</div>
<p class="text-xs text-gray-500 mt-1">Extra principal you'll pay each month</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">One-Time Lump Sum Payment</label>
<div class="relative">
<span class="absolute left-3 top-3 text-gray-500">$</span>
<input type="number" id="lumpsum" class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="0" value="0">
</div>
<p class="text-xs text-gray-500 mt-1">One-time extra payment (applied to first month)</p>
</div>
</div>
</div>
<!-- Target Payoff Date Calculator -->
<div class="bg-blue-50 border-2 border-blue-200 rounded-lg p-6">
<h4 class="font-semibold text-gray-700 mb-3 text-lg">🎯 Calculate Required Payment for Target Date</h4>
<p class="text-sm text-gray-600 mb-4">Want to pay off by a specific date? Enter your target date and we'll calculate the required monthly extra payment.</p>
<div class="grid md:grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Target Payoff Date</label>
<input type="date" id="target-payoff-date" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
<p class="text-xs text-gray-500 mt-1">When you want to pay off the loan</p>
</div>
<div class="flex items-end">
<button onclick="calculateRequiredPayment()" class="w-full bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-semibold transition">
Calculate Required Payment
</button>
</div>
</div>
<div id="required-payment-result" class="hidden bg-white border border-blue-300 rounded-lg p-4">
<div class="flex items-center gap-2 mb-2">
<span class="text-2xl">💰</span>
<span class="font-semibold text-gray-800">Required Monthly Extra Payment:</span>
</div>
<div class="text-3xl font-bold text-blue-600 mb-2" id="required-payment-amount">--</div>
<p class="text-sm text-gray-600" id="required-payment-details">--</p>
<button onclick="applyRequiredPayment()" class="mt-3 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition">
Apply This Amount to Form
</button>
</div>
</div>
</div>
<button onclick="calculateMortgage()" class="w-full mt-6 bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white py-3 rounded-lg font-semibold text-lg transition shadow-lg">
Calculate Payoff Date & Interest Saved 🚀
</button>
<div class="mt-3 text-center">
<button onclick="clearFormData(event)" class="text-sm text-gray-500 hover:text-gray-700 underline">
Clear Saved Data
</button>
</div>
</div>
<!-- Upload Section - Optional/Collapsible -->
<details class="bg-white rounded-lg shadow-md p-6 mb-6">
<summary class="cursor-pointer text-lg font-semibold text-gray-700 mb-4">📄 Upload Statement (Optional - Auto-fill from image)</summary>
<p class="text-gray-600 mb-4">Take a photo or upload a PDF/image of your latest statement. We'll extract the details automatically.</p>
<div class="flex flex-wrap gap-3 mb-4">
<label for="file-upload" class="cursor-pointer bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition flex items-center gap-2">
<span>📁</span>
<span>Choose File</span>
</label>
<input id="file-upload" type="file" accept="image/*,application/pdf" class="hidden" onchange="handleFileUpload(event)">
<label for="camera-upload" class="cursor-pointer bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold transition flex items-center gap-2">
<span>📷</span>
<span>Take Photo</span>
</label>
<input id="camera-upload" type="file" accept="image/*" capture="environment" class="hidden" onchange="handleFileUpload(event)">
</div>
<div id="upload-status" class="hidden">
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3">
<div class="loading-spinner mt-1"></div>
<div>
<p class="font-semibold text-blue-800">Processing statement...</p>
<p class="text-sm text-blue-600" id="ocr-progress">Extracting text from image...</p>
</div>
</div>
</div>
<div id="extracted-preview" class="hidden mt-4">
<div class="bg-green-50 border border-green-200 rounded-lg p-4">
<p class="font-semibold text-green-800 mb-2">✓ Statement processed!</p>
<div class="text-sm text-green-700" id="extracted-text"></div>
</div>
</div>
</details>
<!-- Results Section -->
<div id="results" class="hidden">
<!-- Main Results - Key Calculations -->
<div class="bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-lg shadow-xl p-8 mb-6">
<h2 class="text-3xl font-bold mb-6 text-center">📊 Calculation Results</h2>
<div class="grid md:grid-cols-2 gap-6">
<div class="bg-white bg-opacity-20 rounded-lg p-6 backdrop-blur-sm">
<div class="text-lg opacity-90 mb-2">Loan Will Be Fully Paid On</div>
<div class="text-4xl font-bold mb-2" id="payoff-date">--</div>
<div class="text-sm opacity-90" id="time-saved">--</div>
</div>
<div class="bg-white bg-opacity-20 rounded-lg p-6 backdrop-blur-sm">
<div class="text-lg opacity-90 mb-2">Total Interest Payment Saved</div>
<div class="text-4xl font-bold mb-2" id="interest-saved">--</div>
<div class="text-sm opacity-90">Compared to standard payment schedule</div>
</div>
</div>
</div>
<!-- Loan Information (if start date provided) -->
<div id="loan-info" class="hidden bg-gray-100 rounded-lg shadow-md p-6 mb-6">
<h3 class="text-xl font-bold mb-4">📅 Loan Information</h3>
<div class="grid md:grid-cols-2 gap-4">
<div>
<div class="text-sm text-gray-600 mb-1">Loan Start Date</div>
<div class="text-lg font-semibold text-gray-800" id="display-loan-start-date">--</div>
</div>
<div>
<div class="text-sm text-gray-600 mb-1">Months Since Loan Start</div>
<div class="text-lg font-semibold text-gray-800" id="months-since-start">--</div>
</div>
</div>
</div>
<!-- Additional Summary Cards -->
<div class="grid md:grid-cols-3 gap-4 mb-6">
<div class="bg-gradient-to-br from-green-500 to-green-600 text-white rounded-lg shadow-lg p-6">
<div class="text-sm opacity-90 mb-1">Months to Payoff</div>
<div class="text-2xl font-bold" id="months-to-payoff">--</div>
</div>
<div class="bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-lg shadow-lg p-6">
<div class="text-sm opacity-90 mb-1">Total Interest Paid</div>
<div class="text-2xl font-bold" id="total-interest-paid">--</div>
</div>
<div class="bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-lg shadow-lg p-6">
<div class="text-sm opacity-90 mb-1">Total Amount Paid</div>
<div class="text-2xl font-bold" id="total-paid">--</div>
<div class="text-xs opacity-90 mt-1">Principal + Interest</div>
</div>
</div>
<!-- Loan Progress (if calculated from statement) -->
<div id="loan-progress" class="hidden bg-gradient-to-r from-indigo-500 to-purple-600 text-white rounded-lg shadow-lg p-6 mb-6">
<h3 class="text-2xl font-bold mb-4 flex items-center gap-2">
<span>🎯</span>
<span>Loan Progress</span>
</h3>
<div class="grid md:grid-cols-4 gap-4">
<div>
<div class="text-sm opacity-90 mb-1">Original Loan Amount</div>
<div class="text-2xl font-bold" id="original-amount">--</div>
</div>
<div>
<div class="text-sm opacity-90 mb-1">Original Term</div>
<div class="text-2xl font-bold" id="original-term">--</div>
</div>
<div>
<div class="text-sm opacity-90 mb-1">Payments Made</div>
<div class="text-2xl font-bold" id="payments-made">--</div>
</div>
<div>
<div class="text-sm opacity-90 mb-1">Principal Paid Down</div>
<div class="text-2xl font-bold" id="principal-paid">--</div>
</div>
</div>
<div class="mt-4 bg-white bg-opacity-20 rounded p-3 text-sm">
💡 Based on your current payment breakdown, we reverse-engineered your original loan details!
</div>
</div>
<!-- Chart -->
<div class="bg-white rounded-lg shadow-md p-6 mb-6">
<h3 class="text-xl font-bold mb-4">📈 Balance Over Time</h3>
<div style="max-height: 400px;">
<canvas id="balanceChart"></canvas>
</div>
</div>
<!-- Detailed Schedule -->
<div class="bg-white rounded-lg shadow-md p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-xl font-bold">📅 Prepayment Schedule</h3>
<div class="flex gap-2">
<select id="schedule-view" onchange="renderScheduleTable()" class="bg-gray-100 border border-gray-300 rounded px-3 py-2 text-sm">
<option value="12">First Year</option>
<option value="24">First 2 Years</option>
<option value="60">First 5 Years</option>
<option value="all">All Months</option>
</select>
<button onclick="exportToCSV()" class="bg-gray-200 hover:bg-gray-300 px-4 py-2 rounded-lg text-sm font-medium">
📥 Export CSV
</button>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead class="bg-gray-100 border-b-2 border-gray-300">
<tr class="text-left">
<th class="py-2 px-3">Month</th>
<th class="py-2 px-3">Date</th>
<th class="py-2 px-3">Payment</th>
<th class="py-2 px-3">Principal</th>
<th class="py-2 px-3">Interest</th>
<th class="py-2 px-3">Extra</th>
<th class="py-2 px-3">Total Payment</th>
<th class="py-2 px-3">Balance</th>
</tr>
</thead>
<tbody id="schedule-table" class="divide-y divide-gray-200">
<!-- Rows inserted here -->
</tbody>
</table>
</div>
<div id="schedule-info" class="text-sm text-gray-600 mt-3 text-center"></div>
</div>
</div>
</div>
</div>
<script>
console.log('🏠 Mortgage Calculator loaded');
console.log('Tesseract available:', typeof Tesseract !== 'undefined');
console.log('Chart.js available:', typeof Chart !== 'undefined');
let scheduleData = [];
let chart = null;
// Form data caching functions
function saveFormData() {
const formData = {
principal: document.getElementById('principal').value,
rate: document.getElementById('rate').value,
years: document.getElementById('years').value,
escrow: document.getElementById('escrow').value,
currentPrincipal: document.getElementById('current-principal').value,
currentInterest: document.getElementById('current-interest').value,
extra: document.getElementById('extra').value,
lumpsum: document.getElementById('lumpsum').value,
loanStartDate: document.getElementById('loan-start-date').value,
statementDate: document.getElementById('statement-date').value,
targetPayoffDate: document.getElementById('target-payoff-date').value
};
localStorage.setItem('mortgageCalculatorData', JSON.stringify(formData));
console.log('Form data saved to localStorage');
}
function loadFormData() {
try {
const savedData = localStorage.getItem('mortgageCalculatorData');
const statementDateField = document.getElementById('statement-date');
if (savedData) {
const formData = JSON.parse(savedData);
if (formData.principal) document.getElementById('principal').value = formData.principal;
if (formData.rate) document.getElementById('rate').value = formData.rate;
if (formData.years) document.getElementById('years').value = formData.years;
if (formData.escrow) document.getElementById('escrow').value = formData.escrow;
if (formData.currentPrincipal) document.getElementById('current-principal').value = formData.currentPrincipal;
if (formData.currentInterest) document.getElementById('current-interest').value = formData.currentInterest;
if (formData.extra) document.getElementById('extra').value = formData.extra;
if (formData.lumpsum) document.getElementById('lumpsum').value = formData.lumpsum;
if (formData.loanStartDate) document.getElementById('loan-start-date').value = formData.loanStartDate;
if (formData.statementDate) {
statementDateField.value = formData.statementDate;
} else if (statementDateField && !statementDateField.value) {
// Set default to today if not saved
const today = new Date();
statementDateField.value = today.toISOString().split('T')[0];
}
if (formData.targetPayoffDate) document.getElementById('target-payoff-date').value = formData.targetPayoffDate;
console.log('Form data loaded from localStorage');
} else if (statementDateField && !statementDateField.value) {
// Set default to today if no saved data
const today = new Date();
statementDateField.value = today.toISOString().split('T')[0];
}
} catch (e) {
console.error('Error loading form data:', e);
}
}
function clearFormData(event) {
localStorage.removeItem('mortgageCalculatorData');
// Clear all form fields
document.getElementById('principal').value = '';
document.getElementById('rate').value = '';
document.getElementById('years').value = '';
document.getElementById('escrow').value = '';
document.getElementById('current-principal').value = '';
document.getElementById('current-interest').value = '';
document.getElementById('extra').value = '0';
document.getElementById('lumpsum').value = '0';
const loanStartDateField = document.getElementById('loan-start-date');
if (loanStartDateField) loanStartDateField.value = '';
const statementDateField = document.getElementById('statement-date');
if (statementDateField) {
// Reset to today's date
const today = new Date();
statementDateField.value = today.toISOString().split('T')[0];
}
const targetPayoffDateField = document.getElementById('target-payoff-date');
if (targetPayoffDateField) targetPayoffDateField.value = '';
// Hide required payment result
const requiredPaymentResult = document.getElementById('required-payment-result');
if (requiredPaymentResult) requiredPaymentResult.classList.add('hidden');
console.log('Form data cleared from localStorage and form fields reset');
// Show a brief confirmation
if (event && event.target) {
const button = event.target;
const originalText = button.textContent;
button.textContent = '✓ Cleared!';
button.classList.add('text-green-600');
setTimeout(() => {
button.textContent = originalText;
button.classList.remove('text-green-600');
}, 2000);
}
}
// Calculate required monthly payment to reach target payoff date
function calculateRequiredPayment() {
// Get loan parameters
const principal = parseFloat(document.getElementById('principal').value);
const rateInput = parseFloat(document.getElementById('rate').value);
const rate = rateInput / 100 / 12; // Monthly rate
const years = parseFloat(document.getElementById('years').value);
const escrow = parseFloat(document.getElementById('escrow').value) || 0;
const currentPrincipalPayment = parseFloat(document.getElementById('current-principal').value) || null;
const currentInterestPayment = parseFloat(document.getElementById('current-interest').value) || null;
const targetDateInput = document.getElementById('target-payoff-date').value;
// Validate inputs
if (!principal || principal <= 0) {
alert('Please enter a valid Current Principal Balance first.');
document.getElementById('principal').focus();
return;
}
if (!rateInput || rateInput <= 0) {
alert('Please enter a valid Interest Rate first.');
document.getElementById('rate').focus();
return;
}
if (!targetDateInput) {
alert('Please select a Target Payoff Date.');
document.getElementById('target-payoff-date').focus();
return;
}
// Calculate standard payment
let standardPayment;
if (currentPrincipalPayment && currentInterestPayment) {
standardPayment = currentPrincipalPayment + currentInterestPayment;
} else if (years) {
const months = years * 12;
standardPayment = principal * (rate * Math.pow(1 + rate, months)) / (Math.pow(1 + rate, months) - 1);
} else {
alert('Please enter either Remaining Term or Current Payment Information.');
return;
}
// Get current date (statement date or today)
const statementDateElement = document.getElementById('statement-date');
const statementDateInput = statementDateElement ? statementDateElement.value : '';
let currentDate;
if (statementDateInput) {
currentDate = new Date(statementDateInput);
currentDate.setHours(0, 0, 0, 0);
} else {
currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
}
// Calculate months until target date
const targetDate = new Date(targetDateInput);
targetDate.setHours(0, 0, 0, 0);
if (targetDate <= currentDate) {
alert('Target date must be after the Current Statement Date.');
return;
}
const monthsUntilTarget = Math.ceil((targetDate - currentDate) / (1000 * 60 * 60 * 24 * 30.44)); // Average days per month
if (monthsUntilTarget <= 0) {
alert('Target date must be at least 1 month in the future.');
return;
}
// Use binary search to find required extra payment
let minExtra = 0;
let maxExtra = principal; // Upper bound: can't pay more than principal
let requiredExtra = 0;
const tolerance = 0.01; // $0.01 tolerance
// First check if it's even possible with no extra payment
let testBalance = principal;
let testMonths = 0;
while (testBalance > 0 && testMonths < monthsUntilTarget) {
const interest = testBalance * rate;
const principalPayment = standardPayment - interest;
testBalance -= principalPayment;
testMonths++;
}
if (testBalance <= 0 && testMonths <= monthsUntilTarget) {
// Can pay off without extra payment
requiredExtra = 0;
} else {
// Need extra payment - use binary search
let foundSolution = false;
while (maxExtra - minExtra > tolerance) {
const testExtra = (minExtra + maxExtra) / 2;
// Simulate loan payoff with this extra payment
testBalance = principal;
testMonths = 0;
while (testBalance > 0 && testMonths < monthsUntilTarget * 2) { // Safety limit
const interest = testBalance * rate;
const principalPayment = standardPayment - interest;
const extraPayment = testExtra;
if (principalPayment + extraPayment > testBalance) {
testBalance = 0;
} else {
testBalance -= (principalPayment + extraPayment);
}
testMonths++;
}
if (testBalance <= 0 && testMonths <= monthsUntilTarget) {
// This extra payment works, try lower
requiredExtra = testExtra;
maxExtra = testExtra;
foundSolution = true;
} else {
// Need more extra payment
minExtra = testExtra;
}
}
// Check if solution is even possible
if (!foundSolution && maxExtra >= principal - tolerance) {
// Test with maximum possible payment
testBalance = principal;
testMonths = 0;
while (testBalance > 0 && testMonths < monthsUntilTarget * 2) {
const interest = testBalance * rate;
const principalPayment = standardPayment - interest;
const extraPayment = principal; // Maximum possible
if (principalPayment + extraPayment > testBalance) {
testBalance = 0;
} else {
testBalance -= (principalPayment + extraPayment);
}
testMonths++;
}
if (testBalance > 0 || testMonths > monthsUntilTarget) {
// Impossible to pay off by target date
const resultDiv = document.getElementById('required-payment-result');
const amountDiv = document.getElementById('required-payment-amount');
const detailsDiv = document.getElementById('required-payment-details');
resultDiv.classList.remove('hidden');
amountDiv.textContent = 'Not Possible';
amountDiv.classList.remove('text-blue-600', 'text-green-600');
amountDiv.classList.add('text-red-600');
detailsDiv.textContent = `It's not possible to pay off the loan by ${targetDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}. The target date is too soon. Please select a later date.`;
return;
}
}
}
// Round to nearest dollar
requiredExtra = Math.ceil(requiredExtra);
// Display result
const resultDiv = document.getElementById('required-payment-result');
const amountDiv = document.getElementById('required-payment-amount');
const detailsDiv = document.getElementById('required-payment-details');
if (requiredExtra === 0) {
amountDiv.textContent = '$0';
amountDiv.classList.remove('text-blue-600');
amountDiv.classList.add('text-green-600');
detailsDiv.textContent = `Great news! You can pay off by ${targetDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })} with your current payment schedule (${monthsUntilTarget} months).`;
} else {
amountDiv.textContent = '$' + requiredExtra.toLocaleString();
amountDiv.classList.remove('text-green-600');
amountDiv.classList.add('text-blue-600');
// Calculate actual payoff with this payment
let actualBalance = principal;
let actualMonths = 0;
while (actualBalance > 0 && actualMonths < monthsUntilTarget * 2) {
const interest = actualBalance * rate;
const principalPayment = standardPayment - interest;
const extraPayment = requiredExtra;
if (principalPayment + extraPayment > actualBalance) {
actualBalance = 0;
} else {
actualBalance -= (principalPayment + extraPayment);
}
actualMonths++;
}
const actualPayoffDate = new Date(currentDate);
actualPayoffDate.setMonth(actualPayoffDate.getMonth() + actualMonths);
detailsDiv.textContent = `By paying an extra $${requiredExtra.toLocaleString()} per month, you'll pay off by ${actualPayoffDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })} (${actualMonths} months).`;
}
resultDiv.classList.remove('hidden');
// Store the required payment for the apply function
window.requiredExtraPayment = requiredExtra;
}
// Apply the calculated required payment to the form
function applyRequiredPayment() {
if (window.requiredExtraPayment !== undefined) {
document.getElementById('extra').value = window.requiredExtraPayment;
saveFormData();
// Show confirmation
const button = event.target;
const originalText = button.textContent;
button.textContent = '✓ Applied!';
button.classList.add('bg-green-600', 'hover:bg-green-700');
setTimeout(() => {
button.textContent = originalText;
button.classList.remove('bg-green-600', 'hover:bg-green-700');
}, 2000);
}
}
// Load saved data when page loads
window.addEventListener('DOMContentLoaded', function() {
loadFormData();
// Auto-save when form fields change
const formFields = ['principal', 'rate', 'years', 'escrow', 'current-principal',
'current-interest', 'extra', 'lumpsum', 'loan-start-date', 'statement-date', 'target-payoff-date'];
formFields.forEach(fieldId => {
const field = document.getElementById(fieldId);
if (field) {
field.addEventListener('input', function() {
// Debounce: save after user stops typing for 1 second
clearTimeout(field.saveTimeout);
field.saveTimeout = setTimeout(saveFormData, 1000);
});
field.addEventListener('change', saveFormData);
}
});
});
function calculateExtraFromRoundUp() {
const roundUpAmount = parseFloat(document.getElementById('roundup').value);
if (!roundUpAmount) return;
const principal = parseFloat(document.getElementById('principal').value);
const rate = parseFloat(document.getElementById('rate').value) / 100 / 12;
const years = parseFloat(document.getElementById('years').value);
const escrow = parseFloat(document.getElementById('escrow').value) || 0;
if (!principal || !rate) {
alert('Please fill in principal balance and interest rate first.');
return;
}
// Calculate standard payment
// If we have years, use it; otherwise calculate from payment breakdown
let standardPayment;
if (years) {
const months = years * 12;
standardPayment = principal * (rate * Math.pow(1 + rate, months)) / (Math.pow(1 + rate, months) - 1);
} else {
// Try to get from current payment breakdown
const currentPrincipal = parseFloat(document.getElementById('current-principal').value);
const currentInterest = parseFloat(document.getElementById('current-interest').value);
if (currentPrincipal && currentInterest) {
standardPayment = currentPrincipal + currentInterest;
// Remove any existing extra from current principal
const expectedInterest = principal * rate;
standardPayment = (currentPrincipal + currentInterest) - (currentPrincipal - (standardPayment - expectedInterest));
} else {
alert('Please fill in remaining term or current payment breakdown first.');
return;
}
}
const totalStandardPayment = standardPayment + escrow;
// Calculate extra
const extra = roundUpAmount - totalStandardPayment;
console.log('Round-up calculation:', {
roundUpAmount,
standardPayment: standardPayment.toFixed(2),
escrow: escrow.toFixed(2),
totalStandard: totalStandardPayment.toFixed(2),
extra: extra.toFixed(2)
});
if (extra < 0) {
alert(`Round-up amount ($${roundUpAmount.toLocaleString()}) is less than standard payment ($${totalStandardPayment.toFixed(2)})`);
document.getElementById('roundup').value = '';
return;
}
document.getElementById('extra').value = Math.round(extra);
// Show feedback
document.getElementById('roundup').classList.add('bg-green-50', 'border-green-300');
setTimeout(() => {
document.getElementById('roundup').classList.remove('bg-green-50', 'border-green-300');
}, 1000);
}
function clearRoundUp() {
document.getElementById('roundup').value = '';
}
function calculateRemainingTerm(balance, monthlyRate, monthlyPayment) {
// Calculate remaining months using amortization formula
// n = -ln(1 - (B * r / P)) / ln(1 + r)
// Where: B = balance, r = monthly rate, P = payment
if (balance <= 0 || monthlyRate <= 0 || monthlyPayment <= 0) return null;
// Check if payment is sufficient to pay off loan
const minPayment = balance * monthlyRate;
if (monthlyPayment <= minPayment) {
// Payment doesn't even cover interest - infinite loan
return null;
}
try {
const numerator = Math.log(1 - (balance * monthlyRate / monthlyPayment));
const denominator = Math.log(1 + monthlyRate);
const months = -numerator / denominator;
// Sanity check: between 1 month and 40 years
if (months > 0 && months <= 480) {
return Math.round(months);
}
} catch (e) {
console.error('Error calculating term:', e);
}
return null;
}
function calculateLoanProgress(currentBalance, monthlyRate, standardPayment, remainingMonths) {
// Work backwards to find original loan details
// Try common loan terms: 30, 20, 15 years
console.log('=== Calculating Loan Progress ===');
console.log('Current balance:', currentBalance);
console.log('Monthly rate:', monthlyRate);
console.log('Standard payment:', standardPayment);
console.log('Remaining months:', remainingMonths);
const commonTerms = [360, 240, 180]; // 30, 20, 15 years in months
let bestMatch = null;
for (const originalTerm of commonTerms) {
// Calculate what the original loan amount would be for this term
// Using: P = L × [r(1+r)^n] / [(1+r)^n - 1]
// Solve for L: L = P × [(1+r)^n - 1] / [r(1+r)^n]
const factor = Math.pow(1 + monthlyRate, originalTerm);
const originalAmount = standardPayment * (factor - 1) / (monthlyRate * factor);
// Calculate how many payments have been made
const paymentsMade = originalTerm - remainingMonths;
// Calculate principal paid down
const principalPaid = originalAmount - currentBalance;
console.log(`\nTrying ${originalTerm / 12}-year term:`);
console.log(' Original amount:', Math.round(originalAmount));
console.log(' Payments made:', Math.round(paymentsMade));
console.log(' Principal paid:', Math.round(principalPaid));
// Sanity check: payments made should be positive and reasonable
if (paymentsMade > 0 && paymentsMade < originalTerm && principalPaid > 0) {
// This could be the original term
// Prefer the term that results in a positive, reasonable number of payments made
if (!bestMatch || Math.abs(paymentsMade - originalTerm / 2) < Math.abs(bestMatch.paymentsMade - bestMatch.originalTerm / 2)) {
bestMatch = {
originalAmount: Math.round(originalAmount),
originalTerm: Math.round(originalTerm / 12), // Convert to years
paymentsMade: Math.round(paymentsMade),
principalPaid: Math.round(principalPaid),
percentComplete: Math.round((paymentsMade / originalTerm) * 100)
};
}
}
}
console.log('\n✓ Best match:', bestMatch);
return bestMatch;
}
async function handleFileUpload(event) {
console.log('=== FILE UPLOAD STARTED ===');
const file = event.target.files[0];
if (!file) {
console.log('No file selected');
return;
}
console.log('File:', file.name, file.type, file.size, 'bytes');
document.getElementById('upload-status').classList.remove('hidden');
document.getElementById('extracted-preview').classList.add('hidden');
try {
let text = '';
if (file.type === 'application/pdf') {
console.log('PDF detected - not supported yet');
// For PDF, we'd need pdf.js - for now, prompt user to use image
alert('PDF support coming soon! Please take a photo of your statement instead.');
document.getElementById('upload-status').classList.add('hidden');
return;
}
console.log('Starting OCR...');
// OCR for images
document.getElementById('ocr-progress').textContent = 'Reading statement...';
try {
const result = await Tesseract.recognize(file, 'eng', {
logger: m => {
if (m.status === 'recognizing text') {
document.getElementById('ocr-progress').textContent =
`Processing: ${Math.round(m.progress * 100)}%`;
}
}
});
text = result.data.text;
console.log('OCR Text:', text); // Debug output
if (!text || text.trim().length < 50) {
throw new Error('OCR returned insufficient text');
}
} catch (ocrError) {
console.error('OCR Error:', ocrError);
throw new Error('Failed to extract text from image. Please ensure image is clear and well-lit.');
}
// Parse the text
const parsed = parseStatement(text);
// Calculate remaining term and detect extra payments
let calculatedTerm = null;
let detectedExtraPayment = 0;
let loanProgress = null;
if (parsed.principal && parsed.rate && parsed.currentPrincipalPayment && parsed.currentInterestPayment) {
const monthlyRate = parsed.rate / 100 / 12;
const totalPayment = parsed.currentPrincipalPayment + parsed.currentInterestPayment;
// First, calculate what the STANDARD principal payment should be
// Standard = Total Payment - Interest
// Where Interest = Balance × Monthly Rate
const expectedInterest = parsed.principal * monthlyRate;
const standardPrincipal = totalPayment - expectedInterest;
// Detect extra payment
if (parsed.currentPrincipalPayment > standardPrincipal + 50) {
// There's an extra payment (allow $50 buffer for rounding)
detectedExtraPayment = Math.round(parsed.currentPrincipalPayment - standardPrincipal);
}
// Calculate remaining term using STANDARD payment (without extra)
const standardPayment = totalPayment - detectedExtraPayment;
calculatedTerm = calculateRemainingTerm(
parsed.principal,
monthlyRate,
standardPayment
);
// Calculate original loan details using standard payment
loanProgress = calculateLoanProgress(
parsed.principal,
monthlyRate,
standardPayment,
calculatedTerm
);
}
if (parsed.principal) document.getElementById('principal').value = parsed.principal;
if (parsed.rate) document.getElementById('rate').value = parsed.rate;
if (calculatedTerm) document.getElementById('years').value = (calculatedTerm / 12).toFixed(1);
if (parsed.escrow) document.getElementById('escrow').value = parsed.escrow;
if (detectedExtraPayment > 0) document.getElementById('extra').value = detectedExtraPayment;
// Fill in current payment breakdown fields
if (parsed.currentPrincipalPayment) document.getElementById('current-principal').value = parsed.currentPrincipalPayment.toFixed(2);
if (parsed.currentInterestPayment) document.getElementById('current-interest').value = parsed.currentInterestPayment.toFixed(2);
// Auto-fill original term if we calculated loan progress
if (loanProgress) {
const originalYearsElement = document.getElementById('original-years');
if (originalYearsElement) {
originalYearsElement.value = loanProgress.originalTerm;
}
}
// Save the auto-filled data
saveFormData();
document.getElementById('upload-status').classList.add('hidden');
document.getElementById('extracted-preview').classList.remove('hidden');
// Show loan progress if calculated
if (loanProgress) {
document.getElementById('loan-progress').classList.remove('hidden');
document.getElementById('original-amount').textContent = '$' + loanProgress.originalAmount.toLocaleString();
document.getElementById('original-term').textContent = loanProgress.originalTerm + ' years';
document.getElementById('payments-made').textContent = loanProgress.paymentsMade + ' months';
document.getElementById('principal-paid').textContent = '$' + loanProgress.principalPaid.toLocaleString();
}
let extractedInfo = '';
// Check if any data was extracted
const hasData = parsed.principal || parsed.rate || parsed.escrow ||
parsed.currentPrincipalPayment || parsed.currentInterestPayment;
if (!hasData) {
// No data extracted - show warning and raw text for debugging
extractedInfo = `
<div class="bg-yellow-50 border border-yellow-200 rounded p-3 mb-3">
<p class="font-semibold text-yellow-800">⚠️ Could not extract mortgage details</p>
<p class="text-sm text-yellow-700 mt-1">Please enter values manually below or try retaking the photo with better lighting.</p>
</div>
<details class="text-xs">
<summary class="cursor-pointer text-blue-600 hover:text-blue-700">Show extracted text (debug)</summary>