summaryrefslogtreecommitdiff
path: root/plugins/NotesAndReminders/src/reminders.cpp
blob: 8a4012d99063b113ca3a4b020e87b15d54710624 (plain)
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
#include "stdafx.h"

#define FILETIME_TICKS_PER_SEC ((ULONGLONG)10000000)

#define MAX_REMINDER_LEN	16384

// RemindersData DB data params
#define DATATAG_TEXT	      1 // %s
#define DATATAG_SNDREPEAT  2 // %u (specifies seconds to wait between sound repeats, 0 if repeat is disabled)
#define DATATAG_SNDSEL     3 // %d (which sound to use, default, alt1, alt2, -1 means no sound at all)
#define DATATAG_REPEAT     4 // %d (repeateable reminder)

#define IDM_NEWREMINDER 40001
#define IDM_DELETEREMINDER 40002
#define IDM_DELETEALLREMINDERS 40003

#define WM_RELOAD (WM_USER + 100)

#define NOTIFY_LIST() if (bListReminderVisible) PostMessage(LV,WM_RELOAD,0,0)

/////////////////////////////////////////////////////////////////////////////////////////

static void RemoveReminderSystemEvent(struct REMINDERDATA *p);

struct REMINDERDATA : public MZeroedObject
{
	HWND handle;
	DWORD uid;
	char* Reminder;
	ULARGE_INTEGER When;	// FILETIME in UTC
	UINT RepeatSound;
	UINT RepeatSoundTTL;
	int  SoundSel;			// -1 if sound disabled
	bool bVisible;
	bool bRepeat;
	bool bSystemEventQueued;

	REMINDERDATA()
	{
	}

	~REMINDERDATA()
	{
		// remove pending system event
		if (bSystemEventQueued)
			RemoveReminderSystemEvent(this);
	}
};

static int ReminderSortCb(const REMINDERDATA *v1, const REMINDERDATA *v2)
{
	if (v1->When.QuadPart == v2->When.QuadPart)
		return 0;

	return (v1->When.QuadPart < v2->When.QuadPart) ? -1 : 1;
}

static LIST<REMINDERDATA> arReminders(1, ReminderSortCb);

static bool bNewReminderVisible = false;
static bool bListReminderVisible = false;
static UINT QueuedReminderCount = 0;
static HWND LV;

int WS_Send(SOCKET s, char *data, int datalen);
unsigned long WS_ResolveName(char *name, WORD *port, int defaultPort);

void Send(char *user, char *host, char *Msg, char* server);
wchar_t* GetPreviewString(const char *lpsz);

// time convertsion routines that take local time-zone specific daylight saving configuration into account
// (unlike the standard FileTimeToLocalFileTime functions)

void FileTimeToTzLocalST(const FILETIME *lpUtc, SYSTEMTIME *tmLocal)
{
	SYSTEMTIME tm;
	FileTimeToSystemTime(lpUtc, &tm);
	SystemTimeToTzSpecificLocalTime(nullptr, &tm, tmLocal);
}

void TzLocalSTToFileTime(const SYSTEMTIME *tmLocal, FILETIME *lpUtc)
{
	SYSTEMTIME tm;
	TzSpecificLocalTimeToSystemTime(nullptr, (SYSTEMTIME*)tmLocal, &tm);
	SystemTimeToFileTime(&tm, lpUtc);
}

static REMINDERDATA* FindReminder(DWORD uid)
{
	for (auto &pReminder : arReminders)
		if (pReminder->uid == uid)
			return pReminder;

	return nullptr;
}

static DWORD CreateUid()
{
	if (!arReminders.getCount())
		return 1;

	// check existing reminders if uid is in use
	for (DWORD uid = 1;; uid++) {
		if (!FindReminder(uid)) // uid in use
			return uid;
	}
}

static void RemoveReminderSystemEvent(REMINDERDATA *p)
{
	if (p->bSystemEventQueued) {
		for (int i = 0;; i++) {
			CLISTEVENT *pev = g_clistApi.pfnGetEvent(-1, i);
			if (!pev)
				break;

			if ((ULONG)pev->lParam == p->uid && !pev->hContact && pev->pszService && !mir_strcmp(pev->pszService, MODULENAME"/OpenTriggeredReminder")) {
				if (!g_clistApi.pfnRemoveEvent(pev->hContact, pev->hDbEvent)) {
					p->bSystemEventQueued = false;
					if (QueuedReminderCount)
						QueuedReminderCount--;
				}
				break;
			}
		}
	}
}

void PurgeReminders(void)
{
	char ValueName[32];

	int ReminderCount = g_plugin.getDword("RemindersData", 0);
	for (int i = 0; i < ReminderCount; i++) {
		mir_snprintf(ValueName, "RemindersData%d", i);
		g_plugin.delSetting(ValueName);
	}
}

void JustSaveReminders(void)
{
	int OldReminderCount = g_plugin.getDword("RemindersData", 0);
	g_plugin.setDword("RemindersData", arReminders.getCount());

	int i = 0;
	for (auto &pReminder : arReminders) {
		char *tmpReminder;
		if (mir_strlen(pReminder->Reminder))
			tmpReminder = pReminder->Reminder;
		else
			tmpReminder = "";

		CMStringA szValue;

		// data header (save 'When' with 1-second resolution, it's just a waste to have 100-nanosecond resolution
		// which results in larger DB strings with no use)
		szValue.AppendFormat("X%u:%I64x", pReminder->uid, pReminder->When.QuadPart / FILETIME_TICKS_PER_SEC);

		// repeat
		if (pReminder->bRepeat)
			szValue.AppendFormat("\033""%u:%u", DATATAG_REPEAT, (int)pReminder->bRepeat);

		// sound repeat
		if (pReminder->RepeatSound)
			szValue.AppendFormat("\033""%u:%u", DATATAG_SNDREPEAT, pReminder->RepeatSound);

		// sound
		if (pReminder->SoundSel)
			szValue.AppendFormat("\033""%u:%d", DATATAG_SNDSEL, pReminder->SoundSel);

		// reminder text/note (ALWAYS PUT THIS PARAM LAST)
		if (tmpReminder && *tmpReminder)
			szValue.AppendFormat("\033""%u:%s", DATATAG_TEXT, tmpReminder);

		char ValueName[32];
		mir_snprintf(ValueName, "RemindersData%d", i++);
		db_set_blob(0, MODULENAME, ValueName, szValue.GetBuffer(), szValue.GetLength() + 1);
	}

	// delete any left over DB reminder entries
	while (i < OldReminderCount) {
		char ValueName[32];
		mir_snprintf(ValueName, "RemindersData%d", i++);
		g_plugin.delSetting(ValueName);
	}
}

void LoadReminders(void)
{
	char *Value;
	WORD Size;
	char ValueName[32];
	BOOL GenerateUids = FALSE;

	arReminders.destroy();
	int RemindersCount = g_plugin.getDword("RemindersData", 0);

	for (int i = 0; i < RemindersCount; i++) {
		Size = 65535;
		Value = nullptr;
		mir_snprintf(ValueName, "RemindersData%d", i);

		ReadSettingBlob(0, MODULENAME, ValueName, &Size, (void**)&Value);

		// was the blob found
		if (Size && Value) {
			REMINDERDATA rem = {};
			char *TVal;
			REMINDERDATA *TempRem;
			char *DelPos = strchr(Value, 0x1B);

			// ensure that read data is null-terminated
			Value[(UINT)Size - 1] = 0;

			if (Value[0] == 'X') {
				// new eXtended/fleXible data format

				if (DelPos)
					*DelPos = 0;

				// uid:when
				TVal = strchr(Value + 1, ':');
				if (!TVal || (DelPos && TVal > DelPos))
					continue;

				*TVal++ = 0;
				rem.uid = strtoul(Value + 1, nullptr, 10);
				rem.When.QuadPart = _strtoui64(TVal, nullptr, 16) * FILETIME_TICKS_PER_SEC;

				// optional \033 separated params
				while (DelPos) {
					char *sep;
					UINT tag;

					TVal = DelPos + 1;
					// find param end and make sure it's null-terminated (if end of data then it's already null-terminated)
					DelPos = strchr(TVal, 0x1B);
					if (DelPos)
						*DelPos = 0;

					// tag:<data>
					sep = strchr(TVal, ':');
					if (!sep || (DelPos && sep > DelPos))
						goto skip;

					tag = strtoul(TVal, nullptr, 10);
					TVal = sep + 1;

					switch (tag) {
					case DATATAG_TEXT:
						rem.Reminder = _strdup(TVal);
						break;

					case DATATAG_SNDREPEAT:
						rem.RepeatSound = strtoul(TVal, nullptr, 10);
						break;

					case DATATAG_SNDSEL:
						rem.SoundSel = strtol(TVal, nullptr, 10);
						if (rem.SoundSel > 2) rem.SoundSel = 2;
						break;

					case DATATAG_REPEAT:
						rem.bRepeat = strtol(TVal, nullptr, 10) != 0;
						break;
					}
				}

				if (rem.SoundSel < 0)
					rem.RepeatSound = 0;
				if (!rem.Reminder)
					rem.Reminder = _strdup("");
			}
			else {
				// old format (for DB backward compatibility)
				if (!DelPos)
					continue;

				DelPos[0] = 0;
				// convert time_t to (local) FILETIME

				time_t tt = (time_t)strtoul(Value, nullptr, 10);
				struct tm *stm = localtime(&tt);

				SYSTEMTIME tm;
				tm.wDayOfWeek = 0;
				tm.wSecond = 0;
				tm.wMilliseconds = 0;
				tm.wHour = stm->tm_hour;
				tm.wMinute = stm->tm_min;
				tm.wSecond = stm->tm_sec;
				tm.wYear = stm->tm_year + 1900;
				tm.wMonth = stm->tm_mon + 1;
				tm.wDay = stm->tm_mday;
				SystemTimeToFileTime(&tm, (FILETIME*)&rem.When);

				TVal = DelPos + 1;
				rem.Reminder = _strdup(TVal);
			}

			// queue uid generation if invalid uid is present
			if (!rem.uid)
				GenerateUids = true;

			TempRem = new REMINDERDATA(rem);
			arReminders.insert(TempRem);
skip:;
		}

		FreeSettingBlob(Size, Value);
	}

	// generate UIDs if there are any items with an invalid UID
	if (GenerateUids && arReminders.getCount()) {
		for (auto &pReminder : arReminders)
			if (!pReminder->uid)
				pReminder->uid = CreateUid();

		JustSaveReminders();
	}
}

static void DeleteReminder(REMINDERDATA *p)
{
	if (p) {
		arReminders.remove(p);
		delete p;
	}
}

static void PurgeReminderTree()
{
	for (auto &pt : arReminders)  // empty whole tree
		delete pt;

	arReminders.destroy();
}

void SaveReminders(void)
{
	JustSaveReminders();
	PurgeReminderTree();
}

void DeleteReminders(void)
{
	PurgeReminders();
	g_plugin.setDword("RemindersData", 0);
	PurgeReminderTree();
}

void GetTriggerTimeString(const ULARGE_INTEGER *When, wchar_t *s, size_t strSize, BOOL bUtc)
{
	SYSTEMTIME tm = {0};
	LCID lc = GetUserDefaultLCID();

	*s = 0;

	if (bUtc)
		FileTimeToTzLocalST((const FILETIME*)When, &tm);
	else
		FileTimeToSystemTime((FILETIME*)When, &tm);

	if (GetDateFormat(lc, DATE_LONGDATE, &tm, nullptr, s, (int)strSize)) {
		// append time
		size_t n = mir_wstrlen(s);
		s[n++] = ' ';
		s[n] = 0;

		if (!GetTimeFormat(lc, LOCALE_NOUSEROVERRIDE | TIME_NOSECONDS, &tm, nullptr, s + n, int(strSize - n)))
			mir_snwprintf(s + n, strSize - n, L"%02d:%02d", tm.wHour, tm.wMinute);
	}
	else mir_snwprintf(s, strSize, L"%d-%02d-%02d %02d:%02d", tm.wYear, tm.wMonth, tm.wDay, tm.wHour, tm.wMinute);
}

static void Skin_PlaySoundPoly(LPCSTR pszSoundName)
{
	if (!g_plugin.bUseMSI) {
		Skin_PlaySound(pszSoundName);
		return;
	}

	if (db_get_b(0, "SkinSoundsOff", pszSoundName, 0) == 0) {
		DBVARIANT dbv;
		if (db_get_s(0, "SkinSounds", pszSoundName, &dbv) == 0) {
			char szFull[MAX_PATH];

			PathToAbsolute(dbv.pszVal, szFull);

			// use MCI device which allows multiple sounds playing at once
			// NOTE: mciSendString does not like long paths names, must convert to short
			char szShort[MAX_PATH];
			char s[512];
			GetShortPathNameA(szFull, szShort, sizeof(szShort));
			mir_snprintf(s, "play \"%s\"", szShort);
			mciSendStringA(s, nullptr, 0, nullptr);

			db_free(&dbv);
		}
	}
}

static void UpdateReminderEvent(REMINDERDATA *pReminder, UINT nElapsedSeconds, DWORD *pHasPlayedSound)
{
	DWORD dwSoundMask;

	if (pReminder->RepeatSound) {
		if (nElapsedSeconds >= pReminder->RepeatSoundTTL) {
			pReminder->RepeatSoundTTL = pReminder->RepeatSound;

			dwSoundMask = 1 << pReminder->SoundSel;

			if (!(*pHasPlayedSound & dwSoundMask)) {
				switch (pReminder->SoundSel) {
				case 1: Skin_PlaySoundPoly("AlertReminder2"); break;
				case 2: Skin_PlaySoundPoly("AlertReminder3"); break;
				default:
					Skin_PlaySoundPoly("AlertReminder");
				}

				*pHasPlayedSound |= dwSoundMask;
			}
		}
		else pReminder->RepeatSoundTTL -= nElapsedSeconds;
	}
}

static void FireReminder(REMINDERDATA *pReminder, DWORD *pHasPlayedSound)
{
	if (pReminder->bSystemEventQueued)
		return;

	// add a system event
	CLISTEVENT ev = {};
	ev.hIcon = g_hReminderIcon;
	ev.flags = CLEF_URGENT;
	ev.lParam = (LPARAM)pReminder->uid;
	ev.pszService = MODULENAME"/OpenTriggeredReminder";
	ev.szTooltip.a = Translate("Reminder");
	g_clistApi.pfnAddEvent(&ev);

	pReminder->bSystemEventQueued = true;
	QueuedReminderCount++;

	if (pReminder->SoundSel < 0) // sound disabled
		return;

	DWORD dwSoundMask = 1 << pReminder->SoundSel;

	pReminder->RepeatSoundTTL = pReminder->RepeatSound;

	if (!(*pHasPlayedSound & dwSoundMask)) {
		switch (pReminder->SoundSel) {
		case 1: Skin_PlaySoundPoly("AlertReminder2"); break;
		case 2: Skin_PlaySoundPoly("AlertReminder3"); break;
		default:
			Skin_PlaySoundPoly("AlertReminder");
		}

		*pHasPlayedSound |= dwSoundMask;
	}
}


bool CheckRemindersAndStart(void)
{
	// returns TRUE if there are any triggered reminder with bSystemEventQueued, this will shorten the update interval
	// allowing sound repeats with shorter intervals

	if (!arReminders.getCount())
		return false;

	ULARGE_INTEGER curT;
	SYSTEMTIME tm;
	GetSystemTime(&tm);
	SystemTimeToFileTime(&tm, (FILETIME*)&curT);

	// NOTE: reminder list is sorted by trigger time, so we can early out on the first reminder > cur time
	// quick check for normal case with no reminder ready to be triggered and no queued triggered reminders
	// (happens 99.99999999999% of the time)
	if (curT.QuadPart < arReminders[0]->When.QuadPart && !QueuedReminderCount)
		return false;

	bool bResult = false;

	// var used to avoid playing multiple alarm sounds during a single update
	DWORD bHasPlayedSound = 0;

	// if there are queued (triggered) reminders then iterate through entire list, becaue of WM_TIMECHANGE events
	// and for example daylight saving changes it's possible for an already triggered event to end up with When>curT
	bool bHasQueuedReminders = (QueuedReminderCount != 0);

	// allthough count should always be correct, it's fool proof to just count them again in the loop below
	QueuedReminderCount = 0;

	for (auto &pReminder : arReminders) {
		if (!bHasQueuedReminders && pReminder->When.QuadPart > curT.QuadPart)
			break;

		if (!pReminder->bVisible) {
			if (pReminder->bSystemEventQueued) {
				UpdateReminderEvent(pReminder, REMINDER_UPDATE_INTERVAL_SHORT / 1000, &bHasPlayedSound);

				QueuedReminderCount++;
				bResult = true;
			}
			else if (pReminder->When.QuadPart <= curT.QuadPart) {
				if (!g_RemindSMS) {
					FireReminder(pReminder, &bHasPlayedSound);

					if (pReminder->bSystemEventQueued)
						bResult = true;
				}
				else {
					char *S2 = strchr(g_RemindSMS, '@');
					char *S1 = (char*)malloc(S2 - g_RemindSMS);

					strncpy(S1, g_RemindSMS, S2 - g_RemindSMS);
					S1[S2 - g_RemindSMS] = 0x0;
					S2++;
					Send(S1, S2, pReminder->Reminder ? pReminder->Reminder : "", NULL);
					SAFE_FREE((void**)&S1);
					DeleteReminder(pReminder);
					JustSaveReminders();
					NOTIFY_LIST();
				}
			}
		}
	}

	return bResult;
}

static LRESULT CALLBACK DatePickerWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message) {
	case WM_RBUTTONDOWN:
	case WM_RBUTTONUP:
	case WM_RBUTTONDBLCLK:
	case WM_KEYDOWN:
	case WM_KEYUP:
	case WM_CHAR:
	case WM_INITMENUPOPUP:
	case WM_PASTE:
		return TRUE;
	case WM_SYSKEYUP:
	case WM_SYSKEYDOWN:
	case WM_SYSCHAR:
		return FALSE;
	}

	return mir_callNextSubclass(hWnd, DatePickerWndProc, message, wParam, lParam);
}

static void InitDatePicker(HWND hwndDlg, UINT nIDDate)
{
	// subclass date picker to prevent user editing (should only use the dropdown calender to ensure valid dates)
	HWND hCtrl = GetDlgItem(hwndDlg, nIDDate);

	// tweak style of picker
	if (IsWinVerVistaPlus()) {
		DWORD dw = SendDlgItemMessage(hwndDlg, nIDDate, DTM_GETMCSTYLE, 0, 0);
		dw |= MCS_WEEKNUMBERS | MCS_NOSELCHANGEONNAV;
		SendDlgItemMessage(hwndDlg, nIDDate, DTM_SETMCSTYLE, 0, dw);
	}

	mir_subclassWindow(hCtrl, DatePickerWndProc);
}

static BOOL ParseTime(const wchar_t *s, int *hout, int *mout, BOOL bTimeOffset, BOOL bAllowOffsetOverride)
{
	// validate format: <WS><digit>[<digit>]<WS>[':'<WS><digit>[<digit>]]<WS>[p | P].*

	// if bTimeOffset is FALSE the user may still enter a time offset by using + as the first char, the
	// delta time will be returned in minutes (even > 60) and hout will always be -1

	// if bTimeOffset is TRUE time is always interpreted as an offset (ignores PM indicator and defaults to minutes)

	int h, m;
	BOOL bOffset = bTimeOffset;

	// read hour

	while (iswspace(*s)) s++;

	if (*s == '+') {
		if (!bTimeOffset) {
			if (!bAllowOffsetOverride)
				return FALSE;

			// treat value as an offset anyway
			bOffset = TRUE;
		}

		s++;
		while (iswspace(*s)) s++;
	}

	if (!iswdigit(*s))
		return FALSE;
	h = (int)(*s - '0');
	s++;

	if (!bOffset) {
		if (iswdigit(*s)) {
			h = h * 10 + (int)(*s - '0');
			s++;
		}

		if (iswdigit(*s))
			return FALSE;
	}
	else {
		// allow more than 2-digit numbers for offset
		while (iswdigit(*s)) {
			h = h * 10 + (int)(*s - '0');
			s++;
		}
	}

	// find : separator
	while (iswspace(*s))
		s++;

	if (*s == ':') {
		s++;

		// read minutes

		while (iswspace(*s)) s++;

		if (!isdigit(*s))
			return FALSE;
		m = (int)(*s - '0');
		s++;

		if (iswdigit(*s)) {
			m = m * 10 + (int)(*s - '0');
			s++;
		}
	}
	else {
		if (bOffset) {
			// no : separator found, interpret the entered number as minutes and allow > 60

			if (h < 0)
				return FALSE;

			if (bTimeOffset) {
				*hout = h / 60;
				*mout = h % 60;
			}
			else {
				*mout = h;
				*hout = -1;
			}

			return TRUE;
		}
		else {
			m = 0;
		}
	}

	// validate time
	if (bOffset) {
		if (h < 0)
			return FALSE;
		if (m < 0 || m > 59)
			return FALSE;
	}
	else {
		if (h == 24)
			h = 0;
		else if (h < 0 || h > 23)
			return FALSE;
		if (m < 0 || m > 59)
			return FALSE;
	}

	if (!bOffset) {
		// check for PM indicator (not strict, only checks for P char)

		while (iswspace(*s)) s++;

		if (*s == 'p' || *s == 'P') {
			if (h < 13)
				h += 12;
			else if (h == 12)
				h = 0;
		}
	}
	else if (!bTimeOffset) {
		// entered time is an offset

		*mout = h * 60 + m;
		*hout = -1;

		return TRUE;
	}

	*hout = h;
	*mout = m;

	return TRUE;
}

// returns TRUE if combo box list displays time offsets ("23:34 (5 Minutes)" etc.)
__inline static BOOL IsRelativeCombo(HWND hwndDlg, UINT nIDTime)
{
	return (((int)SendDlgItemMessage(hwndDlg, nIDTime, CB_GETITEMDATA, 0, 0)) >= 0);
}

static void PopulateTimeCombo(HWND hwndDlg, UINT nIDTime, BOOL bRelative, const SYSTEMTIME *tmUtc)
{
	// NOTE: may seem like a bit excessive time converstion and handling, but this is done in order
	//       to gracefully handle crossing daylight saving boundaries

	SendDlgItemMessage(hwndDlg, nIDTime, CB_RESETCONTENT, 0, 0);

	SYSTEMTIME tm2;
	ULARGE_INTEGER li;
	wchar_t s[64];
	const ULONGLONG MinutesToFileTime = (ULONGLONG)60 * FILETIME_TICKS_PER_SEC;

	if (!bRelative) {

		// ensure that we start on midnight local time
		SystemTimeToTzSpecificLocalTime(nullptr, (SYSTEMTIME*)tmUtc, &tm2);
		tm2.wHour = 0;
		tm2.wMinute = 0;
		tm2.wSecond = 0;
		tm2.wMilliseconds = 0;
		TzSpecificLocalTimeToSystemTime(nullptr, &tm2, &tm2);
		SystemTimeToFileTime(&tm2, (FILETIME*)&li);

		// from 00:00 to 23:30 in 30 minute steps
		for (int i = 0; i < 50; i++) {
			const int h = i >> 1;
			const int m = (i & 1) ? 30 : 0;

			FileTimeToTzLocalST((FILETIME*)&li, &tm2);
			mir_snwprintf(s, L"%02d:%02d", (UINT)tm2.wHour, (UINT)tm2.wMinute);
			int n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
			// item data contains time offset from midnight in seconds (bit 31 is set to flag that
			// combo box items are absolute times and not relative times like below
			SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((ULONG)((h * 60 + m) * 60) | 0x80000000));

			li.QuadPart += (ULONGLONG)30 * MinutesToFileTime;

			if (tm2.wHour == 23 && tm2.wMinute >= 30)
				break;
		}
	}

	////////////////////////////////////////////////////////////////////////////////////////

	SystemTimeToFileTime(tmUtc, (FILETIME*)&li);
	ULONGLONG ref = li.QuadPart;

	// NOTE: item data contains offset from reference time (tmUtc) in seconds

	// cur time
	FileTimeToTzLocalST((FILETIME*)&li, &tm2);
	WORD wCurHour = tm2.wHour;
	WORD wCurMinute = tm2.wMinute;
	mir_snwprintf(s, L"%02d:%02d", (UINT)tm2.wHour, (UINT)tm2.wMinute);
	int n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
	SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((li.QuadPart - ref) / FILETIME_TICKS_PER_SEC));

	// 5 minutes
	li.QuadPart += (ULONGLONG)5 * MinutesToFileTime;
	FileTimeToTzLocalST((FILETIME*)&li, &tm2);
	mir_snwprintf(s, L"%02d:%02d (5 %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, TranslateT("Minutes"));
	n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
	SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((li.QuadPart - ref) / FILETIME_TICKS_PER_SEC));

	// 10 minutes
	li.QuadPart += (ULONGLONG)5 * MinutesToFileTime;
	FileTimeToTzLocalST((FILETIME*)&li, &tm2);
	mir_snwprintf(s, L"%02d:%02d (10 %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, TranslateT("Minutes"));
	n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
	SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((li.QuadPart - ref) / FILETIME_TICKS_PER_SEC));

	// 15 minutes
	li.QuadPart += (ULONGLONG)5 * MinutesToFileTime;
	FileTimeToTzLocalST((FILETIME*)&li, &tm2);
	mir_snwprintf(s, L"%02d:%02d (15 %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, TranslateT("Minutes"));
	n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
	SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((li.QuadPart - ref) / FILETIME_TICKS_PER_SEC));

	// 30 minutes
	li.QuadPart += (ULONGLONG)15 * MinutesToFileTime;
	FileTimeToTzLocalST((FILETIME*)&li, &tm2);
	mir_snwprintf(s, L"%02d:%02d (30 %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, TranslateT("Minutes"));
	n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
	SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, (LPARAM)((li.QuadPart - ref) / FILETIME_TICKS_PER_SEC));

	// round +1h time to nearest even or half hour
	li.QuadPart += (ULONGLONG)30 * MinutesToFileTime;
	li.QuadPart = (li.QuadPart / (30 * MinutesToFileTime)) * (30 * MinutesToFileTime);

	// add from +1 to +23.5 (in half hour steps) if crossing daylight saving boundary it may be 22.5 or 24.5 hours
	for (int i = 0; i < 50; i++) {
		UINT dt;

		FileTimeToTzLocalST((FILETIME*)&li, &tm2);

		if (i > 40) {
			UINT nLastEntry = ((UINT)wCurHour * 60 + (UINT)wCurMinute) / 30;
			if (nLastEntry)
				nLastEntry *= 30;
			else
				nLastEntry = 23 * 60 + 30;

			if (((UINT)tm2.wHour * 60 + (UINT)tm2.wMinute) == nLastEntry)
				break;
		}

		// icq-style display 1.0, 1.5 etc. hours even though that isn't accurate due to rounding
		//mir_snwprintf(s, L"%02d:%02d (%d.%d %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, 1+(i>>1), (i&1) ? 5 : 0, lpszHours);
		// display delta time more accurately to match reformatting (that icq doesn't do)
		dt = (UINT)((li.QuadPart / MinutesToFileTime) - (ref / MinutesToFileTime));
		if (dt < 60)
			mir_snwprintf(s, L"%02d:%02d (%d %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, dt, TranslateT("Minutes"));
		else
			mir_snwprintf(s, L"%02d:%02d (%d.%d %s)", (UINT)tm2.wHour, (UINT)tm2.wMinute, dt / 60, ((dt % 60) * 10) / 60, TranslateT("Hours"));
		n = SendDlgItemMessage(hwndDlg, nIDTime, CB_ADDSTRING, 0, (LPARAM)s);
		SendDlgItemMessage(hwndDlg, nIDTime, CB_SETITEMDATA, n, dt * 60);

		li.QuadPart += (ULONGLONG)30 * MinutesToFileTime;
	}
}

// returns non-zero if specified time was inside "missing" hour of daylight saving
// IMPORTANT: triggerRelUtcOut is only initialized if IsRelativeCombo() is TRUE and return value is 0
static int ReformatTimeInput(HWND hwndDlg, UINT nIDTime, UINT nIDRefTime, int h, int m, const SYSTEMTIME *pDateLocal, ULARGE_INTEGER *triggerRelUtcOut = nullptr)
{
	int n;
	UINT dt;
	const ULONGLONG MinutesToFileTime = (ULONGLONG)60 * FILETIME_TICKS_PER_SEC;

	if (h < 0) {
		// time value is an offset ('m' holds the offset in minutes)

		if (IsRelativeCombo(hwndDlg, nIDTime)) {
			// get reference time (UTC) from hidden control
			wchar_t buf[64];
			GetDlgItemText(hwndDlg, nIDRefTime, buf, 30);

			ULONGLONG ref;
			ULARGE_INTEGER li;
			li.QuadPart = ref = _wcstoui64(buf, nullptr, 16);

			// clamp delta time to 23.5 hours (coule be issues otherwise as relative combo only handles <24)
			if (m > (23 * 60 + 30))
				m = 23 * 60 + 30;

			li.QuadPart += (ULONGLONG)(m * 60) * FILETIME_TICKS_PER_SEC;

			SYSTEMTIME tm;
			FileTimeToTzLocalST((FILETIME*)&li, &tm);
			h = (int)tm.wHour;
			m = (int)tm.wMinute;

			if (triggerRelUtcOut)
				*triggerRelUtcOut = li;

			dt = (UINT)((li.QuadPart / MinutesToFileTime) - (ref / MinutesToFileTime));

			if (dt < 60)
				mir_snwprintf(buf, L"%02d:%02d (%d %s)", h, m, dt, TranslateT("Minutes"));
			else
				mir_snwprintf(buf, L"%02d:%02d (%d.%d %s)", h, m, dt / 60, ((dt % 60) * 10) / 60, TranslateT("Hours"));

			// search for preset
			n = SendDlgItemMessage(hwndDlg, nIDTime, CB_FINDSTRING, (WPARAM)-1, (LPARAM)buf);
			if (n != CB_ERR) {
				SendDlgItemMessage(hwndDlg, nIDTime, CB_SETCURSEL, n, 0);
				return 0;
			}

			SetDlgItemText(hwndDlg, nIDTime, buf);
		}
		else {
			// should never happen
			SendDlgItemMessage(hwndDlg, nIDTime, CB_SETCURSEL, 0, 0);
		}

		return 0;
	}

	wchar_t buf[64];
	mir_snwprintf(buf, L"%02d:%02d", h, m);

	// search for preset first
	n = SendDlgItemMessage(hwndDlg, nIDTime, CB_FINDSTRING, (WPARAM)-1, (LPARAM)buf);
	if (n != CB_ERR) {
		SendDlgItemMessage(hwndDlg, nIDTime, CB_SETCURSEL, n, 0);
		return 0;
	}

	if (IsRelativeCombo(hwndDlg, nIDTime)) {
		// date format is a time offset ("24:43 (5 Minutes)" etc.)

		SYSTEMTIME tmTriggerLocal, tmTriggerLocal2;

		// get reference time (UTC) from hidden control
		GetDlgItemText(hwndDlg, nIDRefTime, buf, 30);
		ULONGLONG ref = _wcstoui64(buf, nullptr, 16);

		SYSTEMTIME tmRefLocal;
		FileTimeToTzLocalST((FILETIME*)&ref, &tmRefLocal);

		ULARGE_INTEGER li;
		const UINT nRefT = (UINT)tmRefLocal.wHour * 60 + (UINT)tmRefLocal.wMinute;
		const UINT nT = h * 60 + m;

		tmTriggerLocal = tmRefLocal;
		tmTriggerLocal.wHour = (WORD)h;
		tmTriggerLocal.wMinute = (WORD)m;
		tmTriggerLocal.wSecond = 0;
		tmTriggerLocal.wMilliseconds = 0;

		if (nT < nRefT) {
			// (this special case only works correctly if time can be returned in triggerRelUtcOut)
			if (tmRefLocal.wHour == tmTriggerLocal.wHour && triggerRelUtcOut) {
				// check for special case if daylight saving ends in this hour, then interpret as within the next hour
				TzLocalSTToFileTime(&tmTriggerLocal, (FILETIME*)&li);
				li.QuadPart += (ULONGLONG)3600 * FILETIME_TICKS_PER_SEC;
				FileTimeToTzLocalST((FILETIME*)&li, &tmTriggerLocal2);
				if ((tmTriggerLocal2.wHour * 60 + tmTriggerLocal2.wMinute) == (tmTriggerLocal.wHour * 60 + tmTriggerLocal.wMinute))
					// special case detected
					goto output_result;
			}

			// tomorrow (add 24h to local time)
			SystemTimeToFileTime(&tmTriggerLocal, (FILETIME*)&li);
			li.QuadPart += (ULONGLONG)(24 * 3600)*FILETIME_TICKS_PER_SEC;
			FileTimeToSystemTime((FILETIME*)&li, &tmTriggerLocal);
		}

		// clean up value for potential daylight saving boundary
		TzLocalSTToFileTime(&tmTriggerLocal, (FILETIME*)&li);
		FileTimeToTzLocalST((FILETIME*)&li, &tmTriggerLocal2);

		// NOTE: win32 time functions will round hour downward if supplied hour does not exist due to daylight saving
		//       for example if supplied time is 02:30 on the night the clock is turned forward at 02:00 to 03:00, thus
		//       there never is a 02:30, the time functions will convert it to 01:30 (and not 03:30 as one might think)
		//       (02:00 would return 01:00)

		// check for special case when the current time and requested time is inside the "missing" hour
		// standard->daylight switch, so that the cleaned up time ends up being earlier than the current
		// time even though it originally wasn't (see note above)
		if ((tmTriggerLocal2.wHour * 60 + tmTriggerLocal2.wMinute) < (tmTriggerLocal.wHour * 60 + tmTriggerLocal.wMinute)) {
			// special case detected, fall back to current time so at least the reminder won't be missed
			// due to ending up at an undesired time (this way the user immediately notices something was wrong)
			SendDlgItemMessage(hwndDlg, nIDTime, CB_SETCURSEL, 0, 0);
invalid_dst:
			MessageBox(hwndDlg, TranslateT("The specified time is invalid due to begin of daylight saving (summer time)."), _A2W(SECTIONNAME), MB_OK | MB_ICONWARNING);
			return 1;
		}

output_result:
		if (triggerRelUtcOut)
			*triggerRelUtcOut = li;

		dt = (UINT)((li.QuadPart / MinutesToFileTime) - (ref / MinutesToFileTime));

		if (dt < 60)
			mir_snwprintf(buf, L"%02d:%02d (%d %s)", h, m, dt, TranslateT("Minutes"));
		else
			mir_snwprintf(buf, L"%02d:%02d (%d.%d %s)", h, m, dt / 60, ((dt % 60) * 10) / 60, TranslateT("Hours"));
	}
	else {
		// absolute time (00:00 to 23:59), clean up time to make sure it's not inside "missing" hour (will be rounded downard)
		SYSTEMTIME Date = *pDateLocal;
		Date.wHour = h;
		Date.wMinute = m;
		Date.wSecond = 0;
		Date.wMilliseconds = 0;

		FILETIME ft;
		TzLocalSTToFileTime(&Date, &ft);
		FileTimeToTzLocalST(&ft, &Date);

		if ((int)Date.wHour != h || (int)Date.wMinute != m) {
			mir_snwprintf(buf, L"%02d:%02d", Date.wHour, Date.wMinute);

			// search for preset again
			n = SendDlgItemMessage(hwndDlg, nIDTime, CB_FINDSTRING, -1, (LPARAM)buf);
			if (n != CB_ERR) {
				SendDlgItemMessage(hwndDlg, nIDTime, CB_SETCURSEL, n, 0);
				goto invalid_dst;
			}

			SetDlgItemText(hwndDlg, nIDTime, buf);
			goto invalid_dst;
		}
	}

	SetDlgItemText(hwndDlg, nIDTime, buf);
	return 0;
}

// in:  pDate contains the desired trigger date in LOCAL time
// out: pDate contains the resulting trigger time and date in UTC
static bool GetTriggerTime(HWND hwndDlg, UINT nIDTime, UINT nIDRefTime, SYSTEMTIME *pDate)
{
	// get reference (UTC) time from hidden control
	wchar_t buf[32];
	GetDlgItemText(hwndDlg, nIDRefTime, buf, 30);
	ULARGE_INTEGER li;
	li.QuadPart = _wcstoui64(buf, nullptr, 16);

	int n = SendDlgItemMessage(hwndDlg, nIDTime, CB_GETCURSEL, 0, 0);
	if (n != CB_ERR) {
		// use preset value
preset_value:;
		if (IsRelativeCombo(hwndDlg, nIDTime)) {
			// time offset from ref time ("24:43 (5 Minutes)" etc.)

			UINT nDeltaSeconds = (UINT)SendDlgItemMessage(hwndDlg, nIDTime, CB_GETITEMDATA, n, 0);
			li.QuadPart += (ULONGLONG)nDeltaSeconds * FILETIME_TICKS_PER_SEC;

			FileTimeToSystemTime((FILETIME*)&li, pDate);

			// if specified time is a small offset (< 10 Minutes) then retain current second count for better accuracy
			// otherwise try to match specified time (which never contains seconds only even minutes) as close as possible
			if (nDeltaSeconds >= 10 * 60) {
				pDate->wSecond = 0;
				pDate->wMilliseconds = 0;
			}
		}
		else {
			// absolute time (offset from midnight on pDate)

			UINT nDeltaSeconds = (UINT)((ULONG)SendDlgItemMessage(hwndDlg, nIDTime, CB_GETITEMDATA, n, 0) & ~0x80000000);
			pDate->wHour = 0;
			pDate->wMinute = 0;
			pDate->wSecond = 0;
			pDate->wMilliseconds = 0;
			TzLocalSTToFileTime(pDate, (FILETIME*)&li);
			li.QuadPart += (ULONGLONG)nDeltaSeconds * FILETIME_TICKS_PER_SEC;

			FileTimeToSystemTime((FILETIME*)&li, pDate);
		}
		return true;
	}

	// user entered a custom value
	GetDlgItemText(hwndDlg, nIDTime, buf, 30);

	int h, m;
	if (!ParseTime(buf, &h, &m, FALSE, IsRelativeCombo(hwndDlg, nIDTime))) {
		MessageBox(hwndDlg, TranslateT("The specified time is invalid."), _A2W(SECTIONNAME), MB_OK | MB_ICONWARNING);
		return false;
	}

	if (IsRelativeCombo(hwndDlg, nIDTime)) {
		// date has not been changed, the specified time is a time between reftime and reftime+24h
		ULARGE_INTEGER li2;
		if (ReformatTimeInput(hwndDlg, nIDTime, nIDRefTime, h, m, pDate, &li2))
			return FALSE;

		// check if reformatted value is a preset
		if ((n = SendDlgItemMessage(hwndDlg, nIDTime, CB_GETCURSEL, 0, 0)) != CB_ERR)
			goto preset_value;

		FileTimeToSystemTime((FILETIME*)&li2, pDate);
		return true;
	}

	if (ReformatTimeInput(hwndDlg, nIDTime, nIDRefTime, h, m, pDate, nullptr))
		return false;

	// check if reformatted value is a preset
	if ((n = SendDlgItemMessage(hwndDlg, nIDTime, CB_GETCURSEL, 0, 0)) != CB_ERR)
		goto preset_value;

	// absolute time (on pDate)
	pDate->wHour = h;
	pDate->wMinute = m;
	pDate->wSecond = 0;
	pDate->wMilliseconds = 0;

	TzLocalSTToFileTime(pDate, (FILETIME*)&li);
	FileTimeToSystemTime((FILETIME*)&li, pDate);
	return true;
}

static void OnDateChanged(HWND hwndDlg, UINT nDateID, UINT nTimeID, UINT nRefTimeID)
{
	// repopulate time combo list with regular times (not offsets like "23:32 (5 minutes)" etc.)
	wchar_t s[32];
	GetDlgItemText(hwndDlg, nTimeID, s, _countof(s));

	int h = -1, m;
	ParseTime(s, &h, &m, FALSE, FALSE);

	SYSTEMTIME Date, DateUtc;
	SendDlgItemMessage(hwndDlg, nDateID, DTM_GETSYSTEMTIME, 0, (LPARAM)&Date);

	TzSpecificLocalTimeToSystemTime(nullptr, &Date, &DateUtc);
	PopulateTimeCombo(hwndDlg, nTimeID, FALSE, &DateUtc);

	if (h < 0) {
		// parsing failed, default to current time
		SYSTEMTIME tm;
		GetLocalTime(&tm);
		h = (UINT)tm.wHour;
		m = (UINT)tm.wMinute;
	}

	ReformatTimeInput(hwndDlg, nTimeID, nRefTimeID, h, m, &Date);
}

/////////////////////////////////////////////////////////////////////////////////////////
// Reminder notification dialog

class CReminderNotifyDlg : public CDlgBase
{
	REMINDERDATA *m_pReminder;

	void PopulateTimeOffsetCombo()
	{
		cmbRemindAgainIn.ResetContent();

		// 5 - 55 minutes (in 5 minute steps)
		wchar_t s[MAX_PATH];
		for (int i = 1; i < 12; i++) {
			mir_snwprintf(s, L"%d %s", i * 5, TranslateT("Minutes"));
			cmbRemindAgainIn.AddString(s, i * 5);
		}

		// 1 hour
		mir_snwprintf(s, L"1 %s", TranslateT("Hour"));
		cmbRemindAgainIn.AddString(s, 60);

		// 2, 4, 8 hours
		for (int i = 2; i <= 8; i += 2) {
			mir_snwprintf(s, L"%d %s", i, TranslateT("Hours"));
			cmbRemindAgainIn.AddString(s, i * 60);
		}

		// 1 day
		mir_snwprintf(s, L"1 %s", TranslateT("Day"));
		cmbRemindAgainIn.AddString(s, 24 * 60);

		// 2-4 days
		for (int i = 2; i <= 4; i++) {
			mir_snwprintf(s, L"%d %s", i, TranslateT("Days"));
			cmbRemindAgainIn.AddString(s, i * 24 * 60);
		}

		// 1 week
		mir_snwprintf(s, L"1 %s", TranslateT("Week"));
		cmbRemindAgainIn.AddString(s, 7 * 24 * 60);
	}

	CCtrlDate dateAgain;
	CCtrlCheck chkAfter, chkOnDate;
	CCtrlCombo cmbTimeAgain, cmbRemindAgainIn;
	CCtrlButton btnDismiss, btnNone, btnRemindAgain;

public:
	CReminderNotifyDlg(REMINDERDATA *pReminder) :
		CDlgBase(g_plugin, IDD_NOTIFYREMINDER),
		m_pReminder(pReminder),
		btnNone(this, IDC_NONE),
		btnDismiss(this, IDC_DISMISS),
		btnRemindAgain(this, IDC_REMINDAGAIN),
		chkAfter(this, IDC_AFTER),
		chkOnDate(this, IDC_ONDATE),
		dateAgain(this, IDC_DATEAGAIN),
		cmbTimeAgain(this, IDC_TIMEAGAIN),
		cmbRemindAgainIn(this, IDC_REMINDAGAININ)
	{
		chkAfter.OnChange = Callback(this, &CReminderNotifyDlg::onChange_After);
		chkOnDate.OnChange = Callback(this, &CReminderNotifyDlg::onChange_OnDate);

		cmbTimeAgain.OnKillFocus = Callback(this, &CReminderNotifyDlg::onKillFocus_TimeAgain);
		cmbRemindAgainIn.OnKillFocus = Callback(this, &CReminderNotifyDlg::onKillFocus_RemindAgain);

		btnNone.OnClick = Callback(this, &CReminderNotifyDlg::onClick_None);
		btnDismiss.OnClick = Callback(this, &CReminderNotifyDlg::onClick_Dismiss);
		btnRemindAgain.OnClick = Callback(this, &CReminderNotifyDlg::onClick_RemindAgain);
	}

	bool OnInitDialog() override
	{
		m_pReminder->handle = m_hwnd;
		m_pReminder->bVisible = true;

		SYSTEMTIME tm;
		ULARGE_INTEGER li = m_pReminder->When;
		FileTimeToSystemTime((FILETIME*)&li, &tm);

		// save reference time in hidden control, is needed when adding reminder to properly detect if speicifed
		// time wrapped around to tomorrow or not (dialog could in theory be open for a longer period of time
		// which could potentially mess up things otherwise)
		wchar_t s[32];
		mir_snwprintf(s, L"%I64x", li.QuadPart);
		SetDlgItemText(m_hwnd, IDC_REFTIME, s);

		BringWindowToTop(m_hwnd);

		PopulateTimeOffsetCombo();

		cmbRemindAgainIn.Show();
		dateAgain.Hide();
		cmbTimeAgain.Hide();
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_DATE), SW_HIDE);
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_TIME), SW_HIDE);
		chkAfter.SetState(true);
		chkOnDate.SetState(false);
		cmbRemindAgainIn.SetCurSel(0);

		if (m_pReminder->bRepeat) {
			chkOnDate.Hide();
			chkAfter.Disable();
			cmbRemindAgainIn.Disable();
			cmbRemindAgainIn.SetCurSel(16);
		}

		SendDlgItemMessage(m_hwnd, IDC_REMDATA, EM_LIMITTEXT, MAX_REMINDER_LEN, 0);

		PopulateTimeCombo(m_hwnd, IDC_TIMEAGAIN, TRUE, &tm);

		FileTimeToTzLocalST((FILETIME*)&li, &tm);

		// make sure date picker uses reference time
		dateAgain.SetTime(&tm);
		InitDatePicker(m_hwnd, IDC_DATEAGAIN);

		cmbTimeAgain.SetCurSel(0);

		wchar_t S1[128], S2[MAX_PATH];
		GetTriggerTimeString(&m_pReminder->When, S1, sizeof(S1), TRUE);
		mir_snwprintf(S2, L"%s! - %s", TranslateT("Reminder"), S1);
		SetCaption(S2);

		if (m_pReminder->Reminder)
			SetDlgItemTextA(m_hwnd, IDC_REMDATA, m_pReminder->Reminder);
		return true;
	}

	bool OnClose() override
	{
		if (m_pReminder)
			DeleteReminder(m_pReminder);
		JustSaveReminders();
		NOTIFY_LIST();
		return true;
	}

	void onChange_After(CCtrlCheck*)
	{
		cmbRemindAgainIn.Show();
		dateAgain.Hide();
		cmbTimeAgain.Hide();
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_DATE), SW_HIDE);
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_TIME), SW_HIDE);
	}

	void onChange_OnDate(CCtrlCheck*)
	{
		dateAgain.Show();
		cmbTimeAgain.Show();
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_DATE), SW_SHOW);
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_TIME), SW_SHOW);
		cmbRemindAgainIn.Hide();
	}

	void onChange_Date(CCtrlDate*)
	{
		OnDateChanged(m_hwnd, IDC_DATEAGAIN, IDC_TIMEAGAIN, IDC_REFTIME);
	}

	void onKillFocus_TimeAgain(CCtrlCombo*)
	{
		// reformat displayed value
		if (cmbTimeAgain.GetCurSel() == -1) {
			wchar_t buf[64];
			cmbTimeAgain.GetText(buf, _countof(buf));

			int h, m;
			if (ParseTime(buf, &h, &m, FALSE, IsRelativeCombo(m_hwnd, IDC_TIMEAGAIN))) {
				SYSTEMTIME Date;
				dateAgain.GetTime(&Date);
				ReformatTimeInput(m_hwnd, IDC_TIMEAGAIN, IDC_REFTIME, h, m, &Date);
			}
			else cmbTimeAgain.SetCurSel(0);
		}
	}

	void onKillFocus_RemindAgain(CCtrlCombo*)
	{
		// reformat displayed value if it has been edited
		if (cmbRemindAgainIn.GetCurSel() == -1) {
			wchar_t buf[64];
			cmbRemindAgainIn.GetText(buf, 30);

			int h, m;
			if (ParseTime(buf, &h, &m, TRUE, TRUE) && h + m) {
				if (h)
					mir_snwprintf(buf, L"%d:%02d %s", h, m, TranslateT("Hours"));
				else
					mir_snwprintf(buf, L"%d %s", m, TranslateT("Minutes"));

				cmbRemindAgainIn.SetText(buf);
			}
			else cmbRemindAgainIn.SetCurSel(0);
		}
	}

	void onClick_Dismiss(CCtrlButton*)
	{
		Close();
	}

	void onClick_RemindAgain(CCtrlButton*)
	{
		if (chkAfter.GetState()) {
			// delta time
			SYSTEMTIME tm;
			ULARGE_INTEGER li;

			GetSystemTime(&tm);
			SystemTimeToFileTime(&tm, (FILETIME*)&li);

			int TT = cmbRemindAgainIn.GetItemData(cmbRemindAgainIn.GetCurSel()) * 60;
			if (TT >= 24 * 3600) {
				// selection is 1 day or more, take daylight saving boundaries into consideration
				// (ie. 24 hour might actually be 23 or 25, in order for reminder to pop up at the
				// same time tomorrow)
				SYSTEMTIME tm2, tm3;
				ULARGE_INTEGER li2 = li;
				FileTimeToTzLocalST((FILETIME*)&li2, &tm2);
				li2.QuadPart += (TT * FILETIME_TICKS_PER_SEC);
				FileTimeToTzLocalST((FILETIME*)&li2, &tm3);
				if (tm2.wHour != tm3.wHour || tm2.wMinute != tm3.wMinute) {
					// boundary crossed

					// do a quick and dirty sanity check that times not more than 2 hours apart
					if (abs((int)(tm3.wHour * 60 + tm3.wMinute) - (int)(tm2.wHour * 60 + tm2.wMinute)) <= 120) {
						// adjust TT so that same HH:MM is set
						tm3.wHour = tm2.wHour;
						tm3.wMinute = tm2.wMinute;
						TzLocalSTToFileTime(&tm3, (FILETIME*)&li2);
						TT = (li2.QuadPart - li.QuadPart) / FILETIME_TICKS_PER_SEC;
					}
				}
			}
			else {
				// parse user input
				wchar_t s[32];
				cmbRemindAgainIn.GetText(s, _countof(s));

				int h = 0, m = 0;
				ParseTime(s, &h, &m, TRUE, TRUE);
				m += h * 60;
				if (!m) {
					MessageBox(m_hwnd, TranslateT("The specified time offset is invalid."), _A2W(SECTIONNAME), MB_OK | MB_ICONWARNING);
					return;
				}

				TT = m * 60;
			}

			// reset When from the current time
			if (!m_pReminder->bRepeat)
				m_pReminder->When = li;
			m_pReminder->When.QuadPart += (TT * FILETIME_TICKS_PER_SEC);
		}
		else if (chkOnDate.GetState()) {
			SYSTEMTIME Date;
			dateAgain.GetTime(&Date);
			if (!GetTriggerTime(m_hwnd, IDC_TIMEAGAIN, IDC_REFTIME, &Date))
				return;

			SystemTimeToFileTime(&Date, (FILETIME*)&m_pReminder->When);
		}

		// update reminder text
		char *ReminderText = nullptr;
		int SzT = SendDlgItemMessage(m_hwnd, IDC_REMDATA, WM_GETTEXTLENGTH, 0, 0);
		if (SzT) {
			if (SzT > MAX_REMINDER_LEN) SzT = MAX_REMINDER_LEN;
			ReminderText = (char*)malloc(SzT + 1);
			GetDlgItemTextA(m_hwnd, IDC_REMDATA, ReminderText, SzT + 1);
		}

		if (m_pReminder->Reminder)
			free(m_pReminder->Reminder);
		m_pReminder->Reminder = ReminderText;

		m_pReminder->bVisible = FALSE;
		m_pReminder->handle = nullptr;

		// re-insert tree item sorted
		arReminders.remove(m_pReminder);
		arReminders.insert(m_pReminder);
		m_pReminder = nullptr; // prevent reminder from being deleted;
		Close();
	}

	void onClick_None(CCtrlButton*)
	{
		// create note from remainder
		char *ReminderText = nullptr;
		int SzT = SendDlgItemMessage(m_hwnd, IDC_REMDATA, WM_GETTEXTLENGTH, 0, 0);
		if (SzT) {
			if (SzT > MAX_REMINDER_LEN) SzT = MAX_REMINDER_LEN;
			ReminderText = (char*)malloc(SzT + 1);
			GetDlgItemTextA(m_hwnd, IDC_REMDATA, ReminderText, SzT + 1);
		}

		NewNote(0, 0, -1, -1, ReminderText, nullptr, TRUE, TRUE, 0);
	}
};

INT_PTR OpenTriggeredReminder(WPARAM, LPARAM l)
{
	if (!l)
		return 0;

	l = ((CLISTEVENT*)l)->lParam;

	REMINDERDATA *pReminder = (REMINDERDATA*)FindReminder((DWORD)l);
	if (!pReminder || !pReminder->bSystemEventQueued)
		return 0;

	pReminder->bSystemEventQueued = false;
	if (QueuedReminderCount)
		QueuedReminderCount--;

	(new CReminderNotifyDlg(pReminder))->Show();
	return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////

class CReminderFormDlg : public CDlgBase
{
	REMINDERDATA *m_pReminder;

	CCtrlDate date;
	CCtrlCheck chkRepeat;
	CCtrlCombo cmbSound, cmbRepeat, cmbTime;
	CCtrlButton btnAdd, btnView, btnPlaySound;

public:
	CReminderFormDlg(REMINDERDATA *pReminder = nullptr) :
		CDlgBase(g_plugin, IDD_ADDREMINDER),
		m_pReminder(pReminder),
		date(this, IDC_DATE),
		btnAdd(this, IDC_ADDREMINDER),
		btnView(this, IDC_VIEWREMINDERS),
		btnPlaySound(this, IDC_BTN_PLAYSOUND),
		chkRepeat(this, IDC_CHECK_REPEAT),
		cmbTime(this, IDC_COMBOREMINDERTIME),
		cmbSound(this, IDC_COMBO_SOUND),
		cmbRepeat(this, IDC_COMBO_REPEATSND)
	{
		btnAdd.OnClick = Callback(this, &CReminderFormDlg::onClick_Add);
		btnView.OnClick = Callback(this, &CReminderFormDlg::onClick_View);
		btnPlaySound.OnClick = Callback(this, &CReminderFormDlg::onClick_PlaySound);

		date.OnChange = Callback(this, &CReminderFormDlg::onChange_Date);
		cmbSound.OnChange = Callback(this, &CReminderFormDlg::onChange_Sound);

		cmbTime.OnKillFocus = Callback(this, &CReminderFormDlg::onChange_Time);
	}

	bool OnInitDialog() override
	{
		ULARGE_INTEGER li;
		SYSTEMTIME tm;

		if (m_pReminder) {
			// opening the edit reminder dialog (uses same dialog resource as add reminder)
			SetWindowText(m_hwnd, TranslateT("Reminder"));
			SetDlgItemText(m_hwnd, IDC_ADDREMINDER, TranslateT("&Update Reminder"));
			btnView.Hide();

			li = m_pReminder->When;
			FileTimeToSystemTime((FILETIME*)&li, &tm);
		}
		else {
			GetSystemTime(&tm);
			SystemTimeToFileTime(&tm, (FILETIME*)&li);
		}

		// save reference time in hidden control, is needed when adding reminder to properly detect if speicifed
		// time wrapped around to tomorrow or not (dialog could in theory be open for a longer period of time
		// which could potentially mess up things otherwise)
		wchar_t s[64];
		mir_snwprintf(s, L"%I64x", li.QuadPart);
		SetDlgItemText(m_hwnd, IDC_REFTIME, s);

		PopulateTimeCombo(m_hwnd, IDC_COMBOREMINDERTIME, m_pReminder == nullptr, &tm);

		// make sure date picker uses reference time
		FileTimeToTzLocalST((FILETIME*)&li, &tm);
		date.SetTime(&tm);
		InitDatePicker(m_hwnd, IDC_DATE);

		SendDlgItemMessage(m_hwnd, IDC_REMINDER, EM_LIMITTEXT, MAX_REMINDER_LEN, 0);

		if (m_pReminder) {
			mir_snwprintf(s, L"%02d:%02d", tm.wHour, tm.wMinute);

			// search for preset first
			int n = cmbTime.FindString(s);
			if (n != -1)
				cmbTime.SetCurSel(n);
			else
				cmbTime.SetText(s);

			SetDlgItemTextA(m_hwnd, IDC_REMINDER, m_pReminder->Reminder);
		}
		else cmbTime.SetCurSel(0);

		// populate sound repeat combo
		wchar_t *lpszEvery = TranslateT("Every");
		wchar_t *lpszSeconds = TranslateT("Seconds");

		// NOTE: use multiples of REMINDER_UPDATE_INTERVAL_SHORT (currently 5 seconds)
		cmbRepeat.AddString(TranslateT("Never"), 0);

		mir_snwprintf(s, L"%s 5 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 5);

		mir_snwprintf(s, L"%s 10 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 10);

		mir_snwprintf(s, L"%s 15 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 15);

		mir_snwprintf(s, L"%s 20 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 20);

		mir_snwprintf(s, L"%s 30 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 30);

		mir_snwprintf(s, L"%s 60 %s", lpszEvery, lpszSeconds);
		cmbRepeat.AddString(s, 60);

		if (m_pReminder && m_pReminder->RepeatSound) {
			mir_snwprintf(s, L"%s %d %s", lpszEvery, m_pReminder->RepeatSound, lpszSeconds);
			cmbRepeat.SetText(s);
			cmbRepeat.SetCurSel(cmbRepeat.FindString(s));
		}
		else cmbRepeat.SetCurSel(0);

		// populate sound selection combo
		cmbSound.AddString(TranslateT("Default"), 0);
		cmbSound.AddString(TranslateT("Alternative 1"), 1);
		cmbSound.AddString(TranslateT("Alternative 2"), 2);
		cmbSound.AddString(TranslateT("None"), -1);

		if (m_pReminder && m_pReminder->SoundSel) {
			const UINT n2 = m_pReminder->SoundSel < 0 ? 3 : m_pReminder->SoundSel;
			cmbSound.SetCurSel(n2);
		}
		else cmbSound.SetCurSel(0);

		HICON hIcon = IcoLib_GetIconByHandle(iconList[12].hIcolib);
		btnPlaySound.SendMsg(BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);

		if (m_pReminder && m_pReminder->SoundSel) {
			btnPlaySound.Enable(m_pReminder->SoundSel >= 0);
			cmbRepeat.Enable(m_pReminder->SoundSel >= 0);
		}

		if (m_pReminder)
			SetFocus(GetDlgItem(m_hwnd, IDC_ADDREMINDER));
		else
			SetFocus(GetDlgItem(m_hwnd, IDC_REMINDER));
		return true;
	}

	bool OnClose() override
	{
		bNewReminderVisible = false;
		if (m_pReminder)
			m_pReminder->bVisible = false;
		return true;
	}

	void onClick_Add(CCtrlButton*)
	{
		SYSTEMTIME Date;
		date.GetTime(&Date);
		if (!GetTriggerTime(m_hwnd, IDC_COMBOREMINDERTIME, IDC_REFTIME, &Date))
			return;

		int RepeatSound = cmbRepeat.GetCurSel();
		if (RepeatSound != CB_ERR)
			RepeatSound = cmbRepeat.GetItemData(RepeatSound);
		else
			RepeatSound = 0;

		int SzT = SendDlgItemMessage(m_hwnd, IDC_REMINDER, WM_GETTEXTLENGTH, 0, 0);
		char *ReminderText = nullptr;
		if (SzT) {
			if (SzT > MAX_REMINDER_LEN) SzT = MAX_REMINDER_LEN;
			ReminderText = (char*)malloc(SzT + 1);
			GetDlgItemTextA(m_hwnd, IDC_REMINDER, ReminderText, SzT + 1);
		}

		bool bClose = g_plugin.bCloseAfterAddReminder || m_pReminder;
		if (!m_pReminder) {
			// new reminder
			REMINDERDATA *TempRem = new REMINDERDATA();
			TempRem->uid = CreateUid();
			SystemTimeToFileTime(&Date, (FILETIME*)&TempRem->When);
			TempRem->Reminder = ReminderText;
			TempRem->bRepeat = chkRepeat.GetState();
			TempRem->SoundSel = cmbSound.GetItemData(cmbSound.GetCurSel());
			TempRem->RepeatSound = TempRem->SoundSel < 0 ? 0 : (UINT)RepeatSound;
			arReminders.insert(TempRem);
		}
		else {
			// update existing reminder
			SystemTimeToFileTime(&Date, (FILETIME*)&m_pReminder->When);

			if (m_pReminder->Reminder)
				free(m_pReminder->Reminder);
			m_pReminder->Reminder = ReminderText;

			m_pReminder->bRepeat = chkRepeat.GetState();
			m_pReminder->SoundSel = cmbSound.GetItemData(cmbSound.GetCurSel());
			m_pReminder->RepeatSound = m_pReminder->SoundSel < 0 ? 0 : (UINT)RepeatSound;

			// re-insert tree item sorted
			arReminders.remove(m_pReminder);
			arReminders.insert(m_pReminder);

			m_pReminder->bVisible = false;
			m_pReminder = nullptr; // prevent new reminder from being deleted
		}
		SetDlgItemTextA(m_hwnd, IDC_REMINDER, "");
		JustSaveReminders();
		NOTIFY_LIST();
		if (bClose)
			Close();
	}

	void onClick_View(CCtrlButton*)
	{
		PluginMenuCommandViewReminders(0, 0);
	}

	void onClick_PlaySound(CCtrlButton*)
	{
		int n = cmbSound.GetItemData(cmbSound.GetCurSel());
		switch (n) {
		case 0: 
			Skin_PlaySound("AlertReminder"); 
			break;
		case 1:
			Skin_PlaySound("AlertReminder2");
			break;
		case 2:
			Skin_PlaySound("AlertReminder3");
			break;
		}
	}

	void onChange_Date(CCtrlDate*)
	{
		OnDateChanged(m_hwnd, IDC_DATE, IDC_COMBOREMINDERTIME, IDC_REFTIME);
	}

	void onChange_Time(CCtrlCombo*)
	{
		if (cmbTime.GetCurSel() != -1)
			return;

		wchar_t buf[64];
		cmbTime.GetText(buf, _countof(buf));

		int h, m;
		if (ParseTime(buf, &h, &m, FALSE, IsRelativeCombo(m_hwnd, IDC_COMBOREMINDERTIME))) {
			SYSTEMTIME Date;
			date.GetTime(&Date);
			ReformatTimeInput(m_hwnd, IDC_COMBOREMINDERTIME, IDC_REFTIME, h, m, &Date);
		}
		else cmbTime.SetCurSel(0);
	}

	void onChange_Sound(CCtrlCombo*)
	{
		int n = cmbSound.GetItemData(cmbSound.GetCurSel());
		btnPlaySound.Enable(n >= 0);
		cmbRepeat.Enable(n >= 0);
	}
};

void EditReminder(REMINDERDATA *p)
{
	if (!p)
		return;

	if (!bNewReminderVisible && !p->bSystemEventQueued) {
		if (!p->bVisible) {
			p->bVisible = true;
			(new CReminderFormDlg(p))->Show();
		}
		else BringWindowToTop(p->handle);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////

static void InitListView(HWND AHLV)
{
	ListView_SetHoverTime(AHLV, 700);
	ListView_SetExtendedListViewStyle(AHLV, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_TRACKSELECT);
	ListView_DeleteAllItems(AHLV);

	int i = 0;
	for (auto &pReminder : arReminders) {
		LV_ITEM lvTIt;
		lvTIt.mask = LVIF_TEXT;

		wchar_t S1[128];
		GetTriggerTimeString(&pReminder->When, S1, _countof(S1), TRUE);

		lvTIt.iItem = i;
		lvTIt.iSubItem = 0;
		lvTIt.pszText = S1;
		ListView_InsertItem(AHLV, &lvTIt);
		lvTIt.mask = LVIF_TEXT;

		wchar_t *S2 = GetPreviewString(pReminder->Reminder);
		lvTIt.iItem = i;
		lvTIt.iSubItem = 1;
		lvTIt.pszText = S2;
		ListView_SetItem(AHLV, &lvTIt);

		i++;
	}

	ListView_SetItemState(AHLV, 0, LVIS_SELECTED, LVIS_SELECTED);
}

void OnListResize(HWND hwndDlg)
{
	HWND hList, hText, hBtnNew, hBtnClose;
	RECT lr, cr, tr, clsr;
	int th, btnh, btnw, MARGIN;
	POINT org = {0};

	hList = GetDlgItem(hwndDlg, IDC_LISTREMINDERS);
	hText = GetDlgItem(hwndDlg, IDC_REMINDERDATA);
	hBtnNew = GetDlgItem(hwndDlg, IDC_ADDNEWREMINDER);
	hBtnClose = GetDlgItem(hwndDlg, IDC_CLOSE);

	ClientToScreen(hwndDlg, &org);
	GetClientRect(hwndDlg, &cr);

	GetWindowRect(hList, &lr); OffsetRect(&lr, -org.x, -org.y);
	GetWindowRect(hText, &tr); OffsetRect(&tr, -org.x, -org.y);
	GetWindowRect(hBtnClose, &clsr); OffsetRect(&clsr, -org.x, -org.y);

	MARGIN = lr.left;

	th = tr.bottom - tr.top;
	btnh = clsr.bottom - clsr.top;
	btnw = clsr.right - clsr.left;

	clsr.left = cr.right - MARGIN - btnw;
	clsr.top = cr.bottom - MARGIN - btnh;

	tr.left = MARGIN;
	tr.right = cr.right - MARGIN;
	tr.bottom = clsr.top - MARGIN - 2;
	tr.top = tr.bottom - th;

	lr.right = cr.right - MARGIN;
	lr.bottom = tr.top - 5;

	MoveWindow(hList, lr.left, lr.top, lr.right - lr.left, lr.bottom - lr.top, FALSE);
	MoveWindow(hText, tr.left, tr.top, tr.right - tr.left, tr.bottom - tr.top, FALSE);

	MoveWindow(hBtnClose, clsr.left, clsr.top, btnw, btnh, FALSE);
	clsr.left -= btnw + 2;
	MoveWindow(hBtnNew, clsr.left, clsr.top, btnw, btnh, FALSE);

	RedrawWindow(hwndDlg, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
}

void UpdateGeomFromWnd(HWND hwndDlg, int *geom, int *colgeom, int nCols)
{
	if (geom) {
		WINDOWPLACEMENT wp;
		wp.length = sizeof(WINDOWPLACEMENT);
		GetWindowPlacement(hwndDlg, &wp);

		geom[0] = wp.rcNormalPosition.left;
		geom[1] = wp.rcNormalPosition.top;
		geom[2] = wp.rcNormalPosition.right - wp.rcNormalPosition.left;
		geom[3] = wp.rcNormalPosition.bottom - wp.rcNormalPosition.top;
	}

	if (colgeom) {
		HWND H = GetDlgItem(hwndDlg, IDC_LISTREMINDERS);

		for (int i = 0; i < nCols; i++)
			colgeom[i] = ListView_GetColumnWidth(H, i);
	}
}

static BOOL DoListContextMenu(HWND AhWnd, WPARAM wParam, LPARAM lParam, REMINDERDATA *pReminder)
{
	HWND hwndListView = (HWND)wParam;
	if (hwndListView != GetDlgItem(AhWnd, IDC_LISTREMINDERS))
		return FALSE;
	
	HMENU hMenuLoad = LoadMenuA(g_plugin.getInst(), "MNU_REMINDERPOPUP");
	HMENU FhMenu = GetSubMenu(hMenuLoad, 0);

	MENUITEMINFO mii = {};
	mii.cbSize = sizeof(mii);
	mii.fMask = MIIM_STATE;
	mii.fState = MFS_DEFAULT;
	if (!pReminder || pReminder->bSystemEventQueued)
		mii.fState |= MFS_GRAYED;
	SetMenuItemInfo(FhMenu, ID_CONTEXTMENUREMINDERLISTVIEW_EDIT, FALSE, &mii);

	if (!pReminder)
		EnableMenuItem(FhMenu, IDM_DELETEREMINDER, MF_GRAYED | MF_BYCOMMAND);

	TranslateMenu(FhMenu);
	TrackPopupMenu(FhMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, LOWORD(lParam), HIWORD(lParam), 0, AhWnd, nullptr);
	DestroyMenu(hMenuLoad);
	return TRUE;
}

static INT_PTR CALLBACK DlgProcViewReminders(HWND hwndDlg, UINT Message, WPARAM wParam, LPARAM lParam)
{
	HWND H = GetDlgItem(hwndDlg, IDC_LISTREMINDERS);

	switch (Message) {
	case WM_SIZE:
		OnListResize(hwndDlg);
		UpdateGeomFromWnd(hwndDlg, g_reminderListGeom, nullptr, 0);
		break;

	case WM_MOVE:
		UpdateGeomFromWnd(hwndDlg, g_reminderListGeom, nullptr, 0);
		break;

	case WM_GETMINMAXINFO:
		{
			MINMAXINFO *mm = (MINMAXINFO*)lParam;
			mm->ptMinTrackSize.x = 394;
			mm->ptMinTrackSize.y = 300;
		}
		return 0;

	case WM_RELOAD:
		SetDlgItemTextA(hwndDlg, IDC_REMINDERDATA, "");
		InitListView(GetDlgItem(hwndDlg, IDC_LISTREMINDERS));
		return TRUE;

	case WM_CONTEXTMENU:
		{
			REMINDERDATA *pReminder = nullptr;

			if (ListView_GetSelectedCount(H)) {
				int i = ListView_GetSelectionMark(H);
				if (i != -1)
					pReminder = arReminders[i];
			}

			if (DoListContextMenu(hwndDlg, wParam, lParam, pReminder))
				return TRUE;
		}
		break;

	case WM_INITDIALOG:
		Window_SetIcon_IcoLib(hwndDlg, iconList[6].hIcolib);

		TranslateDialogDefault(hwndDlg);
		SetDlgItemTextA(hwndDlg, IDC_REMINDERDATA, "");

		LV_COLUMN lvCol;
		lvCol.mask = LVCF_TEXT | LVCF_WIDTH;
		lvCol.pszText = TranslateT("Reminder text");
		lvCol.cx = g_reminderListColGeom[1];
		ListView_InsertColumn(H, 0, &lvCol);

		lvCol.mask = LVCF_TEXT | LVCF_WIDTH;
		lvCol.pszText = TranslateT("Date of activation");
		lvCol.cx = g_reminderListColGeom[0];
		ListView_InsertColumn(H, 0, &lvCol);

		InitListView(H);

		SetWindowLongPtr(GetDlgItem(H, 0), GWL_ID, IDC_LISTREMINDERS_HEADER);
		LV = hwndDlg;

		if (g_reminderListGeom[1] && g_reminderListGeom[2]) {
			WINDOWPLACEMENT wp;
			wp.length = sizeof(WINDOWPLACEMENT);
			GetWindowPlacement(hwndDlg, &wp);
			wp.rcNormalPosition.left = g_reminderListGeom[0];
			wp.rcNormalPosition.top = g_reminderListGeom[1];
			wp.rcNormalPosition.right = g_reminderListGeom[2] + g_reminderListGeom[0];
			wp.rcNormalPosition.bottom = g_reminderListGeom[3] + g_reminderListGeom[1];
			SetWindowPlacement(hwndDlg, &wp);
		}
		return TRUE;

	case WM_CLOSE:
		DestroyWindow(hwndDlg);
		bListReminderVisible = FALSE;
		return TRUE;

	case WM_NOTIFY:
		if (wParam == IDC_LISTREMINDERS) {
			LPNMLISTVIEW NM = (LPNMLISTVIEW)lParam;
			switch (NM->hdr.code) {
			case LVN_ITEMCHANGED:
				SetDlgItemTextA(hwndDlg, IDC_REMINDERDATA, arReminders[NM->iItem]->Reminder);
				break;

			case NM_DBLCLK:
				if (ListView_GetSelectedCount(H)) {
					int i = ListView_GetSelectionMark(H);
					if (i != -1)
						EditReminder(arReminders[i]);
				}
				break;
			}
		}
		else if (wParam == IDC_LISTREMINDERS_HEADER) {
			LPNMHEADER NM = (LPNMHEADER)lParam;
			switch (NM->hdr.code) {
			case HDN_ENDTRACK:
				UpdateGeomFromWnd(hwndDlg, nullptr, g_reminderListColGeom, _countof(g_reminderListColGeom));
				break;
			}
		}
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case ID_CONTEXTMENUREMINDERLISTVIEW_EDIT:
			if (ListView_GetSelectedCount(H)) {
				int i = ListView_GetSelectionMark(H);
				if (i != -1)
					EditReminder(arReminders[i]);
			}
			return TRUE;

		case IDC_CLOSE:
			DestroyWindow(hwndDlg);
			bListReminderVisible = false;
			return TRUE;

		case IDM_NEWREMINDER:
		case IDC_ADDNEWREMINDER:
			PluginMenuCommandNewReminder(0, 0);
			return TRUE;

		case IDM_DELETEALLREMINDERS:
			if (arReminders.getCount() && IDOK == MessageBox(hwndDlg, TranslateT("Are you sure you want to delete all reminders?"), _A2W(SECTIONNAME), MB_OKCANCEL)) {
				SetDlgItemTextA(hwndDlg, IDC_REMINDERDATA, "");
				DeleteReminders();
				InitListView(GetDlgItem(hwndDlg, IDC_LISTREMINDERS));
			}
			return TRUE;

		case IDM_DELETEREMINDER:
			if (ListView_GetSelectedCount(H)) {
				int i = ListView_GetSelectionMark(H);
				if (i != -1 && IDOK == MessageBox(hwndDlg, TranslateT("Are you sure you want to delete this reminder?"), _A2W(SECTIONNAME), MB_OKCANCEL)) {
					SetDlgItemTextA(hwndDlg, IDC_REMINDERDATA, "");
					DeleteReminder(arReminders[i]);
					JustSaveReminders();
					InitListView(H);
				}
			}
			return TRUE;
		}
		break;

	case WM_DESTROY:
		Window_FreeIcon_IcoLib(hwndDlg);
		break;
	}
	return FALSE;
}

/////////////////////////////////////////////////////////////////////////////////////////

void CloseReminderList()
{
	if (bListReminderVisible) {
		DestroyWindow(LV);
		bListReminderVisible = false;
	}
}

INT_PTR PluginMenuCommandNewReminder(WPARAM, LPARAM)
{
	if (!bNewReminderVisible) {
		bNewReminderVisible = true;
		(new CReminderFormDlg())->Show();
	}
	return 0;
}

INT_PTR PluginMenuCommandViewReminders(WPARAM, LPARAM)
{
	if (!bListReminderVisible) {
		CreateDialog(g_plugin.getInst(), MAKEINTRESOURCE(IDD_LISTREMINDERS), nullptr, DlgProcViewReminders);
		bListReminderVisible = true;
	}
	else BringWindowToTop(LV);
	return 0;
}

INT_PTR PluginMenuCommandDeleteReminders(WPARAM, LPARAM)
{
	if (arReminders.getCount())
		if (IDOK == MessageBox(nullptr, TranslateT("Are you sure you want to delete all reminders?"), TranslateT(SECTIONNAME), MB_OKCANCEL))
			DeleteReminders();
	return 0;
}