| 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
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084 |
1×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
25×
25×
88×
88×
88×
88×
88×
113×
88×
88×
88×
88×
88×
88×
88×
10×
10×
88×
88×
88×
9×
9×
79×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
113×
113×
113×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
113×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
113×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
5×
1×
1×
113×
6×
1×
1×
6×
1×
1×
6×
1×
1×
6×
1×
1×
6×
2×
2×
113×
4×
1×
1×
4×
1×
1×
4×
1×
1×
4×
1×
1×
4×
113×
19×
113×
113×
25×
25×
25×
25×
25×
25×
113×
113×
113×
309×
309×
309×
309×
309×
309×
113×
88×
88×
88×
88×
88×
88×
88×
78×
88×
88×
88×
88×
88×
88×
88×
78×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
88×
113×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
440×
1×
440×
440×
440×
440×
23×
23×
23×
23×
4×
23×
10×
10×
23×
23×
23×
7×
4×
4×
4×
4×
23×
23×
23×
2×
23×
7×
7×
7×
7×
4×
4×
4×
4×
440×
1×
440×
440×
440×
440×
9×
9×
9×
9×
1×
9×
8×
8×
9×
9×
9×
8×
1×
9×
9×
9×
2×
9×
8×
8×
1×
8×
8×
1×
440×
1×
440×
440×
440×
440×
440×
440×
2×
2×
1×
2×
2×
2×
2×
2×
2×
1×
1×
1×
1×
1×
1×
1×
1×
1×
440×
440×
1×
440×
440×
440×
440×
440×
113×
78×
78×
78×
78×
78×
78×
78×
78×
78×
78×
78×
78×
1×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
156×
78×
113×
661×
661×
661×
14975×
14975×
14975×
14975×
14975×
14975×
14975×
14975×
88×
14887×
14975×
14975×
10543×
10543×
10543×
10543×
10543×
14975×
661×
2×
2×
2×
2×
661×
661×
661×
661×
661×
661×
661×
113×
221×
221×
221×
221×
221×
221×
113×
221×
221×
221×
221×
221×
221×
221×
113×
2×
2×
113×
677×
629×
48×
48×
11×
11×
11×
11×
7×
7×
7×
7×
7×
7×
9×
7×
48×
48×
48×
48×
48×
4×
44×
113×
113×
131×
131×
131×
131×
2×
131×
131×
131×
131×
19×
131×
131×
4×
4×
4×
4×
4×
4×
127×
127×
2×
2×
125×
2×
2×
2×
123×
3×
120×
127×
18×
18×
127×
127×
113×
280×
280×
249×
249×
14×
235×
31×
113×
110×
110×
110×
110×
110×
110×
110×
110×
110×
110×
113×
336×
113×
126×
20×
106×
106×
106×
106×
106×
106×
106×
2×
1×
1×
1×
1×
1×
106×
106×
106×
106×
106×
113×
106×
106×
106×
106×
106×
106×
106×
106×
106×
106×
67×
67×
67×
39×
39×
39×
113×
758×
758×
113×
6×
113×
109×
109×
109×
109×
109×
109×
109×
109×
109×
113×
486×
113×
112×
112×
112×
112×
112×
112×
112×
112×
112×
112×
113×
463×
113×
109×
109×
109×
109×
109×
109×
109×
109×
109×
109×
113×
465×
113×
113×
113×
102×
102×
102×
102×
102×
102×
102×
102×
102×
102×
102×
113×
1×
113×
575×
575×
575×
575×
575×
575×
575×
575×
575×
113×
4×
4×
4×
4×
4×
113×
113×
2031×
2031×
2031×
2031×
1041×
1041×
990×
990×
1×
1019×
1×
3310×
1×
575×
575×
1×
3390×
3390×
3390×
3051×
3051×
3051×
339×
339×
339×
3051×
339×
1×
181×
181×
10×
171×
1×
128×
128×
88×
40×
1×
40×
1×
352×
352×
5488×
352×
1×
309×
309×
309×
309×
309×
9487×
9487×
9487×
309×
113×
575×
575×
575×
575×
575×
575×
575×
575×
575×
1244×
1241×
1161×
1161×
575×
575×
1244×
1244×
1244×
1244×
1244×
1244×
80×
1164×
490×
674×
674×
669×
575×
575×
113×
102×
102×
102×
102×
102×
113×
113×
1×
1×
113×
6×
113×
2×
113×
1×
113×
113×
1×
113×
1×
113×
5×
4×
1×
113×
5×
4×
4×
4×
4×
4×
1×
113×
2×
113×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
71×
1×
1278×
1278×
1278×
1278×
1×
426×
1×
142×
118×
12×
106×
24×
71×
113×
113×
113×
1×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
113×
|
/**
* The main class of the MtrDatepicker
* Here inside is covered everything that you need to know
*
* @class MtrDatepicker
* @param {Object} inputConfig used for user configurations
*/
function MtrDatepicker(inputConfig) {
/**
* The real implementation of the library starts here
*/
var self = this;
// The main configuration properties
// All of them can be overided by the init method
var config = {
targetElement: null,
defaultValues: {
hours: [],
minutes: [],
dates: [],
datesNames: [],
months: [],
years: [],
},
hours: {
min: 1,
max: 12,
step: 1,
maxlength: 2
},
minutes: {
min: 0,
max: 50,
step: 10,
maxlength: 2
},
months: {
min: 0,
max: 11,
step: 1,
maxlength: 2
},
years: {
min: 2000,
max: 2030,
step: 1,
maxlength: 4
},
animations: true, // Responsible for the transition of the sliders - animated or static
smartHours: false, // Make auto swicth between AM/PM when moving from 11AM to 12PM or backwards
future: false, // Validate the date to be only in the future
disableAmPm: false, // Disable the 12 hours time format and go to a full 24 hours experience
validateAfter: true, // perform the future validation after the date change
utcTimezone: 0, // change the local timezone to a specific one
transitionDelay: 100,
transitionValidationDelay: 500,
references: { // Used to store references to the main elements
hours: null
},
monthsNames: {
0: "Jan",
1: "Feb",
2: "Mar",
3: "Apr",
4: "May",
5: "Jun",
6: "Jul",
7: "Aug",
8: "Sep",
9: "Oct",
10: "Nov",
11: "Dec",
},
daysNames: {
0: "Sun",
1: "Mon",
2: "Tue",
3: "Wed",
4: "Thu",
5: "Fri",
6: "Sat",
},
timezones: null
};
// The main element which holds the datepicker
var targetElement;
var values = {
date: null,
timestamp: null,
ampm: true,
};
var browser = null;
// Here are the attached user events
var defaultChangeEventsCategories = {
'all': [],
'time': [],
'date': [],
'hour': [],
'minute': [],
'ampm': [],
'day': [],
'month': [],
'year': [],
};
var events = {
'onChange': clone(defaultChangeEventsCategories),
'beforeChange': clone(defaultChangeEventsCategories),
'afterChange': clone(defaultChangeEventsCategories)
};
var plugins = {
};
// Keep the wheel scroll in a timeout
var wheelTimeout = null;
// Keep the arrow click in a timeout
var arrowTimeout = {};
/**
* The main init function which prepares the datepicker for use
*
* @param {Object} inputConfig used to setup datepicker specific features
*/
var init = function(inputConfig) {
browser = detectBrowser();
if (!validateInputConfig(inputConfig)) {
console.error('Initialization of the datepicker is blocked because of erros in the config.');
return;
}
setConfig(inputConfig);
targetElement = byId(config.targetElement);
setDatesRange();
createMarkup();
attachEvents();
};
/**
* Attaching the user input config settings to ovverride the default one
*
* @param {Object} input user input settings
*/
var setConfig = function(input) {
config.targetElement = input.target;
config.animations = input.animations !== undefined ? input.animations : config.animations;
config.future = input.future !== undefined ? input.future : config.future;
config.validateAfter = input.validateAfter !== undefined ? input.validateAfter : config.validateAfter;
config.smartHours = input.smartHours !== undefined ? input.smartHours : config.smartHours;
config.disableAmPm = input.disableAmPm !== undefined ? input.disableAmPm : config.disableAmPm;
// Change the defauls if the AM/PM is disabled
if (config.disableAmPm) {
config.hours.min = 0;
config.hours.max = 23;
}
values.date = input.timestamp ? new Date(input.timestamp) : new Date();
values.date.setSeconds(0);
if (input.utcTimezone !== undefined) {
// We are sure that the timezones plugin is loaded because we've made a check in the input validation
plugins.timezones = new MtrDatepickerTimezones();
config.utcTimezone = plugins.timezones.getTimezone(input.utcTimezone);
}
else {
config.utcTimezone = {
offset: input.utcTimezone !== undefined ? input.utcTimezone : (values.date.getTimezoneOffset() / 60 * -1)
};
}
var localTimezoneOffsetTimestamp = values.date.getTime() + (values.date.getTimezoneOffset() * 60 * 1000);
var timezoneOffsetTimestamp = localTimezoneOffsetTimestamp + (config.utcTimezone.offset * 60 * 60 * 1000);
values.date = new Date(timezoneOffsetTimestamp);
values.timestamp = values.date.getTime();
// Override minutes
config.minutes.min = (input.minutes !== undefined && input.minutes.min !== undefined) ? parseInt(input.minutes.min) : config.minutes.min;
config.minutes.max = (input.minutes !== undefined && input.minutes.max !== undefined) ? parseInt(input.minutes.max) : config.minutes.max;
config.minutes.step = (input.minutes !== undefined && input.minutes.step !== undefined) ? parseInt(input.minutes.step) : config.minutes.step;
// Override months
config.months.min = (input.months !== undefined && input.months.min !== undefined) ? parseInt(input.months.min) : config.months.min;
config.months.max = (input.months !== undefined && input.months.max !== undefined) ? parseInt(input.months.max) : config.months.max;
config.months.step = (input.months !== undefined && input.months.step !== undefined) ? parseInt(input.months.step) : config.months.step;
// Override years
config.years.min = (input.years !== undefined && input.years.min !== undefined) ? parseInt(input.years.min) : config.years.min;
config.years.max = (input.years !== undefined && input.years.max !== undefined) ? parseInt(input.years.max) : config.years.max;
config.years.step = (input.years !== undefined && input.years.step !== undefined) ? parseInt(input.years.step) : config.years.step;
// Init hours
config.defaultValues.hours = createRange(config.hours);
config.defaultValues.minutes = createRange(config.minutes);
config.defaultValues.months = createRange(config.months);
config.defaultValues.years = createRange(config.years);
};
var validateInputConfig = function(input) {
var result = true;
// Validate minutes
if (input.minutes) {
// Validate data type
if (input.minutes.min !== undefined && !isNumber(input.minutes.min)) {
console.error('Invalid argument: minutes.min should be a number.');
result = false;
}
if (input.minutes.max !== undefined && !isNumber(input.minutes.max)) {
console.error('Invalid argument: minutes.max should be a number.');
result = false;
}
if (input.minutes.step !== undefined && !isNumber(input.minutes.step)) {
console.error('Invalid argument: minutes.step should be a number.');
result = false;
}
// Validate the range
if (input.minutes.min !== undefined && input.minutes.max !== undefined && input.minutes.max < input.minutes.min) {
console.error('Invalid argument: minutes.max should be larger than minutes.min.');
result = false;
}
if (input.minutes.min !== undefined &&
input.minutes.max !== undefined &&
input.minutes.step !== undefined &&
(input.minutes.step > (input.minutes.max - input.minutes.min))) {
console.error('Invalid argument: minutes.step should be less than minutes.max-minutes.min.');
result = false;
}
}
if (input.hours) {
// Validate data type
if (input.hours.min !== undefined && !isNumber(input.hours.min)) {
console.error('Invalid argument: hours.min should be a number.');
result = false;
}
if (input.hours.max !== undefined && !isNumber(input.hours.max)) {
console.error('Invalid argument: hours.max should be a number.');
result = false;
}
if (input.hours.step !== undefined && !isNumber(input.hours.step)) {
console.error('Invalid argument: hours.step should be a number.');
result = false;
}
// Validate the range
if (input.hours.min !== undefined && input.hours.max !== undefined && input.hours.max < input.hours.min) {
console.error('Invalid argument: hours.max should be larger than hours.min.');
result = false;
}
if (input.hours.min !== undefined &&
input.hours.max !== undefined &&
input.hours.step !== undefined &&
(input.hours.step > (input.hours.max - input.hours.min))) {
console.error('Invalid argument: hours.step should be less than hours.max-hours.min.');
result = false;
}
}
if (input.dates) {
// Validate data type
if (input.dates.min !== undefined && !isNumber(input.dates.min)) {
console.error('Invalid argument: dates.min should be a number.');
result = false;
}
if (input.dates.max !== undefined && !isNumber(input.dates.max)) {
console.error('Invalid argument: dates.max should be a number.');
result = false;
}
if (input.dates.step !== undefined && !isNumber(input.dates.step)) {
console.error('Invalid argument: dates.step should be a number.');
result = false;
}
// Validate the range
if (input.dates.min !== undefined && input.dates.max !== undefined && input.dates.max < input.dates.min) {
console.error('Invalid argument: dates.max should be larger than dates.min.');
result = false;
}
if (input.dates.min !== undefined &&
input.dates.max !== undefined &&
input.dates.step !== undefined &&
(input.dates.step > (input.dates.max - input.dates.min))) {
console.error('Invalid argument: dates.step should be less than dates.max-dates.min.');
result = false;
}
}
if (input.months) {
// Validate data type
if (input.months.min !== undefined && !isNumber(input.months.min)) {
console.error('Invalid argument: months.min should be a number.');
result = false;
}
if (input.months.max !== undefined && !isNumber(input.months.max)) {
console.error('Invalid argument: months.max should be a number.');
result = false;
}
if (input.months.step !== undefined && !isNumber(input.months.step)) {
console.error('Invalid argument: months.step should be a number.');
result = false;
}
// Validate the range
if (input.months.min !== undefined && input.months.max !== undefined && input.months.max < input.months.min) {
console.error('Invalid argument: months.max should be larger than months.min.');
result = false;
}
if (input.months.min !== undefined &&
input.months.max !== undefined &&
input.months.step !== undefined &&
(input.months.step > (input.months.max - input.months.min))) {
console.error('Invalid argument: months.step should be less than months.max-months.min.');
result = false;
}
}
if (input.years) {
// Validate data type
if (input.years.min !== undefined && !isNumber(input.years.min)) {
console.error('Invalid argument: years.min should be a number.');
result = false;
}
if (input.years.max !== undefined && !isNumber(input.years.max)) {
console.error('Invalid argument: years.max should be a number.');
result = false;
}
if (input.years.step !== undefined && !isNumber(input.years.step)) {
console.error('Invalid argument: years.step should be a number.');
result = false;
}
// Validate the range
if (input.years.min !== undefined && input.years.max !== undefined && input.years.max < input.years.min) {
console.error('Invalid argument: years.max should be larger than years.min.');
result = false;
}
Iif (input.years.min !== undefined &&
input.years.max !== undefined &&
input.years.step !== undefined && (input.years.step > (input.years.max - input.years.min))) {
console.error('Invalid argument: years.step should be less than years.max-years.min.');
result = false;
}
}
// Validate input timestamp
if (input.timestamp) {
// If the future dates is enabed, it will be a good idea to check the input timestamp, maybe it is in the past?
Iif (input.future) {
var timestampDate = new Date(input.timestamp);
var todayDate = new Date();
if (timestampDate.getTime() < todayDate.getTime()) {
console.error('Invalid argument: timestamp should be in the future if the future check is enabled.');
result = false;
}
}
}
Iif (input.utcTimezone !== undefined && typeof MtrDatepickerTimezones !== 'function') {
console.error('In order to use the timezones feature you should load the mtr-datepicker-timezones.min.js first.');
result = false;
}
// If there are any erros return a new target element with notice for the users
if (!result) {
targetElement = byId(input.target);
while (targetElement.firstChild) {
targetElement.removeChild(targetElement.firstChild);
}
var errorElement = document.createElement('div');
addClass(errorElement, 'mtr-error-message');
errorElement.appendChild(document.createTextNode('An error has occured during the initialization of the datepicker.'));
targetElement.appendChild(errorElement);
}
return result;
};
var attachEvents = function() {
};
var setDatesRange = function(month, year) {
month = month !== undefined ? month : getMonth();
year = year !== undefined ? year : getYear();
var datesRange = createRangeForDate(month, year);
config.dates = {
min: datesRange.min,
max: datesRange.max,
step: datesRange.step,
maxlength: 2,
};
config.defaultValues.dates = datesRange.values;
config.defaultValues.datesNames = datesRange.names;
};
/**
* Generate the main markup used from the datepicker
* This means that here we are generating input sliders for hours, minutes, months, dates and years
* and a radio input for swithing the time AM/PM
*/
var createMarkup = function() {
// Clear all of the content of the target element
removeClass(targetElement, 'mtr-datepicker');
addClass(targetElement, 'mtr-datepicker');
while (targetElement.firstChild) {
targetElement.removeChild(targetElement.firstChild);
}
// Create time elements
var hoursElement = createSliderInput({
name: 'hours',
values: config.defaultValues.hours,
value: getHours()
});
var minutesElement = createSliderInput({
name: 'minutes',
values: config.defaultValues.minutes,
value: getMinutes()
});
var amPmElement;
if (!config.disableAmPm) {
amPmElement = createRadioInput({
name: 'ampm',
});
}
var rowTime = document.createElement('div');
rowTime.className = 'mtr-row';
var rowClearfixTime = document.createElement('div');
rowClearfixTime.className = 'mtr-clearfix';
rowTime.appendChild(hoursElement);
rowTime.appendChild(minutesElement);
if (!config.disableAmPm) {
rowTime.appendChild(amPmElement);
}
targetElement.appendChild(rowTime);
targetElement.appendChild(rowClearfixTime);
// Create date elements
var monthElement = createSliderInput({
name: 'months',
values: config.defaultValues.months,
valuesNames: config.monthsNames,
value: getMonth()
});
var dateElement = createSliderInput({
name: 'dates',
values: config.defaultValues.dates,
valuesNames: config.defaultValues.datesNames,
value: getDate()
});
var yearElement = createSliderInput({
name: 'years',
values: config.defaultValues.years,
value: getYear()
});
var rowDate = document.createElement('div');
rowDate.className = 'mtr-row';
var rowClearfixDate = document.createElement('div');
rowClearfixDate.className = 'mtr-clearfix';
rowDate.appendChild(monthElement);
rowDate.appendChild(dateElement);
rowDate.appendChild(yearElement);
targetElement.appendChild(rowDate);
targetElement.appendChild(rowClearfixDate);
setTimestamp(values.timestamp);
};
/**
* This function is creating a slider input
*
* It is generating the required markup and attaching the needed event listeners
* The returned element is fully functional input field with arrows for navigating
* through the values
*
* @param {object} elementConfig
* @return {HtmlElement}
*/
var createSliderInput = function(elementConfig) {
var element = document.createElement('div');
element.className = 'mtr-input-slider';
config.references[elementConfig.name] = config.targetElement + '-input-' + elementConfig.name;
element.id = config.references[elementConfig.name];
// First, let's init the main elements
var divArrowUp = createUpArrow();
var divArrowDown = createDownArrow();
// Content of the input, holding the input and the available values
var divContent = document.createElement('div');
divContent.className = "mtr-content";
var inputValue = createInputValue();
var divValues = createValues(inputValue);
// The, let's append them to the element in the correct order
element.appendChild(divArrowUp);
// Append holder of the input and values to the main element
divContent.appendChild(inputValue);
divContent.appendChild(divValues);
element.appendChild(divContent);
element.appendChild(divArrowDown);
// Here are the definitios of the functions which are used to generate the markup
// and to attach the needed event listeners
function createUpArrow() {
var divArrowUp = document.createElement('div');
divArrowUp.className = 'mtr-arrow up';
divArrowUp.appendChild(document.createElement('span'));
// Attach event listener
divArrowUp.addEventListener('click', function() {
// Prevent blur event
var input = qSelect(inputValue, '.mtr-input');
addClass(inputValue, 'arrow-click');
addClass(divContent, 'mtr-active');
if (arrowTimeout[elementConfig.name]) {
window.clearTimeout(arrowTimeout[elementConfig.name]);
}
arrowTimeout[elementConfig.name] = setTimeout(function() {
removeClass(inputValue, 'arrow-click');
removeClass(divContent, 'mtr-active');
}, 1000);
// Change the value with the next one
var name = elementConfig.name;
var currentValue;
switch(name) {
case 'hours': currentValue = getHours(); break;
case 'minutes': currentValue = getMinutes(); break;
case 'dates': currentValue = getDate(); break;
case 'months': currentValue = getMonth(); break;
case 'years': currentValue = getYear(); break;
}
var indexInArray = config.defaultValues[name].indexOf(currentValue);
indexInArray++;
if (indexInArray >= config.defaultValues[name].length) {
indexInArray = 0;
}
switch(name) {
//case 'hours': setHours(config.defaultValues[name][indexInArray]); break;
case 'hours':
// Check is we have to make a transform of the hour
var newHour = config.defaultValues[name][indexInArray];
Iif (!config.disableAmPm && (getIsPm() && newHour !== 12)) {
newHour += 12;
}
setHours(newHour);
break;
case 'minutes': setMinutes(config.defaultValues[name][indexInArray]); break;
case 'dates': setDate(config.defaultValues[name][indexInArray]); break;
case 'months': setMonth(config.defaultValues[name][indexInArray]); break;
case 'years': setYear(config.defaultValues[name][indexInArray]); break;
}
}, false);
return divArrowUp;
}
function createDownArrow() {
var divArrowDown = document.createElement('div');
divArrowDown.className = 'mtr-arrow down';
divArrowDown.appendChild(document.createElement('span'));
divArrowDown.addEventListener('click', function(e) {
// Prevent blur event
var input = qSelect(inputValue, '.mtr-input');
addClass(inputValue, 'arrow-click');
addClass(divContent, 'mtr-active');
if (arrowTimeout[elementConfig.name]) {
window.clearTimeout(arrowTimeout[elementConfig.name]);
}
arrowTimeout[elementConfig.name] = setTimeout(function() {
removeClass(inputValue, 'arrow-click');
removeClass(divContent, 'mtr-active');
}, 1000);
// Change the value with the prev one
var name = elementConfig.name;
var currentValue;
switch(name) {
case 'hours': currentValue = getHours(); break;
case 'minutes': currentValue = getMinutes(); break;
case 'dates': currentValue = getDate(); break;
case 'months': currentValue = getMonth(); break;
case 'years': currentValue = getYear(); break;
}
var indexInArray = config.defaultValues[name].indexOf(currentValue);
indexInArray--;
if (indexInArray < 0) {
indexInArray = config.defaultValues[name].length - 1;
}
switch(name) {
//case 'hours': setHours(config.defaultValues[name][indexInArray]); break;
case 'hours':
// Check is we have to make a transform of the hour
var newHour = config.defaultValues[name][indexInArray];
if (!config.disableAmPm && (getIsPm() && newHour !== 12)) {
newHour += 12;
}
setHours(newHour);
break;
case 'minutes': setMinutes(config.defaultValues[name][indexInArray]); break;
case 'dates': setDate(config.defaultValues[name][indexInArray]); break;
case 'months': setMonth(config.defaultValues[name][indexInArray]); break;
case 'years': setYear(config.defaultValues[name][indexInArray]); break;
}
}, false);
return divArrowDown;
}
function createInputValue() {
var inputValue = document.createElement('input');
inputValue.value = elementConfig.value;
inputValue.type = 'text';
inputValue.className = 'mtr-input ' + elementConfig.name;
inputValue.style.display = 'none';
// Attach event listeners
inputValue.addEventListener('blur', function(e) {
// Blur event has to be calles after specific ammount of time
// because it can be cause from an arrow button. In this case
// we shouldn't apple the blur event body
setTimeout(function() {
blurEvent();
}, 500);
function blurEvent() {
Iif (!targetElement) {
return;
}
var newValue = inputValue.value;
var oldValue = inputValue.getAttribute('data-old-value');
// If the blur is called after click on arrow we shoulnt update the value
Iif (e.target.className.indexOf('arrow-click') > -1) {
removeClass(e.target, 'arrow-click');
return;
}
// If this is the month input we should decrement it because
// the months are starting from 0
Iif (inputValue.className.indexOf('months') > -1) {
newValue--;
}
// Validate the value
if (validateValue(elementConfig.name, newValue) === false) {
inputValue.value = oldValue;
inputValue.focus();
return;
}
// If the future detection is ON validate the value again
var target = elementConfig.name.substring(0, elementConfig.name.length-1);
Iif (elementConfig.name === 'dates') {
target = 'day';
}
Iif (config.future && !validateChange(target, newValue, oldValue)) {
if (elementConfig.name === 'months') {
oldValue++;
}
inputValue.value = oldValue;
inputValue.focus();
return;
}
inputValue.style.display = 'none';
switch(elementConfig.name) {
case 'hours': setHours(newValue); break;
case 'minutes': setMinutes(newValue); break;
case 'dates': setDate(newValue); break;
case 'months': setMonth(newValue); break;
case 'years': setYear(newValue); break;
}
}
}, false);
// On wheel scroll we should change the value in the input
inputValue.addEventListener('wheel ', function(e) {
e.preventDefault();
e.stopPropagation();
// If the user is using the mouse wheel the values should be changed
var target = e.target;
var wheelData = e.wheelDeltaY ? e.wheelDeltaY : (e.deltaY * -1);
var oldValue = parseInt(inputValue.value),
newValue;
var configMin = config[elementConfig.name].min,
configMax = config[elementConfig.name].max,
configStep = config[elementConfig.name].step;
if (elementConfig.name === 'months') {
// If we are scrolling the months we should increment the value
configMin++;
configMax++;
}
if (direction > 0) { // Scroll up
if (oldValue < configMax) {
newValue = oldValue + configStep;
}
else {
newValue = configMin;
}
}
else { // Scroll down
if (oldValue > configMin) {
newValue = oldValue - configStep;
}
else {
newValue = configMax;
}
}
inputValue.value = newValue;
return false;
}, false);
return inputValue;
}
function createValues(inputValue) {
var divValues = createElementValues(elementConfig);
// On swipe, we should cgange the value in the input
divValues.addEventListener('touchstart', function(e) {
handleTouchStart(e);
}, false);
divValues.addEventListener('touchmove', function(e) {
handleTouchMove(e, function(direction) {
var parent = divValues.parentElement.parentElement,
arrow;
if (direction > 0) { // Scroll up
arrow = qSelect(parent, '.mtr-arrow.up');
}
else { // Scroll down
arrow = qSelect(parent, '.mtr-arrow.down');
}
arrow.click();
});
}, false);
return divValues;
}
return element;
};
/**
* Create HtmlElement with a radio button control
*
* @param {object} elementConfig
* @return {HtmlElement}
*/
var createRadioInput = function(elementConfig) {
var element = document.createElement('div');
element.className = 'mtr-input-radio';
config.references[elementConfig.name] = config.targetElement + '-input-' + elementConfig.name;
element.id = config.references[elementConfig.name];
var formHolder = document.createElement('form');
formHolder.name = config.references[elementConfig.name];
// First create the elements
var radioAm = createInputValue('ampm', 1, 'AM');
var radioPm = createInputValue('ampm', 0, 'PM');
formHolder.appendChild(radioAm);
formHolder.appendChild(radioPm);
formHolder.ampm.value = getIsAm() ? '1' : '0';
element.appendChild(formHolder);
function createInputValue(radioName, radioValue, labelValue) {
var divHolder = document.createElement('div');
var label = document.createElement('label');
var input = document.createElement('input');
var elementId = config.targetElement + '-radio-' + radioName + '-' + labelValue;
var innerHtmlSpanValue = document.createElement('span');
innerHtmlSpanValue.className = 'value';
innerHtmlSpanValue.appendChild(document.createTextNode(labelValue));
var innerHtmlSpanRadio = document.createElement('span');
innerHtmlSpanRadio.className = 'radio';
label.setAttribute('for', elementId);
label.appendChild(innerHtmlSpanValue);
label.appendChild(innerHtmlSpanRadio);
input.className = 'mtr-input ';
input.type = 'radio';
input.name = radioName;
input.id = elementId;
input.value = radioValue;
divHolder.appendChild(input);
divHolder.appendChild(label);
// Attach event listeners
input.addEventListener('change', function(e) {
var result = setAmPm(radioValue);
if (!result && config.future) {
setAmPm(!radioValue);
e.preventDefault();
e.stopPropagation();
return false;
}
}, false);
return divHolder;
}
return element;
};
/**
* This function is creating a new set of HtmlElement which
* contains the default values for a specific input
*
* @param {obect} elementConfig
* @return {HtmlElement}
*/
var createElementValues = function(elementConfig) {
var divValues = document.createElement('div');
divValues.className = 'mtr-values';
elementConfig.values.forEach(function(value) {
var innerHTML = elementConfig.name === 'months' ? value+1 : value;
var divValueHolder = document.createElement('div');
divValueHolder.className = 'mtr-default-value-holder';
divValueHolder.setAttribute('data-value', value);
var divValue = document.createElement('div');
divValue.className = 'mtr-default-value';
divValue.setAttribute('data-value', value);
if (elementConfig.name === 'minutes' && value === 0) {
divValue.appendChild(document.createTextNode('00'));
}
else {
divValue.appendChild(document.createTextNode(innerHTML));
}
divValueHolder.appendChild(divValue);
if (elementConfig.valuesNames) {
var divValueName = document.createElement('div');
divValueName.className = 'mtr-default-value-name';
divValueName.appendChild(document.createTextNode(elementConfig.valuesNames[value]));
divValue.className += ' has-name';
divValueHolder.appendChild(divValueName);
}
divValues.appendChild(divValueHolder);
});
// Attach listeners
var inputClickEventListener = function() {
// Show the input field for manual setup
var parent = divValues.parentElement,
inputValue = qSelect(parent, '.mtr-input');
// If we are working with months we have to incement the value
// because the months are starting from 0
Iif (inputValue.className.indexOf('months') > -1) {
inputValue.value = parseInt(inputValue.value) + 1;
}
inputValue.style.display = "block";
inputValue.focus();
};
divValues.addEventListener('click', inputClickEventListener, false);
divValues.addEventListener('touchstart', inputClickEventListener, false);
divValues.addEventListener('touchend', inputClickEventListener, false);
divValues.addEventListener('wheel', function(e) {
e.preventDefault();
e.stopPropagation();
if (wheelTimeout) {
return false;
}
// If the user is using the mouse wheel the values should be changed
var target = e.target;
var parent = target.parentElement.parentElement.parentElement.parentElement; // value -> values -> content -> input slider
var values = qSelect(parent, '.mtr-values');
var input = qSelect(parent, '.mtr-input');
var wheelData = e.wheelDeltaY ? e.wheelDeltaY : (e.deltaY * -1); // Firefox doesn't support wheelDataY, so we are using deltaY and cghanging the sign of the value
var arrow;
if (wheelData > 0) { // Scroll up
arrow = qSelect(parent, '.mtr-arrow.up');
}
else { // Scroll down
arrow = qSelect(parent, '.mtr-arrow.down');
}
wheelTimeout = setTimeout(function() {
clearWheelTimeout();
}, 100);
arrow.click();
return false;
}, false);
divValues.addEventListener('touchstart', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
}, false);
divValues.addEventListener('touchmove', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
}, false);
return divValues;
};
var rebuildElementValues = function(reference, data) {
var element = byId(reference);
var elementContent = qSelect(element, '.mtr-content');
var elementContentValues = qSelect(elementContent, '.mtr-values');
elementContentValues.parentNode.removeChild(elementContentValues);
var elementContentNewValues = createElementValues({
name: data.name,
values: data.values,
valuesNames: data.valuesNames
});
elementContent.appendChild(elementContentNewValues);
};
/**
* Updating the date when a month or year is changed
* It should realculate the dates in the specific month and check
* the postition of the date (if it's bigger than the last date of the month)
*
* @param {Number} newMonth
* @param {NUmber} newYar
*/
var updateDate = function(newMonth, newYear) {
newMonth = newMonth !== undefined ? newMonth : getMonth();
newYear = newYear !== undefined ? newYear : getYear();
// After month change we should recalculate the range of the dates
setDatesRange(newMonth, newYear);
rebuildElementValues(config.references.dates, {
name: 'dates',
values: config.defaultValues.dates,
valuesNames: config.defaultValues.datesNames
});
// After the change in the dates of the month we should check is the current date exist
// because if the current date is 31 and the month has only 30 days it is not correct
var maxDay = config.defaultValues.dates[config.defaultValues.dates.length-1];
var currentDate = getDate();
Iif (currentDate > maxDay) {
setDate(maxDay);
}
};
var validateValue = function(type, value) {
value = parseInt(value);
// Strict, the value is exact in the array
return config.defaultValues[type].indexOf(value) > -1 ? true : false;
};
/**
* This function is validating the change of the date
*
* If the config.feature is enabled this function will prevent selecting dates
* in the past
*
* @param {String} target
* @param {Number} newValue
* @param {Number} oldValue
* @return {boolean}
*/
var validateChange = function(target, newValue, oldValue) {
if (config.future === false) {
return true;
}
var dateNow = new Date(),
datePicker = new Date(values.date.getTime());
switch(target) {
case 'hour':
var isAm = getIsAm();
Iif (isAm && newValue === 12) {
newValue = 0;
}
// else if (!isAm && newValue < 12) {
// newValue += 12;
// }
datePicker.setHours(newValue);
break;
case 'minute': datePicker.setMinutes(newValue); break;
case 'ampm':
var currentHours = datePicker.getHours(),
currentAmPm = (currentHours >= 0 && currentHours <= 11) ? true : false,
newHours = currentHours;
Iif (newValue != oldValue) {
if (newValue == true && currentHours > 12) { // set AM
newHours = currentHours - 12;
}
else if (newValue == true && currentHours == 12) {
newHours = 0;
}
else if (newValue == false && currentHours < 12) { // Set PM
newHours = currentHours + 12;
}
else if (newValue == false && currentHours == 12) { // Set PM
newHours = 12;
}
}
datePicker.setHours(newHours);
break;
case 'day': datePicker.setDate(newValue); break;
case 'month': datePicker.setMonth(newValue); break;
case 'year': datePicker.setFullYear(newValue); break;
}
dateNow.setSeconds(0);
dateNow.setMilliseconds(0);
datePicker.setSeconds(0);
datePicker.setMilliseconds(0);
if (datePicker.getTime() < dateNow.getTime()) {
return false;
}
return true;
};
var clearWheelTimeout = function() {
wheelTimeout = null;
};
/*****************************************************************************
* A lot of getters and setters now
****************************************************************************/
var setHours = function(input, preventAnimation) {
var oldValue = values.date.getHours();
var isChangeValid = validateChange('hour', input, oldValue);
var isAm = getIsAm();
// If the smart hourrs are enabled and we want to gto from 11 Am to 12 PM, we should
// disable the validation
if (!config.disableAmPm && (config.smartHours && input === 12 && isAm)) {
isChangeValid = true;
}
Iif (!config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.hours);
return;
}
executeChangeEvents('hour', 'beforeChange', input, oldValue);
var newHour = input;
if (!config.disableAmPm && input > 12) {
input -= 12; // reduce the values with 12 hours
}
updateInputSlider(config.references.hours, input, preventAnimation);
if (config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.hours);
setTimeout(function() {
Iif (!config.disableAmPm && oldValue > 12) {
oldValue -= 12;
}
updateInputSlider(config.references.hours, oldValue, preventAnimation);
executeChangeEvents('hour', 'onChange', input, oldValue);
executeChangeEvents('hour', 'afterChange', input, oldValue);
}, config.transitionValidationDelay);
}
else {
values.timestamp = values.date.setHours(newHour);
if (!config.disableAmPm && (config.smartHours && newHour === 12 && isAm)) {
values.timestamp = values.date.setHours(12);
setAmPm(false); // set to PM
}
else if (!config.disableAmPm && (config.smartHours && (newHour === 23 || newHour === 11) && oldValue === 12 && !isAm)) {
newHour = 11;
values.timestamp = values.date.setHours(newHour);
setAmPm(true); // set to AM
}
else if (!config.disableAmPm && (!config.smartHours && newHour === 12 && isAm)) {
values.timestamp = values.date.setHours(0);
}
else {
values.timestamp = values.date.setHours(newHour);
}
if (!config.disableAmPm && newHour > 12) {
newHour -= 12; // reduce the values with 12 hours
setAmPm(false); // set to PM
}
executeChangeEvents('hour', 'onChange', input, oldValue);
executeChangeEvents('hour', 'afterChange', input, oldValue);
}
};
var getHours = function() {
var currentHours = values.date.getHours();
if (!config.disableAmPm) {
var isAm = getIsAm();
if (currentHours === 12 || currentHours === 0) {
return 12;
}
return (currentHours < 12 && isAm) ? currentHours : currentHours - 12;
}
else {
return currentHours;
}
};
var setMinutes = function(input, preventAnimation) {
var oldValue = values.date.getMinutes();
var isChangeValid = validateChange('minute', input, oldValue);
Iif (!config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.minutes);
return;
}
executeChangeEvents('minute', 'beforeChange', input, oldValue);
// TODO: validate
var defaultValues = config.defaultValues.minutes;
updateInputSlider(config.references.minutes, input, preventAnimation);
Iif (config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.minutes);
setTimeout(function() {
updateInputSlider(config.references.minutes, oldValue, preventAnimation);
executeChangeEvents('minute', 'onChange', input, oldValue);
executeChangeEvents('minute', 'afterChange', input, oldValue);
}, config.transitionValidationDelay);
}
else {
values.timestamp = values.date.setMinutes(input);
executeChangeEvents('minute', 'onChange', input, oldValue);
executeChangeEvents('minute', 'afterChange', input, oldValue);
}
};
var getMinutes = function() {
return values.date.getMinutes();
};
var setAmPm = function(setAmPm) {
if (config.disableAmPm) {
return;
}
var oldValue = getIsAm();
Iif (!validateChange('ampm', setAmPm, oldValue)) {
showInputRadioError(config.references.ampm, setAmPm);
if (browser.isSafari) {
setTimeout(function() {
setRadioFormValue(config.references.ampm, oldValue);
}, 10);
}
return false;
}
executeChangeEvents('ampm', 'beforeChange', setAmPm, oldValue);
// TODO: validate
var currentHours = values.date.getHours();
var currentHoursCalculates = getHours();
var currentIsAm = getIsAm();
if (currentIsAm !== setAmPm) {
if (setAmPm == true && currentHours >= 12 ) { // Set AM
currentHours -= 12;
values.timestamp = values.date.setHours(currentHours);
}
else Eif (setAmPm == false && currentHours < 12) { // Set PM
currentHours += 12;
values.timestamp = values.date.setHours(currentHours);
}
}
values.ampm = setAmPm;
setRadioFormValue(config.references.ampm, setAmPm);
executeChangeEvents('ampm', 'onChange', setAmPm, oldValue);
executeChangeEvents('ampm', 'afterChange', setAmPm, oldValue);
return true;
};
var setRadioFormValue = function(reference, setAmPm) {
// If the AM/PM is disabled we don't have t do anything here
Iif (config.disableAmPm) {
return;
}
var divRadioInput = byId(reference);
var formRadio = qSelect(divRadioInput, 'form');
formRadio.ampm.value = setAmPm ? '1' : '0';
var labelAmPm = setAmPm ? 'AM' : 'PM';
var radioAm = qSelect(formRadio, 'input.mtr-input[type="radio"][value="1"]');
var radioPm = qSelect(formRadio, 'input.mtr-input[type="radio"][value="0"]');
var label = qSelect(formRadio, 'label[for="'+config.targetElement+'-radio-ampm-'+labelAmPm+'"]');
var checkbox = qSelect(label, 'checkbox');
if (setAmPm) {
radioAm.setAttribute('checked', '');
radioAm.checked = true;
radioPm.removeAttribute('checked');
}
else {
radioPm.setAttribute('checked', '');
radioPm.checked = true;
radioAm.removeAttribute('checked');
}
};
var getIsAm = function() {
var currentHours = values.date.getHours();
return (currentHours >= 0 && currentHours <= 11) ? true : false;
//return values.date.toLocaleTimeString().indexOf('AM') > -1 ? 1 : 0;
//return values.ampm;
};
var getIsPm = function() {
return !getIsAm();
};
var setDate = function(newDate, preventAnimation) {
var oldValue = values.date.getDate();
var isChangeValid = validateChange('day', newDate, oldValue);
Iif (!config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.dates);
return;
}
executeChangeEvents('day', 'beforeChange', newDate, oldValue);
// TODO: Validate input
updateInputSlider(config.references.dates, newDate, preventAnimation);
Iif (config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.dates);
setTimeout(function() {
updateInputSlider(config.references.dates, oldValue, preventAnimation);
executeChangeEvents('day', 'onChange', newDate, oldValue);
executeChangeEvents('day', 'afterChange', newDate, oldValue);
}, config.transitionValidationDelay);
}
else {
values.timestamp = values.date.setDate(newDate);
executeChangeEvents('day', 'onChange', newDate, oldValue);
executeChangeEvents('day', 'afterChange', newDate, oldValue);
}
};
var getDate = function() {
return values.date.getDate();
};
var setMonth = function(newMonth, preventAnimation) {
var oldValue = values.date.getMonth();
var isChangeValid = validateChange('month', newMonth, oldValue);
Iif (!config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.months);
return;
}
executeChangeEvents('month', 'beforeChange', newMonth, oldValue);
// TODO: Validate input
// Finally, update the month
updateInputSlider(config.references.months, newMonth, preventAnimation);
Iif (config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.months);
setTimeout(function() {
updateInputSlider(config.references.months, oldValue, preventAnimation);
executeChangeEvents('month', 'onChange', newMonth, oldValue);
executeChangeEvents('month', 'afterChange', newMonth, oldValue);
}, config.transitionValidationDelay);
}
else {
values.timestamp = values.date.setMonth(newMonth);
updateDate(newMonth);
executeChangeEvents('month', 'onChange', newMonth, oldValue);
executeChangeEvents('month', 'afterChange', newMonth, oldValue);
}
};
var getMonth = function() {
return values.date.getMonth();
};
var setYear = function(newYear, preventAnimation) {
var oldValue = values.date.getFullYear();
var isChangeValid = validateChange('year', newYear, oldValue);
Iif (!config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.years);
return;
}
executeChangeEvents('year', 'beforeChange', newYear, oldValue);
// TODO: Validate input
updateDate(undefined, newYear);
updateInputSlider(config.references.years, newYear, preventAnimation);
Iif (config.validateAfter && !isChangeValid) {
showInputSliderError(config.references.years);
setTimeout(function() {
updateInputSlider(config.references.years, oldValue, preventAnimation);
executeChangeEvents('year', 'onChange', newYear, oldValue);
executeChangeEvents('year', 'afterChange', newYear, oldValue);
}, config.transitionValidationDelay);
}
else {
values.timestamp = values.date.setFullYear(newYear);
executeChangeEvents('year', 'onChange', newYear, oldValue);
executeChangeEvents('year', 'afterChange', newYear, oldValue);
}
};
var getYear = function() {
return values.date.getFullYear();
};
// Bigger getter and setters
var getTime = function() {
return getHours() + ':' + getMinutes();
};
var getFullTime = function() {
return getHours() + ':' + getMinutes() + ' ' + (getIsAm() ? 'AM' : 'PM');
};
var setTimestamp = function(input) {
var roundedTimestamp = roundUpTimestamp(input);
values.date = new Date(roundedTimestamp);
values.timestamp = roundedTimestamp;
var currentHours = values.date.getHours(),
currentMinutes = getMinutes(),
currentAmPm = (currentHours >= 0 && currentHours < 12) ? true : false,
currentDate = getDate(),
currentMonth = getMonth(),
currentYear = getYear();
currentHours = (currentHours === 0) ? 12 : currentHours;
setHours(currentHours);
setMinutes(currentMinutes);
setMonth(currentMonth);
setYear(currentYear);
setDate(currentDate);
setAmPm(currentAmPm);
};
var getTimestamp = function() {
return values.date.getTime();
};
/*****************************************************************************
* A lot of actions here (used when event is triggered)
****************************************************************************/
/**
* Update the value of the input slider
* @param {string} reference id to the specific element
* @param {integer} newValue
*/
var updateInputSlider = function(reference, newValue, preventAnimation) {
var element = byId(reference);
preventAnimation = preventAnimation || false;
Iif (!element) {
return;
}
// Find the specific value
var divValues = qSelect(element, '.mtr-content'),
divValue = qSelect(element, '.mtr-values .mtr-default-value[data-value="'+newValue+'"]'),
divArrow = qSelect(element, '.mtr-arrow.up'),
inputValue = qSelect(element, '.mtr-input');
scrollTo = getRelativeOffset(divValues, divValue) + divArrow.clientHeight;
inputValue.value = newValue;
inputValue.setAttribute('data-old-value', newValue);
Iif (config.animations === false || preventAnimation) {
divValue.scrollIntoView();
}
else {
smooth_scroll_to(divValues, scrollTo, config.transitionDelay);
}
};
/**
* Add a error clas to the current input slider when a validation has failed
* @param {String} reference id to the specific element
*/
var showInputSliderError = function(reference) {
var element = byId(reference);
var divContent = qSelect(element, '.mtr-content');
addClass(divContent, 'mtr-error');
setTimeout(function() {
removeClass(divContent, 'mtr-error');
}, config.transitionValidationDelay + 300);
};
var showInputRadioError = function(reference, value) {
if (typeof value === 'boolean') {
value = value === true ? 1 : 0;
}
var element = byId(reference);
var divContent = qSelect(element, '.mtr-input[value="'+value+'"]');
addClass(divContent, 'mtr-error');
setTimeout(function() {
removeClass(divContent, 'mtr-error');
}, config.transitionValidationDelay + 300);
};
var executeChangeEvents = function(target, changeEvent, newValue, oldValue) {
var callbackFunction = function(callback) {
callback(target, newValue, oldValue);
};
events[changeEvent][target].forEach(function(callback) {
callbackFunction(callback);
});
events[changeEvent].all.forEach(function(callback) {
callbackFunction(callback);
});
switch (target) {
case 'hour':
case 'minute':
case 'ampm':
events[changeEvent].time.forEach(function(callback) {
callbackFunction(callback);
});
break;
case 'day':
case 'month':
case 'year':
events[changeEvent].date.forEach(function(callback) {
callbackFunction(callback);
});
break;
}
};
/*****************************************************************************
* Some Aliases
****************************************************************************/
function byId(selector) {
return document.getElementById(selector);
}
function qSelect(element, selector) {
return element ? element.querySelector(selector) : null;
}
function getRelativeOffset(parent, child) {
Eif (parent && child) {
return child.offsetTop - parent.offsetTop;
}
return 0;
}
/**
* A simple function which makes a clone of a specific JS Object
* @param {Object} obj
* @return {Object}
*/
function clone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
Iif (null == obj || "object" != typeof obj) return obj;
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
Eif (obj instanceof Object) {
copy = {};
for (var attr in obj) {
Eif (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
/**
* A simple shortcut function to add a class to specific element
* @param {HTMLElement} element
* @param {string} className
*/
function addClass(element, className) {
Iif (!element) {
return;
}
if (element.className.indexOf(className) > -1) {
return;
}
element.className += ' ' + className;
}
/**
* Short allias for a function which is removing a class name from a specific element
* @param {HtmlElement} element
* @param {string} className
*/
function removeClass(element, className) {
Iif (!element) {
return;
}
if (element.className.indexOf(className) === -1) {
return;
}
element.className = element.className.replace(new RegExp(className, 'g'), '');
}
/**
* Check is a specific input a number
* @param {Number|String} n
* @return {Boolean}
*/
function isNumber(input){
return Number(input) === input && input % 1 === 0;
}
/**
* Create array of values for a specific range with a givvent step
* @param {object} settings
* @return {array}
*/
function createRange(settings) {
var from = settings.min,
to = settings.max,
step = settings.step,
range = [];
for (var i=from; i<=to; i+=step) {
range.push(i);
}
return range;
}
/**
* Create a special range with dates for a specific month
*/
function createRangeForDate(month, year) {
var firstDay = new Date(year, month, 1);
var lastDay = new Date(year, month + 1, 0);
var range = {
values: [],
names: [],
min: firstDay.getDate(),
max: lastDay.getDate(),
step: 1
};
var currentDate;
for (var i=firstDay.getDate(); i<=lastDay.getDate(); i++) {
currentDate = new Date(year, month, i);
range.values.push(i);
range.names[i] = config.daysNames[currentDate.getDay()];
}
return range;
}
/**
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
*/
var smooth_scroll_to = function(element, target, duration) {
target = Math.round(target);
duration = Math.round(duration);
Iif (duration < 0) {
return;
}
Iif (duration === 0) {
element.scrollTop = target;
return;
}
var startTime = Date.now();
var end_time = startTime + duration;
var start_top = element.scrollTop;
var distance = target - start_top;
// https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery
// based on http://en.wikipedia.org/wiki/Smoothstep
var smooth_step = function(start, end, point) {
if(point <= start) { return 0; }
if(point >= end) { return 1; }
var x = (point - start) / (end - start); // interpolation
return x*x*(3 - 2*x);
};
// This is to keep track of where the element's scrollTop is
// supposed to be, based on what we're doing
var previous_top = element.scrollTop;
// This is like a think function from a game loop
var scroll_frame = function() {
Iif(element.scrollTop != previous_top) {
//reject("interrupted");
return;
}
// set the scrollTop for this frame
var now = Date.now();
var point = smooth_step(startTime, end_time, now);
var frameTop = Math.round(start_top + (distance * point));
element.scrollTop = frameTop;
// check if we're done!
if(now >= end_time) {
return;
}
// If we were supposed to scroll but didn't, then we
// probably hit the limit, so consider it done; not
// interrupted.
if(element.scrollTop === previous_top && element.scrollTop !== frameTop) {
return;
}
previous_top = element.scrollTop;
// schedule next frame for execution
setTimeout(function() {
scroll_frame();
}, 0);
};
// boostrap the animation process
setTimeout(function() {
scroll_frame();
}, 0);
};
/**
* Round up a timestamp to the closest monutes (11:35 to 11:40)
* @param {Number} timestamp
* @return {Number}
*/
var roundUpTimestamp = function(timestamp) {
var border = config.minutes.step * 60 * 1000;
var delta = 0;
// We should round up the timestamp only of the minutes step is not set to 1
Eif (config.minutes.step > 1) {
delta = (border - (timestamp % border)) % timestamp;
}
return (timestamp + delta);
};
/**
* Touch Support
* http://stackoverflow.com/questions/2264072/detect-a-finger-swipe-through-javascript-on-the-iphone-and-android
*/
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
}
/**
* @param {Event} evt
* @return {Number}
*/
function handleTouchMove(evt, callback) {
if (!xDown || !yDown) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
callback(1);
} else {
/* down swipe */
callback(-1);
}
}
/* reset values */
xDown = null;
yDown = null;
}
/*****************************************************************************
* PUBLIC API
*
* Getters
****************************************************************************/
// Here is a set of the default Date function
// We are providing them because the user are familiar with them and
// maybe this way they will implemet this library easily in their system
// "Wed Sep 23 2015"
var toDateString = function() {
return values.date.toDateString();
};
// "Wed, 23 Sep 2015 08:43:47 GMT"
var toGMTString = function() {
return values.date.toGMTString();
};
// "2015-09-23T08:43:47.284Z"
var toISOString = function() {
return values.date.toISOString();
};
// "9/23/2015"
var toLocaleDateString = function() {
return values.date.toLocaleDateString();
};
// "9/23/2015, 11:43:47 AM"
var toLocaleString = function() {
return values.date.toLocaleString();
};
// "11:43:47 AM"
var toLocaleTimeString = function() {
return values.date.toLocaleTimeString();
};
// "Wed Sep 23 2015 11:43:47 GMT+0300 (EEST)"
var toString = function() {
if (plugins.timezones) {
return toDateString() + ' ' + toTimeString();
}
return values.date.toString();
};
// 11:43:47 GMT+0300 (EEST)"
var toTimeString = function() {
if (plugins.timezones) {
var toReturn = '',
timeString = values.date.toTimeString().split(' ');
toReturn += timeString[0];
toReturn += ' GMT' + (config.utcTimezone.offset > 0 ? '+' : '-') + (Math.abs(config.utcTimezone.offset) < 10 ? '0' : '') + Math.abs(config.utcTimezone.offset) + '00';
toReturn += ' (' + config.utcTimezone.abbr + ')';
return toReturn;
}
return values.date.toTimeString();
};
// "Wed, 23 Sep 2015 08:43:47 GMT"
var toUTCString = function() {
return values.date.toUTCString();
};
/**
* Return datetime in specific format
* @param {String} input
* @return {String}
*
* M,MM, MMM
* d,D
* Y,YY, YYYY
*
* h, hh
* m, mm
* a, AA
* Z, ZZ
*/
var format = function(input) {
var currentHours = getHours();
var currentMinutes = getMinutes();
var currentAmPm = getIsAm();
var currentDate = getDate();
var currentMonth = getMonth() + 1;
var currentYear = getYear();
var currentTimezone = config.utcTimezone.offset;
// Dates
input = specialReplace(input, 'DD', prependZero(currentDate));
input = specialReplace(input, 'D', currentDate);
// Years
input = specialReplace(input, 'YYYY', currentYear);
input = specialReplace(input, 'YY', currentYear.toString().substr(2));
input = specialReplace(input, 'Y', currentYear);
// Hours
input = specialReplace(input, 'HH', prependZero(transformAmPm(currentHours, currentAmPm)));
input = specialReplace(input, 'hh', prependZero(currentHours));
input = specialReplace(input, 'H', transformAmPm(currentHours, currentAmPm));
input = specialReplace(input, 'h', currentHours);
// Minutes
input = specialReplace(input, 'mm', prependZero(currentMinutes));
input = specialReplace(input, 'm', getMinutes());
// Am Pm
input = specialReplace(input, 'a', currentAmPm ? 'am' : 'pm');
input = specialReplace(input, 'A', currentAmPm ? 'AM' : 'PM');
// Months
input = specialReplace(input, 'MMM', config.monthsNames[currentMonth-1]);
input = specialReplace(input, 'MM', prependZero(currentMonth));
input = specialReplace(input, 'M', currentMonth);
input = specialReplace(input, 'ZZ', (currentTimezone > 0 ? '+' : '-') + prependZero(Math.abs(currentTimezone)) + ':00');
input = specialReplace(input, 'Z', (currentTimezone > 0 ? '+' : '-') + Math.abs(currentTimezone) + ':00');
input = input.split('#%#').join('');
function specialReplace(input, selector, value) {
var specialDelimiter = '#%#';
var regex = new RegExp(selector+'(?!'+specialDelimiter+')', 'g');
input = input.replace(regex, value + specialDelimiter);
return input;
}
function prependZero(value) {
return value <= 9 ? ('0'+value) : value;
}
function transformAmPm(hours, ampm) {
if (!config.disableAmPm) {
if (hours === 12) {
return ampm ? 0 : 12;
}
return ampm ? hours : hours + 12;
}
else {
return hours;
}
}
return input;
};
/*****************************************************************************
* PUBLIC API
*
* Events
****************************************************************************/
var onChange = function(target, callback) {
events.onChange[target].push(callback);
};
var beforeChange = function(target, callback) {
events.beforeChange[target].push(callback);
};
var afterChange = function(target, callback) {
events.afterChange[target].push(callback);
};
function detectBrowser() {
var browser = {
isChrome: false,
isSafari: false,
isFirefox: false,
};
Iif (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
browser.isSafari = true;
}
return browser;
}
/**
* Public API here
*/
this.init = init;
this.setConfig = setConfig;
// Closing these interfaces, use format, instead of them
// this.getHours = getHours;
// this.getMinutes = getMinutes;
// this.getIsAm = getIsAm;
// this.getIsPm = getIsPm;
// this.getTime = getTime;
// this.getDate = getDate;
// this.getMonth = getMonth;
// this.getYear = getYear;
this.getFullTime = getFullTime;
this.getTimestamp = getTimestamp;
this.setHours = setHours;
this.setMinutes = setMinutes;
this.setAmPm = setAmPm;
this.setDate = setDate;
this.setMonth = setMonth;
this.setYear = setYear;
this.setTimestamp = setTimestamp;
this.values = values;
// Here is the set with the default Date getters
this.toDateString = toDateString;
this.toGMTString = toGMTString;
this.toISOString = toISOString;
this.toLocaleDateString = toLocaleDateString;
this.toLocaleString = toLocaleString;
this.toLocaleTimeString = toLocaleTimeString;
this.toString = toString;
this.toTimeString = toTimeString;
this.toUTCString = toUTCString;
this.format = format;
// Here are some events which the api provides
this.onChange = onChange;
this.beforeChange = beforeChange;
this.afterChange = afterChange;
// Lets init all
init(inputConfig);
}
|