aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/p/scripts/main.js
blob: d075686171eb3af19469e75b98968fcaa6b3291a (plain) (blame)
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
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0
'use strict';

// <Polyfills>
if (!document.scrollingElement) document.scrollingElement = document.documentElement;
if (!NodeList.prototype.forEach) NodeList.prototype.forEach = Array.prototype.forEach;
if (!Element.prototype.matches) {
	Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
	Element.prototype.closest = function (s) {
		let el = this;
		do {
			if (el.matches(s)) return el;
			el = el.parentElement;
		} while (el);
		return null;
	};
}
if (!Element.prototype.remove) Element.prototype.remove = function () { if (this.parentNode) this.parentNode.removeChild(this); };
// </Polyfills>

// <Utils>
function xmlHttpRequestJson(req) {
	let json = req.response;
	if (req.responseType !== 'json') {	// IE11
		try {
			json = JSON.parse(req.responseText);
		} catch (ex) {
			json = null;
		}
	}
	return json;
}
// </Utils>

// <Global context>
/* eslint-disable no-var */
var context;
/* eslint-enable no-var */

(function parseJsonVars() {
	const jsonVars = document.getElementById('jsonVars');
	const json = JSON.parse(jsonVars.innerHTML);
	jsonVars.outerHTML = '';
	context = json.context;
	context.ajax_loading = false;
	context.i18n = json.i18n;
	context.shortcuts = json.shortcuts;
	context.urls = json.urls;
	context.icons = json.icons;
	context.icons.read = decodeURIComponent(context.icons.read);
	context.icons.unread = decodeURIComponent(context.icons.unread);
	context.extensions = json.extensions;
}());
// </Global context>

function badAjax(reload) {
	openNotification(context.i18n.notif_request_failed, 'bad');
	if (reload) {
		setTimeout(function () { location.reload(); }, 2000);
	}
	return true;
}

function needsScroll(elem) {
	const winBottom = document.scrollingElement.scrollTop + document.scrollingElement.clientHeight;
	const elemTop = elem.offsetParent.offsetTop + elem.offsetTop;
	const elemBottom = elemTop + elem.offsetHeight;
	if (elemTop < document.scrollingElement.scrollTop || elemBottom > winBottom) {
		return elemTop - (document.scrollingElement.clientHeight / 2);
	}
	return 0;
}

function str2int(str) {
	if (!str) {
		return 0;
	}
	return parseInt(str.replace(/\D/g, ''), 10) || 0;
}

function numberFormat(nStr) {
	if (nStr < 0) {
		return 0;
	}
	// http://www.mredkj.com/javascript/numberFormat.html
	nStr += '';
	const x = nStr.split('.');
	const x2 = x.length > 1 ? '.' + x[1] : '';
	const rgx = /(\d+)(\d{3})/;
	let x1 = x[0];
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1 $2');
	}
	return x1 + x2;
}

function incLabel(p, inc, spaceAfter) {
	const i = str2int(p) + inc;
	return i > 0 ? ((spaceAfter ? '' : ' ') + '(' + numberFormat(i) + ')' + (spaceAfter ? ' ' : '')) : '';
}

function incUnreadsFeed(article, feed_id, nb) {
	// Update unread: feed
	let elem = document.getElementById(feed_id);
	let feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
	const feed_priority = elem ? str2int(elem.getAttribute('data-priority')) : 0;
	if (elem) {
		elem.setAttribute('data-unread', feed_unreads + nb);
		elem = elem.querySelector('.item-title');
		if (elem) {
			elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
		}
	}

	// Update unread: category
	elem = document.getElementById(feed_id);
	elem = elem ? elem.closest('.category') : null;
	if (elem) {
		feed_unreads = str2int(elem.getAttribute('data-unread'));
		elem.setAttribute('data-unread', feed_unreads + nb);
		elem = elem.querySelector('.title');
		if (elem) {
			elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
		}
	}

	// Update unread: all
	if (feed_priority > 0) {
		elem = document.querySelector('#aside_feed .all .title');
		if (elem) {
			feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
			elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
		}
	}

	// Update unread: important
	if (feed_priority >= 20) {
		elem = document.querySelector('#aside_feed .important .title');
		if (elem) {
			feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
			elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
		}
	}

	// Update unread: favourites
	if (article && article.closest('div').classList.contains('favorite')) {
		elem = document.querySelector('#aside_feed .favorites .title');
		if (elem) {
			feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
			elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
		}
	}

	let isCurrentView = false;
	// Update unread: title
	document.title = document.title.replace(/^((?:\([\s0-9]+\) )?)/, function (m, p1) {
		const feed = document.getElementById(feed_id);
		if (article || (feed && feed.closest('.active'))) {
			isCurrentView = true;
			return incLabel(p1, nb, true);
		} else if (document.querySelector('.all.active')) {
			isCurrentView = feed_priority > 0;
			return incLabel(p1, feed_priority > 0 ? nb : 0, true);
		} else {
			return p1;
		}
	});
	return isCurrentView;
}

function incUnreadsTag(tag_id, nb) {
	let t = document.getElementById(tag_id);
	if (t) {
		const unreads = str2int(t.getAttribute('data-unread'));
		t.setAttribute('data-unread', unreads + nb);
		t.querySelector('.item-title').setAttribute('data-unread', numberFormat(unreads + nb));
	}
	t = document.querySelector('.category.tags .title');
	if (t) {
		const unreads = str2int(t.getAttribute('data-unread'));
		t.setAttribute('data-unread', numberFormat(unreads + nb));
	}
}

function removeArticle(div) {
	if (!div || div.classList.contains('not_read') || (context.auto_mark_article && div.classList.contains('active'))) {
		return;
	}
	let scrollTop = box_to_follow.scrollTop;
	let dirty = false;
	const p = div.previousElementSibling;
	const n = div.nextElementSibling;
	if (p && p.classList.contains('day') && n && n.classList.contains('day')) {
		scrollTop -= p.offsetHeight;
		dirty = true;
		p.remove();
	}
	if (div.offsetHeight > 0 && div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < scrollTop) {
		scrollTop -= div.offsetHeight;
		dirty = true;
	}
	div.remove();
	if (dirty) {
		box_to_follow.scrollTop = scrollTop;
	}
}

const pending_entries = {};
let mark_read_queue = [];

function send_mark_read_queue(queue, asRead, callback) {
	if (!queue || queue.length === 0) {
		if (callback) {
			callback();
		}
		return;
	}
	const req = new XMLHttpRequest();
	req.open('POST', '.?c=entry&a=read' + (asRead ? '' : '&is_read=0'), true);
	req.responseType = 'json';
	req.onerror = function (e) {
		for (let i = queue.length - 1; i >= 0; i--) {
			delete pending_entries['flux_' + queue[i]];
		}
		badAjax(this.status == 403);
	};
	req.onload = function (e) {
		if (this.status != 200) {
			return req.onerror(e);
		}
		const json = xmlHttpRequestJson(this);
		if (!json) {
			return req.onerror(e);
		}
		for (let i = queue.length - 1; i >= 0; i--) {
			const div = document.getElementById('flux_' + queue[i]);
			const myIcons = context.icons;
			let inc = 0;
			if (div.classList.contains('not_read')) {
				div.classList.remove('not_read');
				div.querySelectorAll('a.read').forEach(function (a) {
					a.href = a.href.replace('&is_read=0', '') + '&is_read=1';
				});
				div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.read; });
				inc--;
				if (context.auto_remove_article) {
					removeArticle(div);
				}
			} else {
				div.classList.add('not_read');
				div.classList.add('keep_unread');	// Split for IE11
				div.querySelectorAll('a.read').forEach(function (a) {
					a.href = a.href.replace('&is_read=1', '');
				});
				div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.unread; });
				inc++;
			}
			const feed_link = div.querySelector('.website > a, a.website');
			if (feed_link) {
				const feed_url = feed_link.href;
				const feed_id = feed_url.substr(feed_url.lastIndexOf('f_'));
				incUnreadsFeed(div, feed_id, inc);
			}
			delete pending_entries['flux_' + queue[i]];
		}
		faviconNbUnread();
		if (json.tags) {
			const tagIds = Object.keys(json.tags);
			for (let i = tagIds.length - 1; i >= 0; i--) {
				const tagId = tagIds[i];
				incUnreadsTag(tagId, (asRead ? -1 : 1) * json.tags[tagId].length);
			}
		}
		toggle_bigMarkAsRead_button();
		onScroll();
		if (callback) {
			callback();
		}
	};
	req.setRequestHeader('Content-Type', 'application/json');
	req.send(JSON.stringify({
		ajax: true,
		_csrf: context.csrf,
		id: queue,
	}));
}

let send_mark_read_queue_timeout = 0;

function send_mark_queue_tick(callback) {
	send_mark_read_queue_timeout = 0;
	const queue = mark_read_queue.slice(0);
	mark_read_queue = [];
	send_mark_read_queue(queue, true, callback);
}
const delayedFunction = send_mark_queue_tick;

function delayedClick(a) {
	if (a) {
		delayedFunction(function () { a.click(); });
	}
}

function mark_read(div, only_not_read, asBatch) {
	if (!div || !div.id || context.anonymous ||
		(only_not_read && !div.classList.contains('not_read'))) {
		return false;
	}
	if (pending_entries[div.id]) {
		return false;
	}
	pending_entries[div.id] = true;

	const asRead = div.classList.contains('not_read');
	const entryId = div.id.replace(/^flux_/, '');
	if (asRead && asBatch) {
		mark_read_queue.push(entryId);
		if (send_mark_read_queue_timeout == 0) {
			send_mark_read_queue_timeout = setTimeout(function () { send_mark_queue_tick(null); }, 1000);
		}
	} else {
		const queue = [entryId];
		send_mark_read_queue(queue, asRead);
	}
}

function mark_previous_read(div) {
	while (div) {
		mark_read(div, true, true);
		div = div.previousElementSibling;
	}
}

function mark_favorite(div) {
	if (!div) {
		return false;
	}

	const a = div.querySelector('a.bookmark');
	const url = a ? a.href : '';
	if (!url) {
		return false;
	}

	if (pending_entries[div.id]) {
		return false;
	}
	pending_entries[div.id] = true;

	const req = new XMLHttpRequest();
	req.open('POST', url, true);
	req.responseType = 'json';
	req.onerror = function (e) {
		delete pending_entries[div.id];
		badAjax(this.status == 403);
	};
	req.onload = function (e) {
		if (this.status != 200) {
			return req.onerror(e);
		}
		const json = xmlHttpRequestJson(this);
		if (!json) {
			return req.onerror(e);
		}
		let inc = 0;
		if (div.classList.contains('favorite')) {
			div.classList.remove('favorite');
			inc--;
		} else {
			div.classList.add('favorite');
			inc++;
		}
		div.querySelectorAll('a.bookmark').forEach(function (a) { a.href = json.url; });
		div.querySelectorAll('a.bookmark > .icon').forEach(function (img) { img.outerHTML = json.icon; });

		const favourites = document.querySelector('#aside_feed .favorites .title');
		if (favourites) {
			favourites.textContent = favourites.textContent.replace(/((?: \([\s0-9]+\))?\s*)$/, function (m, p1) {
				return incLabel(p1, inc, false);
			});
		}

		if (div.classList.contains('not_read')) {
			const elem = document.querySelector('#aside_feed .favorites .title');
			const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
			if (elem) {
				elem.setAttribute('data-unread', numberFormat(feed_unreads + inc));
			}
		}

		delete pending_entries[div.id];
	};
	req.setRequestHeader('Content-Type', 'application/json');
	req.send(JSON.stringify({
		ajax: true,
		_csrf: context.csrf,
	}));
}

const freshrssOpenArticleEvent = document.createEvent('Event');
freshrssOpenArticleEvent.initEvent('freshrss:openArticle', true, true);

function toggleContent(new_active, old_active, skipping) {
	// If skipping, move current without activating or marking as read
	if (!new_active) {
		return;
	}

	if (context.does_lazyload && !skipping) {
		new_active.querySelectorAll('img[data-original], iframe[data-original]').forEach(function (el) {
			el.src = el.getAttribute('data-original');
			el.removeAttribute('data-original');
		});
	}

	if (old_active !== new_active) {
		if (!skipping) {
			new_active.classList.add('active');
		}
		new_active.classList.add('current');
		if (old_active) {
			old_active.classList.remove('active');
			old_active.classList.remove('current');	// Split for IE11
			if (context.auto_remove_article) {
				removeArticle(old_active);
			}
		}
	} else {
		new_active.classList.toggle('active');
	}

	const relative_move = context.current_view === 'global';
	const box_to_move = relative_move ? document.getElementById('panel') : document.scrollingElement;

	if (context.sticky_post) {	// Stick the article to the top when opened
		const prev_article = new_active.previousElementSibling;
		const nav_menu = document.querySelector('.nav_menu');
		let nav_menu_height = 0;

		if (nav_menu && (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky')) {
			nav_menu_height = nav_menu.offsetHeight;
		}

		let new_pos = new_active.offsetParent.offsetTop + new_active.offsetTop - nav_menu_height;

		if (prev_article && prev_article.offsetParent && new_active.offsetTop - prev_article.offsetTop <= 150) {
			new_pos = prev_article.offsetParent.offsetTop + prev_article.offsetTop - nav_menu_height;
			if (relative_move) {
				new_pos -= box_to_move.offsetTop;
			}
		}

		if (skipping) {
			// when skipping, this feels more natural if it’s not so near the top
			new_pos -= document.body.clientHeight / 4;
		}

		box_to_move.scrollTop = new_pos;
	}

	if (new_active.classList.contains('active') && !skipping) {
		if (context.auto_mark_article) {
			mark_read(new_active, true, true);
		}
		new_active.dispatchEvent(freshrssOpenArticleEvent);
	}
	onScroll();
}

function prev_entry(skipping) {
	const old_active = document.querySelector('.flux.current');
	let new_active = old_active;
	if (new_active) {
		do new_active = new_active.previousElementSibling;
		while (new_active && !new_active.classList.contains('flux'));
		if (!new_active) {
			prev_feed();
		}
	} else {
		new_active = document.querySelector('.flux');
	}
	if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
		mark_read(new_active, true, true);
	}
	toggleContent(new_active, old_active, skipping);
}

function next_entry(skipping) {
	const old_active = document.querySelector('.flux.current');
	let new_active = old_active;
	if (new_active) {
		do new_active = new_active.nextElementSibling;
		while (new_active && !new_active.classList.contains('flux'));
		if (!new_active) {
			next_feed();
		}
	} else {
		new_active = document.querySelector('.flux');
	}
	if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
		mark_read(new_active, true, true);
	}
	toggleContent(new_active, old_active, skipping);
}

function next_unread_entry(skipping) {
	const old_active = document.querySelector('.flux.current');
	let new_active = old_active;
	if (new_active) {
		do new_active = new_active.nextElementSibling;
		while (new_active && !new_active.classList.contains('not_read'));
		if (!new_active) {
			next_feed();
		}
	} else {
		new_active = document.querySelector('.not_read');
	}
	if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
		mark_read(new_active, true, true);
	}
	toggleContent(new_active, old_active, skipping);
}

function prev_feed() {
	let found = false;
	let adjacent = null;
	const feeds = document.querySelectorAll('#aside_feed .feed');
	for (let i = feeds.length - 1; i >= 0; i--) {
		const feed = feeds[i];
		if (feed.classList.contains('active')) {
			found = true;
			continue;
		}
		if (!found) {
			continue;
		}
		if (getComputedStyle(feed).display === 'none') {
			continue;
		}
		if (feed.dataset.unread != 0) {
			return delayedClick(feed.querySelector('a.item-title'));
		} else if (adjacent === null) {
			adjacent = feed;
		}
	}
	if (found) {
		delayedClick(adjacent.querySelector('a.item-title'));
	} else {
		last_feed();
	}
}

function next_feed() {
	let found = false;
	let adjacent = null;
	const feeds = document.querySelectorAll('#aside_feed .feed');
	for (let i = 0; i < feeds.length; i++) {
		const feed = feeds[i];
		if (feed.classList.contains('active')) {
			found = true;
			continue;
		}
		if (!found) {
			continue;
		}
		if (getComputedStyle(feed).display === 'none') {
			continue;
		}
		if (feed.dataset.unread != 0) {
			return delayedClick(feed.querySelector('a.item-title'));
		} else if (adjacent === null) {
			adjacent = feed;
		}
	}
	if (found) {
		delayedClick(adjacent.querySelector('a.item-title'));
	} else {
		first_feed();
	}
}

function first_feed() {
	const a = document.querySelector('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
	delayedClick(a);
}

function last_feed() {
	const links = document.querySelectorAll('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
	if (links && links.length > 0) {
		delayedClick(links[links.length - 1]);
	}
}

function prev_category() {
	const active_cat = document.querySelector('#aside_feed .category.active');
	if (active_cat) {
		let cat = active_cat;
		do cat = cat.previousElementSibling;
		while (cat && getComputedStyle(cat).display === 'none');
		if (cat) {
			delayedClick(cat.querySelector('a.title'));
		}
	} else {
		last_category();
	}
}

function next_category() {
	const active_cat = document.querySelector('#aside_feed .category.active');
	if (active_cat) {
		let cat = active_cat;
		do cat = cat.nextElementSibling;
		while (cat && getComputedStyle(cat).display === 'none');
		if (cat) {
			delayedClick(cat.querySelector('a.title'));
		}
	} else {
		first_category();
	}
}

function next_unread_category() {
	const active_cat = document.querySelector('#aside_feed .category.active');
	if (active_cat) {
		let cat = active_cat;
		do cat = cat.nextElementSibling;
		while (cat && cat.getAttribute('data-unread') <= 0);
		if (cat) {
			delayedClick(cat.querySelector('a.title'));
		}
	} else {
		first_category();
	}
}

function first_category() {
	const a = document.querySelector('#aside_feed .category:not([data-unread="0"]) a.title');
	delayedClick(a);
}

function last_category() {
	const links = document.querySelectorAll('#aside_feed .category:not([data-unread="0"]) a.title');
	if (links && links.length > 0) {
		delayedClick(links[links.length - 1]);
	}
}

function collapse_entry() {
	const flux_current = document.querySelector('.flux.current');
	toggleContent(flux_current, flux_current, false);
}

function toggle_media() {
	const media = document.querySelector('.flux.current video,.flux.current audio');
	if (media === null) {
		return;
	}
	if (media.paused) {
		media.play();
	} else {
		media.pause();
	}
}

function user_filter(key) {
	const filter = document.getElementById('dropdown-query');
	const filters = filter.parentElement.querySelectorAll('.dropdown-menu > .query > a');
	if (typeof key === 'undefined') {
		if (!filters.length) {
			return;
		}
		// Display the filter div
		location.hash = filter.id;
		// Force scrolling to the filter div
		const scroll = needsScroll(document.querySelector('.header'));
		if (scroll !== 0) {
			document.scrollingElement.scrollTop = scroll;
		}
		// Force the key value if there is only one action, so we can trigger it automatically
		if (filters.length === 1) {
			key = 1;
		} else {
			return;
		}
	}
	// Trigger selected share action
	key = parseInt(key);
	if (key <= filters.length) {
		filters[key - 1].click();
	}
}

function auto_share(key) {
	const share = document.querySelector('.flux.current.active .dropdown-target[id^="dropdown-share"]');
	if (!share) {
		return;
	}
	const shares = share.parentElement.querySelectorAll('.dropdown-menu .item a');
	if (typeof key === 'undefined') {
		// Display the share div
		location.hash = share.id;
		// Force scrolling to the share div
		const scrollTop = needsScroll(share.closest('.bottom'));
		if (scrollTop !== 0) {
			document.scrollingElement.scrollTop = scrollTop;
		}
		// Force the key value if there is only one action, so we can trigger it automatically
		if (shares.length === 1) {
			key = 1;
		} else {
			return;
		}
	}
	// Trigger selected share action and hide the share div
	key = parseInt(key);
	if (key <= shares.length) {
		shares[key - 1].click();
		share.parentElement.querySelector('.dropdown-menu + a.dropdown-close').click();
	}
}

let box_to_follow;

function onScroll() {
	if (!box_to_follow) {
		return;
	}
	if (context.auto_mark_scroll) {
		const hidden_px = -5; // negative = pixels over the edge
		const minTop = hidden_px + box_to_follow.scrollTop;
		document.querySelectorAll('.not_read:not(.keep_unread)').forEach(function (div) {
			if (div.offsetHeight > 0 &&
					div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < minTop) {
				mark_read(div, true, true);
			}
		});
	}
	let streamFooter;
	if (context.auto_load_more && (streamFooter = document.getElementById('stream-footer'))) {
		if (box_to_follow.offsetHeight > 0 &&
			box_to_follow.scrollTop + box_to_follow.offsetHeight + (window.innerHeight / 2) >= streamFooter.offsetTop) {
			// Too close to the last pre-loaded article
			load_more_posts();
		} else {
			const after = document.querySelectorAll('.flux.current ~ .flux').length;
			if (after > 0 && after <= 5) {
				// Too few pre-loaded articles
				load_more_posts();
			}
		}
	}
}

let lastScroll = 0;	// Throttle
let timerId = 0;
function debouncedOnScroll() {
	clearTimeout(timerId);
	if (lastScroll + 500 < Date.now()) {
		lastScroll = Date.now();
		onScroll();
	} else {
		timerId = setTimeout(onScroll, 500);
	}
}

function init_posts() {
	if (context.auto_load_more || context.auto_mark_scroll || context.auto_remove_article) {
		box_to_follow = context.current_view === 'global' ? document.getElementById('panel') : document.scrollingElement;
		(box_to_follow === document.scrollingElement ? window : box_to_follow).onscroll = debouncedOnScroll;
		window.addEventListener('resize', debouncedOnScroll);
		onScroll();
	}

	if (!navigator.share && document.styleSheets.length > 0) {
		// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
		// do not show the menu entry if browser does not support navigator.share
		document.styleSheets[0].insertRule(
			'button.as-link[data-type="web-sharing-api"] {display: none !important;}',
			document.styleSheets[0].cssRules.length
		);
	}
}

function rememberOpenCategory(category_id, isOpen) {
	if (context.display_categories === 'remember') {
		const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
		if (isOpen) {
			open_categories[category_id] = true;
		} else {
			delete open_categories[category_id];
		}
		localStorage.setItem('FreshRSS_open_categories', JSON.stringify(open_categories));
	}
}

function openCategory(category_id) {
	const category_element = document.getElementById(category_id);
	if (!category_element) return;
	category_element.querySelector('.tree-folder-items').classList.add('active');
	const img = category_element.querySelector('a.dropdown-toggle img');
	if (!img) return;
	img.src = img.src.replace('/icons/down.', '/icons/up.');
	img.alt = '🔼';
}

function loadJs(name) {
	if (!document.getElementById(name)) {
		const script = document.createElement('script');
		script.setAttribute('id', name);
		script.setAttribute('src', '../scripts/' + name + '?' + context.mtime[name]);
		script.setAttribute('defer', 'defer');
		script.setAttribute('async', 'async');
		document.head.appendChild(script);
	}
}

function init_column_categories() {
	if (context.current_view !== 'normal' && context.current_view !== 'reader') {
		return;
	}

	// Restore sidebar scroll position
	document.getElementById('sidebar').scrollTop = +sessionStorage.getItem('FreshRSS_sidebar_scrollTop');

	// Restore open categories
	if (context.display_categories === 'remember') {
		const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
		Object.keys(open_categories).forEach(function (category_id) {
			openCategory(category_id);
		});
	}

	document.getElementById('aside_feed').onclick = function (ev) {
		let a = ev.target.closest('.tree-folder > .tree-folder-title > a.dropdown-toggle');
		if (a) {
			const icon = a.querySelector('.icon');
			const category_id = a.closest('.category').id;
			if (icon.alt === '🔽' || icon.innerHTML === '🔽') {
				if (icon.src) {
					icon.src = icon.src.replace('/icons/down.', '/icons/up.');
					icon.alt = '🔼';
				} else {
					icon.innerHTML = '🔼';
				}
				rememberOpenCategory(category_id, true);
			} else {
				if (icon.src) {
					icon.src = icon.src.replace('/icons/up.', '/icons/down.');
					icon.alt = '🔽';
				} else {
					icon.innerHTML = '🔽';
				}
				rememberOpenCategory(category_id, false);
			}

			const ul = a.closest('li').querySelector('.tree-folder-items');
			let nbVisibleItems = 0;
			for (let i = ul.children.length - 1; i >= 0; i--) {
				if (ul.children[i].offsetHeight) {
					nbVisibleItems++;
				}
			}
			ul.classList.toggle('active');
			// CSS transition does not work on max-height:auto
			ul.style.maxHeight = ul.classList.contains('active') ? (nbVisibleItems * 4) + 'em' : 0;
			return false;
		}

		a = ev.target.closest('.tree-folder-items > .feed .dropdown-toggle');
		if (a) {
			loadJs('extra.js');
			loadJs('feed.js');
			const itemId = a.closest('.item').id;
			const templateId = itemId.substring(0, 2) === 't_' ? 'tag_config_template' : 'feed_config_template';
			const id = itemId.substr(2);
			const feed_web = a.getAttribute('data-fweb') || '';
			const div = a.parentElement;
			const dropdownMenu = div.querySelector('.dropdown-menu');
			const template = document.getElementById(templateId)
				.innerHTML.replace(/------/g, id).replace('http://example.net/', feed_web);
			if (!dropdownMenu) {
				a.href = '#dropdown-' + id;
				div.querySelector('.dropdown-target').id = 'dropdown-' + id;
				div.insertAdjacentHTML('beforeend', template);
				if (feed_web == '') {
					const website = div.querySelector('.item.link.website');
					if (website) {
						website.remove();
					}
				}
				const b = div.querySelector('button.confirm');
				if (b) {
					b.disabled = false;
				}
			} else if (getComputedStyle(dropdownMenu).display === 'none') {
				const id2 = div.closest('.item').id.substr(2);
				a.href = '#dropdown-' + id2;
			} else {
				a.href = '#close';
			}
			return true;
		}

		return true;
	};
}

function init_shortcuts() {
	Object.keys(context.shortcuts).forEach(function (k) {
		context.shortcuts[k] = (context.shortcuts[k] || '').toUpperCase();
	});

	document.addEventListener('keydown', ev => {
		if (ev.target.closest('input, textarea') ||
				ev.ctrlKey || ev.metaKey || (ev.altKey && ev.shiftKey)) {
			return;
		}

		const s = context.shortcuts;
		let k = (ev.key.trim() || ev.code || 'Space').toUpperCase();

		// IE11
		if (k === 'SPACEBAR') k = 'SPACE';
		else if (k === 'DEL') k = 'DELETE';
		else if (k === 'ESC') k = 'ESCAPE';

		if (location.hash.match(/^#dropdown-/)) {
			const n = parseInt(k);
			if (n) {
				if (location.hash === '#dropdown-query') {
					user_filter(n);
				} else {
					auto_share(n);
				}
				ev.preventDefault();
				return;
			}
		}
		if (k === s.actualize) {
			const btn = document.getElementById('actualize');
			if (btn) {
				btn.click();
			}
			ev.preventDefault();
			return;
		}
		if (k === s.next_entry) {
			if (ev.altKey) {
				next_category();
			} else if (ev.shiftKey) {
				next_feed();
			} else {
				next_entry(false);
			}
			ev.preventDefault();
			return;
		}
		if (k === s.next_unread_entry) {
			if (ev.altKey) {
				next_unread_category();
			} else if (ev.shiftKey) {
				next_feed();
			} else {
				next_unread_entry(false);
			}
			ev.preventDefault();
			return;
		}
		if (k === s.prev_entry) {
			if (ev.altKey) {
				prev_category();
			} else if (ev.shiftKey) {
				prev_feed();
			} else {
				prev_entry(false);
			}
			ev.preventDefault();
			return;
		}
		if (k === s.mark_read) {
			if (ev.altKey) {
				mark_previous_read(document.querySelector('.flux.current'));
			} else if (ev.shiftKey) {
				document.querySelector('.nav_menu .read_all').click();
			} else {	// Toggle the read state
				mark_read(document.querySelector('.flux.current'), false, false);
			}
			ev.preventDefault();
			return;
		}
		if (k === s.first_entry) {
			if (ev.altKey) {
				first_category();
			} else if (ev.shiftKey) {
				first_feed();
			} else {
				const old_active = document.querySelector('.flux.current');
				const first = document.querySelector('.flux');
				if (first.classList.contains('flux')) {
					toggleContent(first, old_active, false);
				}
			}
			ev.preventDefault();
			return;
		}
		if (k === s.last_entry) {
			if (ev.altKey) {
				last_category();
			} else if (ev.shiftKey) {
				last_feed();
			} else {
				const old_active = document.querySelector('.flux.current');
				const last = document.querySelector('.flux:last-of-type');
				if (last.classList.contains('flux')) {
					toggleContent(last, old_active, false);
				}
			}
			ev.preventDefault();
			return;
		}

		if (ev.altKey || ev.shiftKey) {
			return;
		}
		if (k === s.mark_favorite) {	// Toggle the favorite state
			mark_favorite(document.querySelector('.flux.current'));
			ev.preventDefault();
			return;
		}
		if (k === s.go_website) {
			if (context.auto_mark_site) {
				mark_read(document.querySelector('.flux.current'), true, false);
			}

			const link_go_website = document.querySelector('.flux.current a.go_website');
			if (link_go_website) {
				const newWindow = window.open();
				if (newWindow) {
					newWindow.opener = null;
					newWindow.location = link_go_website.href;
					ev.preventDefault();
				}
			}
			return;
		}
		if (k === s.skip_next_entry) { next_entry(true); ev.preventDefault(); return; }
		if (k === s.skip_prev_entry) { prev_entry(true); ev.preventDefault(); return; }
		if (k === s.collapse_entry) { collapse_entry(); ev.preventDefault(); return; }
		if (k === s.auto_share) { auto_share(); ev.preventDefault(); return; }
		if (k === s.user_filter) { user_filter(); ev.preventDefault(); return; }
		if (k === s.load_more) { load_more_posts(); ev.preventDefault(); return; }
		if (k === s.close_dropdown) { location.hash = null; ev.preventDefault(); return; }
		if (k === s.help) { window.open(context.urls.help); ev.preventDefault(); return; }
		if (k === s.focus_search) { document.getElementById('search').focus(); ev.preventDefault(); return; }
		if (k === s.normal_view) { delayedClick(document.querySelector('#nav_menu_views .view-normal')); ev.preventDefault(); return; }
		if (k === s.reading_view) { delayedClick(document.querySelector('#nav_menu_views .view-reader')); ev.preventDefault(); return; }
		if (k === s.global_view) { delayedClick(document.querySelector('#nav_menu_views .view-global')); ev.preventDefault(); return; }
		if (k === s.rss_view) { delayedClick(document.querySelector('#nav_menu_views .view-rss')); ev.preventDefault(); return; }
		if (k === s.toggle_media) { toggle_media(); ev.preventDefault(); }
	});
}

function init_stream(stream) {
	stream.onclick = function (ev) {
		let el = ev.target.closest('.flux a.read');
		if (el) {
			mark_read(el.closest('.flux'), false, false);
			return false;
		}

		el = ev.target.closest('.flux a.bookmark');
		if (el) {
			mark_favorite(el.closest('.flux'));
			return false;
		}

		el = ev.target.closest('.dynamictags');
		if (el) {
			loadDynamicTags(el);
			return true;
		}

		el = ev.target.closest('.item.title > a');
		if (el) {	// Allow default control/command-click behaviour such as open in background-tab
			return ev.ctrlKey || ev.metaKey;
		}

		el = ev.target.closest('.flux .content .text a');
		if (el) {
			if (!el.closest('div').classList.contains('author')) {
				el.target = '_blank';
				el.rel = 'noreferrer';
			}
			return true;
		}

		el = ev.target.closest('.item.share > button[data-type="print"]');
		if (el) {	// Print
			const tmp_window = window.open();
			for (let i = 0; i < document.styleSheets.length; i++) {
				tmp_window.document.writeln('<link href="' + document.styleSheets[i].href + '" rel="stylesheet" type="text/css" />');
			}
			tmp_window.document.writeln(el.closest('.flux_content').querySelector('.content').innerHTML);
			tmp_window.document.close();
			tmp_window.focus();
			tmp_window.print();
			tmp_window.close();
			return false;
		}

		el = ev.target.closest('.item.share > button[data-type="clipboard"]');
		if (el) { // Clipboard
			if (navigator.clipboard) {
				navigator.clipboard.writeText(el.dataset.url)
					.then(() => {
						toggleClass(el, 'error');
					})
					.catch(e => {
						console.log(e);
						toggleClass(el, 'error');
					});
			} else {
				// fallback, if navigator.clipboard is not available f.e. if access is not via https or localhost
				const inputElement = document.createElement('input');
				inputElement.value = el.dataset.url;
				document.body.appendChild(inputElement);
				inputElement.select();
				if (document.execCommand && document.execCommand('copy')) {
					toggleClass(el, 'ok');
				} else {
					console.log('document.execCommand("copy") failed');
					toggleClass(el, 'error');
				}
				inputElement.remove();
			}

			return false;
		}

		el = ev.target.closest('.item.share > button[data-type="web-sharing-api"]');
		if (el && navigator.share) {	// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
			const shareData = {
				url: el.dataset.url,
				title: decodeURI(el.dataset.title),
			};
			navigator.share(shareData);
			return false;
		}

		el = ev.target.closest('.item.share > a[data-type="email-webmail-firefox-fix"]');
		if (el) {
			window.open(el.href);
			return false;
		}

		el = ev.target.closest('.item.share > a[href="POST"]');
		if (el) {	// Share by POST
			const f = el.parentElement.querySelector('form');
			f.disabled = false;
			f.submit();
			return false;
		}

		el = ev.target.closest('.flux_header, .flux_content');
		if (el) {	// flux_toggle
			if (ev.target.closest('.reader, .content, .item.website, .item.link, .dropdown')) {
				return true;
			}
			if (!context.sides_close_article && ev.target.matches('.flux_content')) {
				// setting for not-closing after clicking outside article area
				return false;
			}
			const old_active = document.querySelector('.flux.current');
			const new_active = el.parentNode;
			if (ev.target.tagName.toUpperCase() === 'A') {	// Leave real links alone (but does not catch img in a link)
				if (context.auto_mark_article) {
					mark_read(new_active, true, false);
				}
				return true;
			}
			toggleContent(new_active, old_active, false);
			return false;
		}
	};

	stream.onmouseup = function (ev) {	// Mouseup enables us to catch middle click, and control+click in IE/Edge
		if (ev.altKey || ev.metaKey || ev.shiftKey) {
			return;
		}

		let el = ev.target.closest('.item.title > a');
		if (el) {
			if (ev.which == 1) {
				if (ev.ctrlKey) {	// Control+click
					if (context.auto_mark_site) {
						mark_read(el.closest('.flux'), true, false);
					}
				} else {
					el.parentElement.click();	// Normal click, just toggle article.
				}
			} else if (ev.which == 2 && !ev.ctrlKey) {	// Simple middle click: same behaviour as CTRL+click
				if (context.auto_mark_article) {
					const new_active = el.closest('.flux');
					mark_read(new_active, true, false);
				}
			}
			return;
		}

		if (context.auto_mark_site) {
			// catch mouseup instead of click so we can have the correct behaviour
			// with middle button click (scroll button).
			el = ev.target.closest('.flux .link > a');
			if (el) {
				if (ev.which == 3) {
					return;
				}
				mark_read(el.closest('.flux'), true, false);
			}
		}
	};

	stream.onchange = function (ev) {
		const checkboxTag = ev.target.closest('.checkboxTag');
		if (checkboxTag) {	// Dynamic tags
			ev.stopPropagation();
			const tagId = checkboxTag.name.replace(/^t_/, '');
			const tagName = checkboxTag.nextElementSibling ? checkboxTag.nextElementSibling.childNodes[0].value : '';
			if ((tagId == 0 && tagName.length > 0) || tagId != 0) {
				const isChecked = checkboxTag.checked;
				const entry = checkboxTag.closest('div.flux');
				const entryId = entry.id.replace(/^flux_/, '');
				checkboxTag.disabled = true;

				const req = new XMLHttpRequest();
				req.open('POST', './?c=tag&a=tagEntry&ajax=1', true);
				req.responseType = 'json';
				req.onerror = function (e) {
					checkboxTag.checked = !isChecked;
					badAjax(this.status == 403);
				};
				req.onload = function (e) {
					if (this.status != 200) {
						return req.onerror(e);
					}
					if (entry.classList.contains('not_read')) {
						incUnreadsTag('t_' + tagId, isChecked ? 1 : -1);
					}
				};
				req.onloadend = function (e) {
					checkboxTag.disabled = false;
					if (tagId == 0) {
						loadDynamicTags(checkboxTag.closest('div.dropdown'));
					}
				};
				req.setRequestHeader('Content-Type', 'application/json');
				req.send(JSON.stringify({
					_csrf: context.csrf,
					id_tag: tagId,
					name_tag: tagId == 0 ? tagName : '',
					id_entry: entryId,
					checked: isChecked,
					ajax: 1,
				}));
			}
		}
	};
}

function toggleClass(el, cssclass) {
	el.classList.remove(cssclass);
	el.dataset.foo = el.offsetWidth; // it does nothing, but it is needed. See https://github.com/FreshRSS/FreshRSS/pull/5295
	el.classList.add(cssclass);
}

function init_nav_entries() {
	const nav_entries = document.getElementById('nav_entries');
	if (nav_entries) {
		nav_entries.querySelector('.previous_entry').onclick = function (e) {
			prev_entry(false);
			return false;
		};
		nav_entries.querySelector('.next_entry').onclick = function (e) {
			next_entry(false);
			return false;
		};
		nav_entries.querySelector('.up').onclick = function (e) {
			const active_item = (document.querySelector('.flux.current') || document.querySelector('.flux'));
			const windowTop = document.scrollingElement.scrollTop;
			const item_top = active_item.offsetParent.offsetTop + active_item.offsetTop;

			const nav_menu = document.querySelector('.nav_menu');
			let nav_menu_height = 0;

			if (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky') {
				nav_menu_height = nav_menu.offsetHeight;
			}
			document.scrollingElement.scrollTop = windowTop > item_top ? item_top - nav_menu_height : 0 - nav_menu_height;
			return false;
		};
	}
}

function loadDynamicTags(div) {
	div.classList.remove('dynamictags');
	div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
	const entryId = div.closest('div.flux').id.replace(/^flux_/, '');

	const req = new XMLHttpRequest();
	req.open('GET', './?c=tag&a=getTagsForEntry&id_entry=' + entryId, true);
	req.responseType = 'json';
	req.onerror = function (e) {
		div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
		div.classList.add('dynamictags');
	};
	req.onload = function (e) {
		if (this.status != 200) {
			return req.onerror(e);
		}
		const json = xmlHttpRequestJson(this);
		if (!json) {
			return req.onerror(e);
		}

		if (!context.anonymous) {
			const li_item0 = document.createElement('li');
			li_item0.setAttribute('class', 'item addItem');

			const label = document.createElement('label');
			label.setAttribute('class', 'noHover');

			const input_checkboxTag = document.createElement('input');
			input_checkboxTag.setAttribute('class', 'checkboxTag checkboxNewTag');
			input_checkboxTag.setAttribute('name', 't_0');
			input_checkboxTag.setAttribute('type', 'checkbox');

			const input_newTag = document.createElement('input');
			input_newTag.setAttribute('type', 'text');
			input_newTag.setAttribute('name', 'newTag');
			input_newTag.addEventListener('keydown', function (ev) { if (ev.key.toUpperCase() == 'ENTER') { this.parentNode.previousSibling.click(); } });

			const button_btn = document.createElement('button');
			button_btn.setAttribute('type', 'button');
			button_btn.setAttribute('class', 'btn');
			button_btn.addEventListener('click', function () { this.parentNode.parentNode.click(); });

			const text_plus = document.createTextNode('+');

			const div_stick = document.createElement('div');
			div_stick.setAttribute('class', 'stick');

			button_btn.appendChild(text_plus);
			div_stick.appendChild(input_newTag);
			div_stick.appendChild(button_btn);
			label.appendChild(input_checkboxTag);
			label.appendChild(div_stick);
			li_item0.appendChild(label);

			div.querySelector('.dropdown-menu').appendChild(li_item0);
		}

		let html = '';
		if (json && json.length) {
			let nbLabelsChecked = 0;
			for (let i = 0; i < json.length; i++) {
				const tag = json[i];
				if (context.anonymous && !tag.checked) {
					// In anomymous mode, show only the used tags
					continue;
				}
				if (tag.checked) {
					nbLabelsChecked++;
				}
				html += '<li class="item"><label><input ' +
					(context.anonymous ? '' : 'class="checkboxTag" ') +
					'name="t_' + tag.id + '"type="checkbox" ' +
					(context.anonymous ? 'disabled="disabled" ' : '') +
					(tag.checked ? 'checked="checked" ' : '') + '/> ' + tag.name + '</label></li>';
			}
			if (context.anonymous && nbLabelsChecked === 0) {
				html += '<li class="item"><span class="emptyLabels">' + context.i18n.labels_empty + '</span></li>';
			}
		}
		div.querySelector('.dropdown-menu').insertAdjacentHTML('beforeend', html);
	};
	req.send();
}

// <actualize>
let feeds_processed = 0;
let categories_processed = 0;
let to_process = 0;

function refreshFeed(feeds, feeds_count) {
	const feed = feeds.pop();
	if (!feed) {
		return;
	}
	const req = new XMLHttpRequest();
	req.open('POST', feed.url, true);
	req.onloadend = function (e) {
		feeds_processed++;
		if (this.status != 200) {
			badAjax(false);
		} else {
			const div = document.getElementById('actualizeProgress');
			div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
			div.querySelector('.title').innerHTML = feed.title;
		}
		if (feeds_processed === feeds_count) {
			// Empty request to commit new articles
			const req2 = new XMLHttpRequest();
			req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
			req2.onloadend = function (e) {
				delayedFunction(function () { location.reload(); });
			};
			req2.setRequestHeader('Content-Type', 'application/json');
			req2.send(JSON.stringify({
				_csrf: context.csrf,
				noCommit: 0,
			}));
		} else {
			refreshFeed(feeds, feeds_count);
		}
	};
	req.setRequestHeader('Content-Type', 'application/json');
	req.send(JSON.stringify({
		_csrf: context.csrf,
		noCommit: 1,
	}));
}

function refreshFeeds(json) {
	feeds_processed = 0;
	if (!json.feeds || json.feeds.length === 0) {
		// Empty request to commit new articles
		const req2 = new XMLHttpRequest();
		req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
		req2.onloadend = function (e) {
			context.ajax_loading = false;
		};
		req2.setRequestHeader('Content-Type', 'application/json');
		req2.send(JSON.stringify({
			_csrf: context.csrf,
			noCommit: 0,
		}));
	} else {
		const feeds_count = json.feeds.length;
		for (let i = 10; i > 0; i--) {
			refreshFeed(json.feeds, feeds_count);
		}
	}
}

function refreshDynamicOpml(categories, categories_count, next) {
	const category = categories.pop();
	if (!category) {
		return;
	}
	const req = new XMLHttpRequest();
	req.open('POST', category.url, true);
	req.onloadend = function (e) {
		categories_processed++;
		if (this.status != 200) {
			badAjax(false);
		} else {
			const div = document.getElementById('actualizeProgress');
			div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
			div.querySelector('.title').innerHTML = category.title;
		}
		if (categories_processed === categories_count) {
			if (next) { next(); }
		} else {
			refreshDynamicOpml(categories, categories_count, next);
		}
	};
	req.setRequestHeader('Content-Type', 'application/json');
	req.send(JSON.stringify({
		_csrf: context.csrf,
		noCommit: 1,
	}));
}

function refreshDynamicOpmls(json, next) {
	categories_processed = 0;
	if (json.categories && json.categories.length > 0) {
		const categories_count = json.categories.length;
		for (let i = 10; i > 0; i--) {
			refreshDynamicOpml(json.categories, categories_count, next);
		}
	} else {
		if (next) { next(); }
	}
}

function init_actualize() {
	let auto = false;
	let nbCategoriesFirstRound = 0;
	let skipCategories = false;

	const actualize = document.getElementById('actualize');
	if (!actualize) {
		return;
	}

	actualize.onclick = function () {
		if (context.ajax_loading) {
			return false;
		}
		context.ajax_loading = true;

		const req = new XMLHttpRequest();
		req.open('POST', './?c=javascript&a=actualize', true);
		req.responseType = 'json';
		req.onload = function (e) {
			if (this.status != 200) {
				return badAjax(false);
			}
			const json = xmlHttpRequestJson(this);
			if (!json) {
				return badAjax(false);
			}
			if (auto && json.categories.length < 1 && json.feeds.length < 1) {
				auto = false;
				context.ajax_loading = false;
				return false;
			}
			to_process = json.categories.length + json.feeds.length + nbCategoriesFirstRound;
			if (json.categories.length + json.feeds.length > 0 && !document.getElementById('actualizeProgress')) {
				document.body.insertAdjacentHTML('beforeend', '<div id="actualizeProgress" class="notification good">' +
					json.feedback_actualize + '<br /><span class="title">/</span><br /><span class="progress">0 / ' +
					to_process + '</span></div>');
			} else {
				openNotification(json.feedback_no_refresh, 'good');
			}
			if (json.categories.length > 0 && !skipCategories) {
				skipCategories = true;	// To avoid risk of infinite loop
				nbCategoriesFirstRound = json.categories.length;
				// If some dynamic OPML categories are refreshed, need to reload the list of feeds before updating them
				refreshDynamicOpmls(json, () => {
					context.ajax_loading = false;
					actualize.click();
				});
			} else {
				refreshFeeds(json);
			}
		};
		req.setRequestHeader('Content-Type', 'application/json');
		req.send(JSON.stringify({
			_csrf: context.csrf,
		}));

		return false;
	};

	if (context.auto_actualize_feeds) {
		auto = true;
		actualize.click();
	}
}
// </actualize>

// <notification>
let notification = null;
let notification_interval = null;
let notification_working = false;

function openNotification(msg, status) {
	if (notification_working === true) {
		return false;
	}
	notification_working = true;
	notification.querySelector('.msg').innerHTML = msg;
	notification.className = 'notification';
	notification.classList.add(status);
	if (status == 'good') {
		notification_interval = setTimeout(closeNotification, 4000);
	} else {
		// no status or f.e. status = 'bad', give some more time to read
		notification_interval = setTimeout(closeNotification, 8000);
	}
}

function closeNotification() {
	notification.classList.add('closed');
	clearInterval(notification_interval);
	notification_working = false;
}

function init_notifications() {
	notification = document.getElementById('notification');

	notification.querySelector('a.close').addEventListener('click', function (ev) {
		closeNotification();
		ev.preventDefault();
		return false;
	});

	notification.addEventListener('mouseenter', function () {
		clearInterval(notification_interval);
	});

	notification.addEventListener('mouseleave', function () {
		notification_interval = setTimeout(closeNotification, 3000);
	});

	if (notification.querySelector('.msg').innerHTML.length > 0) {
		notification_working = true;
		if (notification.classList.contains('good')) {
			notification_interval = setTimeout(closeNotification, 4000);
		} else {
			// no status or f.e. status = 'bad', give some more time to read
			notification_interval = setTimeout(closeNotification, 8000);
		}
	}
}
// </notification>

// <notifs html5>
let notifs_html5_permission = 'denied';

function notifs_html5_is_supported() {
	return window.Notification !== undefined;
}

function notifs_html5_ask_permission() {
	try {
		window.Notification.requestPermission(function () {
			notifs_html5_permission = window.Notification.permission;
		});
	} catch (e) {
	}
}

function notifs_html5_show(nb, nb_new) {
	if (notifs_html5_permission !== 'granted') {
		return;
	}

	try {
		const notification = new window.Notification(context.i18n.notif_title_articles, {
			icon: '../themes/icons/favicon-256-padding.png',
			body: context.i18n.notif_body_new_articles.replace('%%d', nb_new) + ' ' + context.i18n.notif_body_unread_articles.replace('%%d', nb),
			tag: 'freshRssNewArticles',
		});

		notification.onclick = function () {
			delayedFunction(function () {
				location.reload();
				window.focus();
				notification.close();
			});
		};

		if (context.html5_notif_timeout !== 0) {
			setTimeout(function () {
				notification.close();
			}, context.html5_notif_timeout * 1000);
		}
	} catch (e) {
	}
}

function init_notifs_html5() {
	if (!notifs_html5_is_supported()) {
		return;
	}

	notifs_html5_permission = notifs_html5_ask_permission();
}
// </notifs html5>

function refreshUnreads() {
	const req = new XMLHttpRequest();
	req.open('GET', './?c=javascript&a=nbUnreadsPerFeed', true);
	req.responseType = 'json';
	req.onload = function (e) {
		const json = xmlHttpRequestJson(this);
		if (!json) {
			return badAjax(false);
		}
		const isAll = document.querySelector('.category.all.active');
		let new_articles = false;
		let nbUnreadFeeds = 0;
		const title = document.querySelector('.category.all .title');
		const nb_unreads_before = title ? str2int(title.getAttribute('data-unread')) : 0;

		Object.keys(json.feeds).forEach(function (feed_id) {
			const nbUnreads = json.feeds[feed_id];
			nbUnreadFeeds += nbUnreads;
			feed_id = 'f_' + feed_id;
			const elem = document.getElementById(feed_id);
			const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;

			if ((incUnreadsFeed(null, feed_id, nbUnreads - feed_unreads) || isAll) &&	// Update of current view?
					(nbUnreads - feed_unreads > 0)) {
				const newArticle = document.getElementById('new-article');
				newArticle.setAttribute('aria-hidden', 'false');
				newArticle.style.display = 'block';
				new_articles = true;
			}
		});

		const noArticlesToShow_div = document.getElementById('noArticlesToShow');
		if (nbUnreadFeeds > 0 && noArticlesToShow_div) {
			noArticlesToShow_div.classList.add('hide');
		}

		let nbUnreadTags = 0;

		Object.keys(json.tags).forEach(function (tag_id) {
			const nbUnreads = json.tags[tag_id];
			nbUnreadTags += nbUnreads;
			const tag = document.getElementById('t_' + tag_id);
			if (tag) {
				tag.setAttribute('data-unread', nbUnreads);
				tag.querySelector('.item-title').setAttribute('data-unread', numberFormat(nbUnreads));
			}
		});

		const tags = document.querySelector('.category.tags');
		if (tags) {
			tags.setAttribute('data-unread', nbUnreadTags);
			tags.querySelector('.title').setAttribute('data-unread', numberFormat(nbUnreadTags));
		}

		const nb_unreads = title ? str2int(title.getAttribute('data-unread')) : 0;

		if (nb_unreads > 0 && new_articles) {
			faviconNbUnread(nb_unreads);
			const nb_new = nb_unreads - nb_unreads_before;
			notifs_html5_show(nb_unreads, nb_new);
		}
	};
	req.send();
}

function toggle_bigMarkAsRead_button() {
	const bigMarkAsRead_button = document.getElementById('bigMarkAsRead');
	if (bigMarkAsRead_button) {
		if (document.querySelector('.flux.not_read') != null) {
			bigMarkAsRead_button.style = '';
			bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
		} else {
			if (bigMarkAsRead_button.querySelector('.jumpNext')) {
				bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = 'hidden';
			} else {
				bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
				bigMarkAsRead_button.style.visibility = 'hidden';
			}
		}
	}
}

// <endless_mode>
let url_load_more = '';
let load_more = false;
let box_load_more = null;

function load_more_posts() {
	if (load_more || !url_load_more || !box_load_more) {
		return;
	}
	load_more = true;
	document.getElementById('load_more').classList.add('loading');

	const req = new XMLHttpRequest();
	req.open('GET', url_load_more, true);
	req.responseType = 'document';
	req.onload = function (e) {
		const html = this.response;
		const streamFooter = document.getElementById('stream-footer');

		const streamAdopted = document.adoptNode(html.getElementById('stream'));
		streamAdopted.querySelectorAll('.flux, .day').forEach(function (div) {
			box_load_more.insertBefore(div, streamFooter);
		});

		const streamFooterOld = streamFooter.querySelector('.stream-footer-inner');
		const streamFooterNew = streamAdopted.querySelector('.stream-footer-inner');
		streamFooter.replaceChild(streamFooterNew, streamFooterOld);

		const bigMarkAsRead = document.getElementById('bigMarkAsRead');
		const readAll = document.querySelector('#nav_menu_read_all .read_all');
		if (readAll && bigMarkAsRead && bigMarkAsRead.formAction) {
			if (context.display_order === 'ASC') {
				readAll.formAction = bigMarkAsRead.formAction;
			} else {
				bigMarkAsRead.formAction = readAll.formAction;
			}
			toggle_bigMarkAsRead_button();
		}

		document.querySelectorAll('[id^=day_]').forEach(function (div) {
			const ids = document.querySelectorAll('[id="' + div.id + '"]');
			for (let i = ids.length - 1; i > 0; i--) {	// Keep only the first
				ids[i].remove();
			}
		});

		init_load_more(box_load_more);

		const div_load_more = document.getElementById('load_more');
		if (bigMarkAsRead) {
			bigMarkAsRead.removeAttribute('disabled');
		}
		if (div_load_more) {
			div_load_more.classList.remove('loading');
		}

		load_more = false;
	};
	req.send();
}

const freshrssLoadMoreEvent = document.createEvent('Event');
freshrssLoadMoreEvent.initEvent('freshrss:load-more', true, true);

function init_load_more(box) {
	box_load_more = box;
	document.body.dispatchEvent(freshrssLoadMoreEvent);

	const next_button = document.getElementById('load_more');
	if (!next_button) {
		// no more article to load
		url_load_more = '';
		return;
	}

	url_load_more = next_button.getAttribute('formaction');

	next_button.onclick = function (e) {
		load_more_posts();
		return false;
	};
}
// </endless_mode>

function init_confirm_action() {
	document.body.onclick = function (ev) {
		const b = ev.target.closest('.confirm');
		if (b) {
			let str_confirmation = this.getAttribute('data-str-confirm');
			if (!str_confirmation) {
				str_confirmation = context.i18n.confirmation_default;
			}
			return confirm(str_confirmation);
		}
	};
	document.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
}

function faviconNbUnread(n) {
	if (typeof n === 'undefined') {
		const t = document.querySelector('.category.all .title');
		n = t ? str2int(t.getAttribute('data-unread')) : 0;
	}
	// http://remysharp.com/2010/08/24/dynamic-favicons/
	const canvas = document.createElement('canvas');
	const link = document.getElementById('favicon').cloneNode(true);
	const ratio = window.devicePixelRatio;
	if (canvas.getContext && link) {
		canvas.height = canvas.width = 16 * ratio;
		const img = document.createElement('img');
		img.onload = function () {
			const ctx = canvas.getContext('2d');
			ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
			if (n > 0) {
				let text = '';
				if (n < 1000) {
					text = n;
				} else if (n < 100000) {
					text = Math.floor(n / 1000) + 'k';
				} else {
					text = 'E' + Math.floor(Math.log10(n));
				}
				ctx.font = 'bold ' + 9 * ratio + 'px "Arial", sans-serif';
				ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
				ctx.fillRect(0, 7 * ratio, ctx.measureText(text).width, 9 * ratio);
				ctx.fillStyle = '#F00';
				ctx.fillText(text, 0, canvas.height - 1);
			}
			link.href = canvas.toDataURL('image/png');
			// Check if data URI has generated a real favicon and if not, fallback to standard icon
			if (link.href.length > 180) {
				document.querySelector('link[rel~=icon]').remove();
				document.head.appendChild(link);
			}
		};
		img.src = '../favicon.ico';
	}
}

function removeFirstLoadSpinner() {
	const first_load = document.getElementById('first_load');
	if (first_load) {
		first_load.remove();
	}
}

function init_normal() {
	const stream = document.getElementById('stream');
	if (!stream) {
		if (window.console) {
			console.log('FreshRSS waiting for content…');
		}
		setTimeout(init_normal, 100);
		return;
	}
	init_column_categories();
	init_stream(stream);
	init_actualize();
	faviconNbUnread();

	window.onbeforeunload = function (e) {
		const sidebar = document.getElementById('sidebar');
		if (sidebar) {	// Save sidebar scroll position
			sessionStorage.setItem('FreshRSS_sidebar_scrollTop', sidebar.scrollTop);
		}
		if (mark_read_queue && mark_read_queue.length > 0) {
			return false;
		}
	};
}

function init_main_beforeDOM() {
	document.scrollingElement.scrollTop = 0;
	init_shortcuts();
	if (['normal', 'reader', 'global'].indexOf(context.current_view) >= 0) {
		init_normal();
	}
}

function init_main_afterDOM() {
	removeFirstLoadSpinner();
	init_notifications();
	init_confirm_action();
	const stream = document.getElementById('stream');
	if (stream) {
		init_load_more(stream);
		init_posts();
		if (document.getElementById('new-article')) {
			// Only relevant for interactive views
			init_nav_entries();
			init_notifs_html5();
			toggle_bigMarkAsRead_button();
			setTimeout(faviconNbUnread, 1000);
			setInterval(refreshUnreads, 120000);
		}
	}

	if (window.console) {
		console.log('FreshRSS main init done.');
	}
}

init_main_beforeDOM();	// Can be called before DOM is fully loaded

if (document.readyState && document.readyState !== 'loading') {
	init_main_afterDOM();
} else {
	if (window.console) {
		console.log('FreshRSS waiting for DOMContentLoaded…');
	}
	document.addEventListener('DOMContentLoaded', init_main_afterDOM, false);
}
// @license-end