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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
<!DOCTYPE html>
<html lang="en">
  <!--- HEADER GOES BELOW HERE--->

  {{ HEADER }}

  <!--- HEADER GOES ABOVE HERE--->

  <style>
    :root {
      --background: #ffffff;
      --foreground: #09090b;
      --card: #ffffff;
      --card-foreground: #09090b;
      --popover: #ffffff;
      --popover-foreground: #09090b;
      --primary: #6e56cf;
      --primary-foreground: #ffffff;
      --secondary: #f4f4f5;
      --secondary-foreground: #18181b;
      --muted: #f4f4f5;
      --muted-foreground: #71717a;
      --accent: #f4f4f5;
      --accent-foreground: #18181b;
      --destructive: #ef4444;
      --destructive-foreground: #fafafa;
      --border: #e4e4e7;
      --input: #e4e4e7;
      --ring: #6e56cf;
      --radius: 0.5rem;
      --primary-color: #6e56cf; /* Shadcn purple */
      --secondary-color: #7c66ce;
      --accent-color: #a18fff;
      --dark-color: #09090b;
      --light-color: #fafafa;
      --gray-color: #71717a;
      --light-gray: #f4f4f5;
      --light-bg: #f5f7fb; /* Light background for sections */
      --heading-color: white; /* For headings */
      --text-color: #555555; /* For regular text */
      --success-color: #10b981;
      --border-radius: 0.5rem;
      --box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1),
        0 1px 2px -1px rgb(0 0 0 / 0.1);
      --transition: all 0.2s ease;
      --section-padding-top: 100px;
    }

    /* Shadcn-style button */
    .shadcn-button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--radius);
      font-weight: 500;
      font-size: 0.875rem;
      height: 2.5rem;
      padding-left: 1rem;
      padding-right: 1rem;
      transition: var(--transition);
      cursor: pointer;
      text-decoration: none;
    }

    .shadcn-button-primary {
      background-color: var(--primary);
      color: var(--primary-foreground);
      border: 1px solid var(--primary);
    }

    .shadcn-button-primary:hover {
      background-color: var(--secondary-color);
      color: var(--primary-foreground);
    }

    .shadcn-button-outline {
      background-color: transparent;
      color: var(--primary);
      border: 1px solid var(--border);
    }

    .shadcn-button-outline:hover {
      background-color: var(--secondary);
      color: var(--primary);
    }

    /* Sidepanel styling */
    .sidepanel {
      height: 100%;
      width: 0;
      position: fixed;
      z-index: 1000;
      top: 0;
      right: 0;
      background-color: var(--card);
      overflow-x: hidden;
      transition: 0.3s;
      padding-top: 60px;
      box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
    }

    .sidepanel a {
      padding: 8px 8px 8px 32px;
      text-decoration: none;
      font-size: 16px;
      color: var(--foreground);
      display: block;
      transition: 0.3s;
    }

    .sidepanel .closebtn {
      position: absolute;
      top: 0;
      right: 25px;
      font-size: 36px;
      margin-left: 50px;
      color: var(--muted-foreground);
    }

    /* Span annotation styling */
    .span_container {
      position: relative;
      display: inline-block;
      border-radius: var(--radius);
    }

    .span_label {
      position: absolute;
      top: -18px;
      left: 0;
      font-size: 10px;
      border-radius: 3px;
      padding: 0 3px;
      color: var(--primary);
    }

    .span_close {
      position: absolute;
      top: -18px;
      right: 0;
      font-size: 12px;
      border-radius: 3px;
      padding: 0 3px;
      cursor: pointer;
      color: var(--destructive);
    }

    /* Card styling */
    .shadcn-card {
      height: 65vh;
      background-color: var(--card);
      border-radius: var(--radius);
      border: 1px solid var(--border);
      box-shadow: var(--box-shadow);
      overflow: hidden;
    }

    .shadcn-card-header {
      padding: 1.5rem;
      border-bottom: 1px solid var(--border);
    }

    .shadcn-card-content {
      padding: 1.5rem;
    }

    fieldset {
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 1rem;
      margin-bottom: 1rem;
    }

    legend {
      font-weight: 500;
      color: var(--heading-color);
      padding: 0 0.5rem;
    }

    /* Form elements */
    input[type="text"],
    input[type="number"],
    textarea,
    select {
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 0.5rem;
      background-color: var(--background);
      color: var(--foreground);
      transition: var(--transition);
    }

    input[type="text"]:focus,
    input[type="number"]:focus,
    textarea:focus,
    select:focus {
      outline: none;
      border-color: var(--ring);
      box-shadow: 0 0 0 2px var(--ring-opacity);
    }
  </style>

  {{ custom_js | safe }}

  <body style="background-color: var(--background); color: var(--foreground)">
    <input type="hidden" name="username" id="username" value="{{username}}" />
    <input
      type="hidden"
      name="instance_id"
      id="instance_id"
      value="{{instance_id}}"
    />
    <input
      type="hidden"
      name="alert_time_each_instance"
      id="alert_time_each_instance"
      value="{{alert_time_each_instance}}"
    />
    <p id="timecounter" hidden>Time spent:</p>

    <div id="mySidepanel" class="sidepanel">
      <a
        href="javascript:void(0)"
        class="closebtn"
        target_id="mySidepanel"
        onclick="closeNav(this.getAttribute('target_id'))"
        >&times;</a
      >
      {{keybindings}}
    </div>

    <div id="Statpanel" class="sidepanel">
      <a
        href="javascript:void(0)"
        class="closebtn"
        target_id="Statpanel"
        onclick="closeNav(this.getAttribute('target_id'))"
        >&times;</a
      >
      [[statistics_nav]]
    </div>

    <script>
      // this is for ai hints
      document.addEventListener("click", function (event) {
        const hintEl = event.target.closest(".hint");
        if (!hintEl) return; // Not a .hint click

        const aiHelp = hintEl.closest(".ai-help");
        const tooltip = aiHelp.querySelector(".tooltip");
        const tooltipText = tooltip.querySelector(".tooltip-text");
        const annotationId = aiHelp.closest("[data-annotation-id]")?.dataset
          .annotationId;
        const text = document.getElementById("instance-text").innerText;

        fetch("get_ai_hint", {
          method: "POST",    
          credentials: "same-origin",              
          body: JSON.stringify({ annotation_id: annotationId, text: text }),
          headers: { "Content-Type": "application/json" },
        })
          .then((response) => response.json())
          .then((data) => {
            tooltipText.innerHTML = `<span class="reasoning">Reasoning:</span> ${data.reasoning}`;
            tooltip.classList.toggle("active");
          })
          .catch((error) => {
            tooltipText.innerHTML = `<span class="reasoning">Error:</span> Could not load hint`;
            tooltip.classList.toggle("active");
            console.error("Error fetching AI hint:", error);
          });
      });
      document.addEventListener("click", function (event) {
        if (!event.target.closest(".ai-help")) {
          document.querySelectorAll(".tooltip.active").forEach((tooltip) => {
            tooltip.classList.remove("active");
          });
        }
      });
    </script>

    <script>
      document.addEventListener("keyup", function (event) {
        var active_id = document.activeElement.id;
        var active_type = document.activeElement.getAttribute("type");
        if ((active_id == "go_to") | (active_type == "text")) return;

        //first check whether this keyboard input is a shortcut for checkboxes
        var checkboxes = document.querySelectorAll("input[type=checkbox]");
        var radios = document.querySelectorAll("input[type=radio]");
        var x = event.key.toLowerCase();

        for (var i = 0; i < checkboxes.length; i++) {
          //alert(checkboxes[i].value)
          if (x === checkboxes[i].value) {
            checkboxes[i].checked = !checkboxes[i].checked;
            if (checkboxes[i].onclick != null)
              checkboxes[i].onclick.apply(checkboxes[i]);
            return;
          }
        }
        for (var i = 0; i < radios.length; i++) {
          //alert(checkboxes[i].value)
          if (x === radios[i].value) {
            radios[i].checked = !radios[i].checked;
            if (radios[i].onclick != null) radios[i].onclick.apply(radios[i]);
            return;
          }
        }

        // Each time we process a user's key presses, track who is doing
        // it by grabbing the hidden firstname and lastname fields
        get_new_instance(event);
      });

      function getFieldSetState(element) {
        // console.dir('saw annotation' + element.value);
        // console.dir(element.parentElement);
        //var fieldSet = element.parentElement;

        // Find the closeset ancestor fieldset element from this input
        var fieldSet = element.closest("fieldset");

        // Get all the inputs in this field set (what are the annotation options)
        var inputs = fieldSet.querySelectorAll("input");

        // Get state of all the in this group
        var state = Array.from(inputs).map((input) => {
          return {
            name: input.getAttribute("label_name"),
            value: input.checked,
            // checked: input.value // unused??
          };
        });
        return state;
      }

      function registerAnnotation(element) {
        // If the element is a radio button, we need to uncheck all the other which
        // requires sending the state of all the other buttons in the group
        sc = element.getAttribute("selection_constraint");
        if (sc && sc == "single") {
          state = getFieldSetState(element);
        } else if (element.getAttribute("type") == "range") {
          state = [
            {
              name: element.getAttribute("label_name"),
              value: element.value,
            },
          ];
        }
        // This is a checkbox so we can just send the state of this checkbox
        else {
          state = [
            {
              name: element.getAttribute("label_name"),
              value: element.checked,
              // checked: element.value // unused??
            },
          ];
        }

        // Get which annotation group this change belongs to
        var schema = element.getAttribute("schema");

        // Get the instance id
        var instance_id = document.getElementById("instance_id").value;

        // Package this all up in a post request to the server's updateinstance endpoint
        var post_req = {
          type: "label",
          schema: schema,
          state: state,
          instance_id: instance_id,
        };

        // Send the post request
        fetch("/updateinstance", {
          method: "POST",
          body: JSON.stringify(post_req),
          credentials: "same-origin",
          headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
        });
      }

      function registerTextAnnotation(element) {
        // Get which annotation group this change belongs to
        var schema = element.getAttribute("schema");

        // Get the instance id
        var instance_id = document.getElementById("instance_id").value;

        state = [
          {
            name: element.getAttribute("label_name"),
            value: element.value,
          },
        ];

        // Package this all up in a post request to the server's updateinstance endpoint
        var post_req = {
          type: "label",
          schema: schema,
          state: state,
          instance_id: instance_id,
        };

        // Send the post request
        fetch("/updateinstance", {
          method: "POST",
          body: JSON.stringify(post_req),
          credentials: "same-origin",
          headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
        });
      }

      function getSelectedText() {
        var text = "";
        if (typeof window.getSelection != "undefined") {
          text = window.getSelection().toString();
        } else if (
          typeof document.selection != "undefined" &&
          document.selection.type == "Text"
        ) {
          text = document.selection.createRange().text;
        }
        return text;
      }

      function deleteSpanAnnotation(
        spanElem,
        schema,
        labelName,
        title,
        start,
        end
      ) {
        // Get the instance id
        var instance_id = document.getElementById("instance_id").value;

        // Get the text of the span
        var spanText = spanElem.innerText;

        // Package this all up in a post request to the server's updateinstance endpoint
        var post_req = {
          type: "span",
          schema: schema,
          state: [
            {
              name: labelName,
              start: start,
              end: end,
              title: title,
              value: null,
            },
          ],
          instance_id: instance_id,
        };

        // Send the post request
        fetch("/updateinstance", {
          method: "POST",
          body: JSON.stringify(post_req),
          credentials: "same-origin",
          headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
        });

        // Remove the outer most div tag that has the span's annotation title (the small text above)
        $(spanElem).find("div").first().remove();
        // Remove the close tag
        $(spanElem).find("div").last().remove();
        // Remove the span highlight by unwrapping the inner text
        $(spanElem.firstChild).unwrap();
      }

      function getEarlierChildren(n, skipMe) {
        var r = [];
        for (; n; n = n.nextSibling)
          if (n.nodeType == 1 && n != skipMe) r.push(n);
          else if (n == skipMe) break;
        return r;
      }

      function getEarlierSiblings(n) {
        return getEarlierChildren(n.parentNode.firstChild, n);
      }

      function getTextOfSpans(elems) {
        text = "";
        for (i = 0; i < elems.length; i++) {
          //console.log(elems[i].textContent)

          e = elems[i].cloneNode(true);
          console.log("e", e);
          // Delete all the nested <div> elements with jquery to get the plain text
          $(e).find("div").remove();
          console.log("sib text", e.textContent);
          text += " " + e.textContent;
        }

        return text.trim();
      }

      function getSelectionIndices() {
        // Get the user selection
        var selection = window.getSelection();

        if (selection.rangeCount === 0) {
          return { start: -1, end: -1 }; // No selection
        }

        // Get the range object representing the selected portion
        var range = selection.getRangeAt(0);

        // Get the left most element in the selection
        var leftMost = range.startContainer;
        var leftSibs = getEarlierSiblings(leftMost);
        console.log("leftSibs", leftSibs);
        // Get the text of the left elements
        var leftText = getTextOfSpans(leftSibs);

        // Find the parent div element with name "instance_text" using jquery
        var parentDiv = $(range.commonAncestorContainer).closest(
          'div[name="instance_text"]'
        )[0];
        //console.log('parentDiv', parentDiv)

        if (!parentDiv) {
          return { start: -2, end: -2 }; // Not within a <div class="context_text">
        }

        //console.log('parentDiv')
        //console.dir(parentDiv.innerHTML)

        // Make a copy of the parent div to manipulate
        parentDiv = parentDiv.cloneNode(true);

        // Create a temporary Range to find the offset relative to the parent div
        console.log(
          "before delete",
          range.startContainer,
          range.startOffset,
          range.endOffset
        );
        var tempRange = document.createRange();
        tempRange.setStart(parentDiv, 0);
        tempRange.setEnd(range.startContainer, range.startOffset);

        // Delete all the nested <div> elements with jquery to get the plain text
        $(parentDiv).find("div").remove();

        console.log("after delete");
        console.dir(parentDiv.innerHTML);
        console.log("text");
        console.dir(parentDiv.textContent);

        console.log(
          "after delete",
          range.startContainer,
          range.startOffset,
          range.endOffset
        );

        // Get the starting offset of the selection within the parent div
        var div = document.createElement("div");
        div.appendChild(tempRange.cloneContents());

        var s = range.startContainer.textContent.toString();
        //console.log(`text: "${text}"`);
        var whitespaceOffset = s.length - s.trimStart().length;

        var startOffset = range.startOffset - whitespaceOffset;

        if (leftText.length > 0) {
          // Add 1 for space between the left text and the selected text
          startOffset += leftText.length + 1;
        }

        // Get the length of the selected text
        var selectedTextLength = range.toString().length;

        // Calculate the ending offset of the selection within the parent div
        var endOffset = startOffset + selectedTextLength;

        return { start: startOffset, end: endOffset };
      }

      function surroundSelection(schema, labelName, title, selectionColor) {
        //var span = document.createElement("span");
        //span.style.fontWeight = "bold";
        //span.style.color = "green";

        // Check that this wasn't a spurious click or the click for the delete button which
        // also seems to trigger this selection event
        if (window.getSelection().rangeCount == 0) {
          return;
        }
        var range = window.getSelection().getRangeAt(0);

        // console.dir(window.getSelection())

        // console.log(range.startOffset, range.endOffset)
        if (range.startOffset == range.endOffset) {
          return;
        }

        // Get the instance id
        var instance_id = document.getElementById("instance_id").value;

        if (window.getSelection) {
          var sel = window.getSelection();

          // console.dir(sel);

          // Check that we're labeling something in the instance text that
          // we want to annotate
          if (!sel.anchorNode.parentElement) {
            return;
          }

          // TODO: check that we're not nesting a span of the same time here

          // Otherwise, we're going to be adding a new span annotation, if
          // the user has selected some non-empty part of the text
          if (sel.rangeCount && sel.toString().trim().length > 0) {
            // Get the selection text as a string
            var selText = window.getSelection().toString().trim();
            console.log("selText1", selText);

            // Get the start and end offsets of the selection
            var range = sel.getRangeAt(0);
            var start = range.startOffset;
            var end = range.endOffset;
            // Get the generic text between the start and end offsets
            var text = range.startContainer.textContent.substring(start, end);
            var s = range.startContainer.textContent.toString();
            //console.log(`text: "${text}"`);
            var whitespaceOffset = s.length - s.trimStart().length;
            //console.log('whitespaceOffset', whitespaceOffset);

            /*
                  console.log(`full range text "${range.startContainer.textContent}`);
                  console.log('start', start);
                  console.log('end', end);
                  console.log('start', start - whitespaceOffset);
                  console.log('end', end - whitespaceOffset);
                  console.log(`ranged substring "${text}"`);
                    */
            // Get the raw text of the selection without any HTML
            var sel = window.getSelection();
            var range = sel.getRangeAt(0);
            var div = document.createElement("div");
            div.appendChild(range.cloneContents());
            var selText = div.innerHTML;
            //console.log(`selText2: "${selText}"`);

            tsc = selectionColor.replace(")", ", 0.25)");

            var span = document.createElement("span");
            span.className = "span_container";
            span.setAttribute("selection_label", labelName);
            span.setAttribute("style", "background-color:rgb" + tsc + ";");

            var label = document.createElement("div");
            label.className = "span_label";
            label.textContent = title;
            label.setAttribute(
              "style",
              "background-color:white;" +
                "border:2px solid rgb" +
                selectionColor +
                ";"
            );

            var delLabel = document.createElement("div");
            delLabel.className = "span_close";
            delLabel.textContent = "×";
            delLabel.setAttribute("style", "background-color:white;");
            //                  + "border:2px solid rgb" + selectionColor + ";");
            delLabel.onclick = function () {
              deleteSpanAnnotation(
                span,
                schema,
                labelName,
                title,
                range.startOffset,
                range.endOffset
              );
            };

            // Get the offsets
            startEnd = getSelectionIndices();
            console.log("startEnd", startEnd);
            state = [
              {
                name: labelName,
                start: startEnd["start"],
                end: startEnd["end"],
                title: title,
                value: sel.toString(),
              },
            ];

            // console.log('adding new annotation', range.startOffset, range.endOffset, sel.toString())

            // Package this all up in a post request to the server's updateinstance endpoint
            var post_req = {
              type: "span",
              schema: schema,
              state: state,
              instance_id: instance_id,
            };

            // Send the post request
            fetch("/updateinstance", {
              method: "POST",
              body: JSON.stringify(post_req),
              credentials: "same-origin",
              headers: {
                "Content-type": "application/json; charset=UTF-8",
              },
            });

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
            span.appendChild(label);
            span.appendChild(delLabel);

            // Clear the current selection
            sel.empty();
          }
        }
      }

      function changeSpanLabel(
        checkbox,
        schema,
        spanLabel,
        spanTitle,
        spanColor
      ) {
        // Listen for when the user has highlighted some text (only when the label is checked)
        document.onmouseup = function (e) {
          var senderElement = e.target;
          // Avoid the case where the user clicks the delete button
          if (senderElement.getAttribute("class") == "span_close") {
            e.stopPropagation();
            return true;
          }
          if (checkbox.checked) {
            surroundSelection(schema, spanLabel, spanTitle, spanColor);
          }
        };
      }

      // Listen for when the user has highlighted some text
      // document.onmouseup = function() { surroundSelection("Undefined"); }
    </script>
    <script>
      function barValue(range, sibling) {
        // function used to obtain value for range input
        sibling.value = range.value;
        //var x = document.getElementsByClassName(range.className);
        //var i;
        //for (i=0: i < x.length; i++) {
        //    if(x[i].value != range.value) x[i]
        //}
      }
    </script>

    <script>
      function onlyOne(checkbox) {
        // this function is used for the single-choice setting
        //alert(checkbox.className)
        var x = document.getElementsByClassName(checkbox.className);
        var i;
        for (i = 0; i < x.length; i++) {
          if (x[i].value != checkbox.value) x[i].checked = false;
        }
      }
    </script>

    <script>
      function whetherNone(checkbox) {
        // this function is used to uncheck all the other labels when "None" is checked
        //alert(checkbox.className)
        var x = document.getElementsByClassName(checkbox.className);
        var i;
        for (i = 0; i < x.length; i++) {
          if (checkbox.value == "None" && x[i].value != "None")
            x[i].checked = false;
          if (checkbox.value != "None" && x[i].value == "None")
            x[i].checked = false;
        }
      }
    </script>

    <script>
      function click_to_next() {
        // Gacky code to simulate the submit button as a keyboard event
        // and not have two separate paths to handle keyboard and mouse
        // events
        var e = $.Event("keyup");
        e.key = "ArrowRight";

        get_new_instance(e);
      }

      function click_to_prev() {
        // Gacky code to simulate the submit button as a keyboard event
        // and not have two separate paths to handle keyboard and mouse
        // events
        var e = $.Event("keyup");
        e.key = "ArrowLeft";

        get_new_instance(e);
      }
    </script>

    {{annotation}}

    <script>
      /*
      window.onunload = check_close;
      function check_close() {
          // console.error("session closed");
          var post_req = {
              is_close: "closed"
          }
          post(post_req);
      }
          */
    </script>

    <script>
      // Set the date we're counting down to
      var countDownDate = new Date().getTime();

      // Update the count down every 1 second
      var x = setInterval(function () {
        // Get today's date and time
        var now = new Date().getTime();

        // Find the distance between now and the count down date
        var distance = now - countDownDate;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor(
          (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        var total_seconds = Math.floor(distance / 1000);

        // Output the result in an element with id="timecounter"

        //document.getElementById("timecounter").innerHTML = "Time spent: " + days + "d " + hours + "h "
        //    + minutes + "m " + seconds + "s ";

        // TODO: add configurations for alert message and maximum time spent on each instance
        // If the count down is over, write some text

        var alert_time_each_instance = document.getElementById(
          "alert_time_each_instance"
        ).value;
        if (total_seconds % alert_time_each_instance == 0) {
          //clearInterval(x);
          //document.getElementById("timecounter").innerHTML = "EXPIRED";
          alert(
            "You have spent " + total_seconds + " seconds on this instance"
          );
        }
      }, 1000);
    </script>

    <script>
      // We submit a new post to the same (user/annotate) endpoint
      function post(params) {
        // Package this all up in a post request to the server's updateinstance endpoint
        var post_req = {
          instance_id: instance_id,
        };
        for (var key in params) {
          if (params.hasOwnProperty(key)) {
            post_req[key] = params[key];
          }
        }

        // Extract inputs from the DOM and add to post_req
        $("form input, form select").each(function () {
          var input = $(this);
          var type = input.attr("type");
          var name = input.attr("name");

          if (!name) return; // skip unnamed inputs

          if (type === "checkbox" || type === "radio") {
            if (input.is(":checked")) {
              post_req[name] = true;
            }
          } else if (type === "text" || input.is("select")) {
            post_req[name] = input.val();
          } else {
            console.log("unknown input type:", type);
          }
        });

        // Send the post request and re-render the page with the new instance
        //
        // TODO: fix this the server-client protocol so we're just sending over
        // the new instance data and not the entire page
        fetch("/annotate", {
          method: "POST",
          body: JSON.stringify(post_req),
          credentials: "same-origin",
          headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error("Network response was not ok");
            }
            return response.text(); // Assuming the response is text/html
          })
          .then((html) => {
            // 2. Update the page content
            document.body.innerHTML = html;
            // Add all the listeners back to the new page
            watch_text_boxes();
          })
          .catch((error) => {
            console.error("Error:", error);
            // Handle errors appropriately, e.g., display an error message
          });

        /*

          // The rest of this code assumes you are not using a library.
          // It can be made less wordy if you use one.
          var form = document.createElement("form");
          form.setAttribute("method", "post");
          form.setAttribute("action", "/");

          var hiddenField = document.createElement("input");
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("name", "email");
          hiddenField.setAttribute("value", document.getElementById('username').value);
          form.appendChild(hiddenField);

          for (var key in params) {
              if (params.hasOwnProperty(key)) {
                  var hiddenField = document.createElement("input");
                  hiddenField.setAttribute("type", "hidden");
                  hiddenField.setAttribute("name", key);
                  hiddenField.setAttribute("value", params[key]);

                  form.appendChild(hiddenField);
              }
          }

          // Stuff all the current annotations into attributes for processing on the server side
          $('form input, form select, form textarea').each(
              function(index){
                  var input = $(this);

                  if (input.attr('type') == 'checkbox' || input.attr('type') == 'radio') {
                      if (input.is(":checked")) {
                          // Stuff all the input fields into something for the post
                          var hiddenField = document.createElement("input");
                          hiddenField.setAttribute("type", "hidden");
                          hiddenField.setAttribute("name", input.attr('name'));
                          hiddenField.setAttribute("value", input.attr('value'));
                          form.appendChild(hiddenField);
                      }
                  }
                  else if (input.attr('type') == 'text' || input.attr('type') == 'number') {
                      var hiddenField = document.createElement("input");
                      hiddenField.setAttribute("type", "hidden");
                      hiddenField.setAttribute("name", input.attr('name'));
                      hiddenField.setAttribute("value", input[0].value);
                      form.appendChild(hiddenField);
                  }
                  else if (input.attr('type') == 'range') {
                      var hiddenField = document.createElement("input");
                      hiddenField.setAttribute("type", "hidden");
                      hiddenField.setAttribute("name", input.attr('name'));
                      hiddenField.setAttribute("value", input[0].value);
                      form.appendChild(hiddenField);
                  }
                  else if (input.attr('type') == 'select-one') {
                      //alert(input[0].value)
                      var hiddenField = document.createElement("input");
                      hiddenField.setAttribute("type", "hidden");
                      hiddenField.setAttribute("name", input.attr('name'));
                      hiddenField.setAttribute("value", input[0].value);
                      form.appendChild(hiddenField);
                  }
                  else {
                      console.log("unknown form type: \"" + input.attr('type') + "\"")
                  }
              }
          );
          */

        /*
          // Get all the highlighted text for this instance and marshall that
          // into some kind of representation for the server side
          $(".span_container").first().each(
              function(index) {

                  // we save the outerHTML to accomadate user-defined HTML inputs,
                  // otherwise we just save the plain text
                  if ($(this).parent().parent().attr("name") == "instance_text"){
                      var annotated_spans = $(this).parent().prop('outerHTML');
                  } else {
                      var annotated_spans = $(this).parent().prop('innerHTML');
                  }

                  // Due to the DJ's inability to write decent Javascript, we're
                  // fully punting on the idea of doing label preprocessing here
                  // and instead shuttling the entire HTML of the instance to
                  // the server for python-based processing. The main issue is
                  // figuring out the precise text offsets of the annotated
                  // spans while dealing with nested DOM elements.
                  var hiddenField = document.createElement("input");
                  hiddenField.setAttribute("type", "hidden");
                  hiddenField.setAttribute("name", "span-annotation");
                  hiddenField.setAttribute("value", annotated_spans);
                  form.appendChild(hiddenField);
                  //console.log(annotated_spans)
              }
          );
          */

        //document.body.appendChild(form);
        //form.submit();
      }

      /**
       * Validate if the user has completed each row for multi-rate schema
       */
      function validateForm() {
        var rows = document.querySelectorAll("tr[schema='multirate']");
        for (var i = 0; i < rows.length; i++) {
          var inputs = rows[i].querySelectorAll(
            "input[type='radio'][validation='required']"
          );
          if (inputs.length > 0) {
            var checked = Array.from(inputs).some((input) => input.checked);
          } else {
            var checked = true;
          }

          if (!checked) {
            alert("Please complete all the require fields");
            return false;
          }
        }
        return true;
      }

      /**
       * Validate if the input answers meet certain rules
       * along with any relevant key presses to request a new instance to
       * annotate.
       */
      function validate_answers() {
        // Test whether all the required labels are checked
        var inputs = document.querySelectorAll(
          "input[validation=required_label]"
        );
        for (var i = 0; i < inputs.length; ++i) {
          if (
            inputs[i].getAttribute("validation") == "required_label" &&
            inputs[i].checked == false
          ) {
            // Get the text of the legend element that contains the question
            var legend = inputs[i].closest("fieldset").querySelector("legend");
            var question = legend.textContent;

            // Get the text of the answer
            var neededAnswer = inputs[i].getAttribute("label_name");

            // Generate an alert that shows the question text and the required label
            // so the user knows what they missed
            alert(
              'The question "' +
                question +
                '" requires the label "' +
                neededAnswer +
                '" to be selected to proceed'
            );
            return false;
          }
        }

        // identify all the fieldsets and check if all the required forms are filled
        var fields = document.getElementsByTagName("fieldset");
        for (var i = 0; i < fields.length; ++i) {
          var inputs = fields[i].querySelectorAll(
            "input[validation=required], select[validation=required], textarea[validation=required]"
          );

          // continue if all there's no required inputs in the current field set
          if (inputs.length == 0) {
            continue;
          }
          //var required = true;
          // check if the current form requires inputs
          //if (inputs[0].getAttribute('validation') == 'required'){
          //    required= true;
          //}

          checked_flag = false;
          for (var j = 0; j < inputs.length; ++j) {
            // if a right_label is not selected, display an error msg and return false
            //if (inputs[j].getAttribute('validation') == 'right_label' && inputs[j].checked == false) {
            //alert(inputs[j].name + " must be selected to proceed");
            //    return false;
            //}
            // if the input is for a span annotation schema, check if the at least some span is annotated or if the
            // bad_text label is selected
            if (inputs[j].getAttribute("for_span") == "True") {
              //alert($(".span_container").length);
              if ($(".span_container").length > 0) {
                checked_flag = true;
                break;
              } else if (
                inputs[j].name.slice(-8) == "bad_text" &&
                inputs[j].checked == true
              ) {
                checked_flag = true;
                break;
              }
            }

            // if any of the labels is checked, set checked_flag as true;
            if (
              inputs[j].getAttribute("for_span") != "True" &&
              inputs[j].checked == true
            ) {
              checked_flag = true;
              break;
            }

            // if the input_type is number, text, select or textarea, check if it's empty
            // todo: the current way might not work well if there are mixed textinput and radio buttons under a sample fieldset
            if (
              inputs[j].type == "text" ||
              inputs[j].tagName == "TEXTAREA" ||
              inputs[j].type == "number" ||
              inputs[j].type == "select-one"
            ) {
              if (inputs[j].value.length == 0) {
                alert(inputs[j].name + " must be completed to proceed");
                return false;
              } else {
                checked_flag = true;
              }
            }
          }

          // Get the text of the legend element that contains the question
          //
          // TODO: check that this works with questions for the text input fields
          var legend = inputs[i].closest("fieldset").querySelector("legend");
          var question = legend.textContent;

          // if this form requires inputs, but nothing is checked, display an error msg and return false
          if (checked_flag == false) {
            alert("You must answer the following item to proceed: " + question);
            return false;
          }
          //alert(instance_obj.id)
        }
        return true;
      }

      /**
       * Sends the current state of the instance's annotation to the server,
       * along with any relevant key presses to request a new instance to
       * annotate.
       */
      function get_new_instance(event) {
        var x = event.key;
        var action = "";
        var ism = "";

        //console.log(x)
        //console.log(firstname)
        //console.log(lastname)
        if (x == "ArrowLeft") {
          // Spacebar
          action = "prev_instance";
        } else if (x == "ArrowRight") {
          //console.log("validateForm", validateForm())
          //console.log("validate_answers", validate_answers())
          if (validateForm() == true && validate_answers() == true) {
            action = "next_instance";
          } else {
            return;
          }
        } else {
          // console.log("Unknown key press", event)
          return;
        }

        var instance_id = document.getElementById("instance_id").value;
        var time_string = document.getElementById("timecounter").innerHTML; //get time spent on this instance
        //time_string = '-1'
        var post_req = {
          label: ism,
          action: action,
          instance_id: instance_id,
          behavior_time_string: time_string,
        };

        console.log("post_req: ", post_req);
        // Sends the post message to the server which will let us update the
        // currently displayed content
        post(post_req);
      }
    </script>

    <script>
      $(document).ready(function () {
        $('[data-toggle="tooltip"]').tooltip();
      });
    </script>

    {{var_elems | safe}}

    <!-- Header navigation bar -->
    <nav
      class="navbar sticky-top shadow-sm"
      style="
        background-color: var(--primary-color);
        padding: 0.75rem 1rem;
        margin-bottom: 1.5rem;
      "
    >
      <div class="container-fluid d-flex align-items-center">
        <!-- Task name (left aligned) -->
        <div class="navbar-brand">
          <span
            class="fw-bold"
            style="color: var(--light-color); font-size: 1.25rem"
            >{{annotation_task_name}}</span
          >
        </div>

        <!-- Middle section with three elements -->
        <div
          class="d-flex align-items-center justify-content-center flex-grow-1 gap-4"
        >
          <!-- 1. Annotation codebook link -->
          <div>{{annotation_codebook}}</div>

          <!-- 2. Progress counter -->
          <div
            class="d-flex align-items-center"
            style="color: var(--light-color); margin-right: 40px"
          >
            <span
              >Progress:
              <span class="fw-medium">{{finished}}/{{total_count}}</span></span
            >
          </div>

          <!-- 3. Jump to item form -->
          <div style="margin-left: 40px">
            <form
              action="/go_to"
              method="post"
              class="d-flex align-items-center"
            >
              <input
                type="hidden"
                name="firstname"
                id="a"
                value="{{firstname}}"
              />
              <input
                type="hidden"
                name="lastname"
                id="b"
                value="{{lastname}}"
              />
              <input type="hidden" name="email" id="c" value="{{username}}" />
              <input type="hidden" name="src" id="src" value="go_to" />
              <label
                for="go_to"
                class="me-2"
                style="color: var(--light-color); margin-bottom: 0"
                >Go to:</label
              >
              <input
                type="number"
                name="go_to"
                id="go_to"
                class="form-control form-control-sm me-2"
                style="
                  width: 70px;
                  height: 31px;
                  border: none;
                  border-radius: var(--radius);
                "
                value=""
                onfocusin="user_input()"
                onfocusout="user_input_leave()"
                max="{{total_count}}"
                min="0"
                required
              />
              <button
                type="submit"
                class="shadcn-button"
                style="
                  height: 31px;
                  line-height: 1;
                  padding: 0 0.75rem;
                  background-color: var(--light-color);
                  color: var(--primary-color);
                  border: none;
                "
              >
                Go
              </button>
            </form>
          </div>
        </div>

        <!-- User info and logout (right aligned) -->
        <div
          class="d-flex align-items-center"
          style="
            background-color: rgba(255, 255, 255, 0.15);
            padding: 0.5rem 1rem;
            border-radius: var(--radius);
          "
        >
          <div class="me-3" style="color: var(--light-color)">
            <span
              >Logged in as <span class="fw-medium">{{username}}</span></span
            >
          </div>
          <div
            class="border-start"
            style="
              padding-left: 20px;
              height: 24px;
              display: flex;
              align-items: center;
            "
          >
            <a
              href="/logout"
              class="shadcn-button"
              style="
                background-color: var(--light-color);
                color: var(--primary-color);
                height: auto;
                padding: 0.25rem 0.75rem !important;
                font-size: 0.875rem;
                min-width: 60px;
                text-align: center;
                border: none;
                text-decoration: none;
              "
              >Logout</a
            >
          </div>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div id="task_layout" class="shadcn-card mb-4">
        <div class="shadcn-card-content">
          <!--- LAYOUT GOES BELOW HERE --->

          {{ TASK_LAYOUT }}

          <!--- LAYOUT GOES ABOVE  --->
        </div>
      </div>
      <!-- Test -->
      <!-- <div id="task_layout" class="shadcn-card mb-4">
        <div class="shadcn-card-content">
          <strong>AI Label Suggestion</strong>
          <div>{{ ai }}</div>
        </div>
      </div> -->
      <!-- Test -->

      <div class="my-4">
        <!-- Reorganized button layout with 3 columns -->
        <div class="d-flex justify-content-between align-items-center">
          <!-- Statistics button (left) -->
          <div>
            <a
              role="button"
              href="#"
              class="shadcn-button shadcn-button-outline openbtn"
              target_id="Statpanel"
              width="475px"
              onclick="openNav(this.getAttribute('target_id'),this.getAttribute('width'))"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                fill="currentColor"
                class="bi bi-bar-chart-line me-1"
                viewBox="0 0 16 16"
              >
                <path
                  d="M11 2a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v12h.5a.5.5 0 0 1 0 1H.5a.5.5 0 0 1 0-1H1v-3a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v3h1V7a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v7h1V2zm1 12h2V2h-2v12zm-3 0V7H7v7h2zm-5 0v-3H2v3h2z"
                />
              </svg>
              Statistics
            </a>
          </div>

          <!-- Previous/Next buttons (center) -->
          <div>
            <a
              class="shadcn-button shadcn-button-outline me-2"
              href="#"
              role="button"
              onclick="click_to_prev()"
              style="vertical-align: middle"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                fill="currentColor"
                class="bi bi-arrow-left"
                viewBox="0 0 16 16"
                style="
                  display: inline-block;
                  vertical-align: middle;
                  margin-right: 0.25rem;
                "
              >
                <path
                  fill-rule="evenodd"
                  d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"
                />
              </svg>
              <span style="display: inline-block; vertical-align: middle"
                >Previous</span
              >
            </a>
            <a
              class="shadcn-button shadcn-button-primary"
              href="#"
              role="button"
              onclick="click_to_next()"
              style="vertical-align: middle"
            >
              <span style="display: inline-block; vertical-align: middle"
                >Next</span
              >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                fill="currentColor"
                class="bi bi-arrow-right"
                viewBox="0 0 16 16"
                style="
                  display: inline-block;
                  vertical-align: middle;
                  margin-left: 0.25rem;
                "
              >
                <path
                  fill-rule="evenodd"
                  d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"
                />
              </svg>
            </a>
          </div>

          <!-- Help button (right) -->
          <div>
            <a
              role="button"
              href="#"
              class="shadcn-button shadcn-button-outline openbtn"
              target_id="mySidepanel"
              onclick="openNav(this.getAttribute('target_id'))"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                fill="currentColor"
                class="bi bi-question-circle me-1"
                viewBox="0 0 16 16"
              >
                <path
                  d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"
                />
                <path
                  d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"
                />
              </svg>
              Help
            </a>
          </div>
        </div>
      </div>

      <hr style="color: var(--border)" />
      <footer
        class="py-2 text-center"
        style="font-size: 0.75rem; color: var(--muted-foreground)"
      >
        Copyright &copy; 2025
        <a
          href="https://blablablab.si.umich.edu/"
          style="color: var(--primary); text-decoration: none"
          >Blablablab</a
        >
        <span class="mx-2">|</span>
        <a
          href="https://github.com/davidjurgens/potato"
          style="color: var(--primary); text-decoration: none"
          >Chat with us on GitHub</a
        >
        <span class="mx-2">|</span>
        <a
          href="https://github.com/davidjurgens/potato#cite-us"
          style="color: var(--primary); text-decoration: none"
          >Cite Us</a
        >
      </footer>
    </div>

    <script>
      /* Set the width of the sidebar to 250px (show it) */
      function openNav(target_id, width = "350px") {
        document.getElementById(target_id).style.width = width;
      }

      /* Set the width of the sidebar to 0 (hide it) */
      function closeNav(target_id) {
        document.getElementById(target_id).style.width = "0";
      }

      function closeNav2(target_id) {
        // document.getElementById(target_id).style.height = "20px";
        console.error(document.getElementById(target_id).style.display);
        if (
          document.getElementById(target_id).style.display == "block" ||
          document.getElementById(target_id).style.display == ""
        ) {
          document.getElementById(target_id).style.display = "none";
          localStorage.setItem("show_instructions", "false");
        } else {
          document.getElementById(target_id).style.display = "block";
          localStorage.setItem("show_instructions", "true");
        }
      }

      /* Keep the instructions hidden/shown across instance transitions based on
         what the user had selected */
      window.addEventListener("load", function () {
        var show = localStorage.getItem("show_instructions");
        if (document.getElementById("instructions")) {
          if (show === "true") {
            document.getElementById("instructions").style.display = "block";
          } else {
            document.getElementById("instructions").style.display = "none";
          }
        }
      });

      function watch_text_boxes() {
        let timer;
        const waitTime = 1000;

        var text_boxes = document.querySelectorAll("input[type=text]");
        for (var i = 0; i < text_boxes.length; i++) {
          //console.log('adding event listener to text box');
          //console.log(text_boxes[i]);
          text_boxes[i].addEventListener("input", function (event) {
            console.log("text box input event");
            clearTimeout(timer);
            timer = setTimeout(() => {
              registerTextAnnotation(event.target);
            }, waitTime);
          });
        }

        var text_areas = document.querySelectorAll("textarea");
        //console.log('num text_areas: ' + text_areas.length);
        for (var i = 0; i < text_areas.length; i++) {
          //console.log('adding event listener to text area');
          //console.dir(text_areas[i]);
          text_areas[i].addEventListener("input", function (event) {
            //console.log('text area input event')
            clearTimeout(timer);
            timer = setTimeout(() => {
              registerTextAnnotation(event.target);
            }, waitTime);
          });
        }
      }
      watch_text_boxes();
    </script>
  </body>
</html>