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
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
if (typeof(ICAL) === 'undefined')
(typeof(window) !== 'undefined') ? this.ICAL = {} : ICAL = {};
ICAL.foldLength = 75;
ICAL.newLineChar = '\r\n';
/**
* Helper functions used in various places within ical.js
*/
ICAL.helpers = {
initState: function initState(aLine, aLineNr) {
return {
buffer: aLine,
line: aLine,
lineNr: aLineNr,
character: 0,
currentData: null,
parentData: []
};
},
initComponentData: function initComponentData(aName) {
return {
name: aName,
type: "COMPONENT",
value: []
};
},
/**
* Creates or returns a class instance
* of a given type with the initialization
* data if the data is not already an instance
* of the given type.
*
*
* Example:
*
* var time = new ICAL.icaltime(...);
* var result = ICAL.helpers.formatClassType(time, ICAL.icaltime);
*
* (result instanceof ICAL.icaltime)
* // => true
*
* result = ICAL.helpers.formatClassType({}, ICAL.icaltime);
* (result isntanceof ICAL.icaltime)
* // => true
*
*
* @param {Object} data object initialization data.
* @param {Object} type object type (like ICAL.icaltime).
*/
formatClassType: function formatClassType(data, type) {
if (typeof(data) === 'undefined')
return undefined;
if (data instanceof type) {
return data;
}
return new type(data);
},
/**
* Identical to index of but will only match values
* when they are not preceded by a backslash char \\\
*
* @param {String} buffer string value.
* @param {String} search value.
* @param {Numeric} pos start position.
*/
unescapedIndexOf: function(buffer, search, pos) {
while ((pos = buffer.indexOf(search, pos)) !== -1) {
if (pos > 0 && buffer[pos - 1] === '\\') {
pos += 1;
} else {
return pos;
}
}
return -1;
},
binsearchInsert: function(list, seekVal, cmpfunc) {
if (!list.length)
return 0;
var low = 0, high = list.length - 1,
mid, cmpval;
while (low <= high) {
mid = low + Math.floor((high - low) / 2);
cmpval = cmpfunc(seekVal, list[mid]);
if (cmpval < 0)
high = mid - 1;
else if (cmpval > 0)
low = mid + 1;
else
break;
}
if (cmpval < 0)
return mid; // insertion is displacing, so use mid outright.
else if (cmpval > 0)
return mid + 1;
else
return mid;
},
dumpn: function() {
if (!ICAL.debug) {
return null;
}
if (typeof (console) !== 'undefined' && 'log' in console) {
ICAL.helpers.dumpn = function consoleDumpn(input) {
return console.log(input);
}
} else {
ICAL.helpers.dumpn = function geckoDumpn(input) {
dump(input + '\n');
}
}
return ICAL.helpers.dumpn(arguments[0]);
},
mixin: function(obj, data) {
if (data) {
for (var k in data) {
obj[k] = data[k];
}
}
return obj;
},
isArray: function(o) {
return o && (o instanceof Array || typeof o == "array");
},
clone: function(aSrc, aDeep) {
if (!aSrc || typeof aSrc != "object") {
return aSrc;
} else if (aSrc instanceof Date) {
return new Date(aSrc.getTime());
} else if ("clone" in aSrc) {
return aSrc.clone();
} else if (ICAL.helpers.isArray(aSrc)) {
var result = [];
for (var i = 0; i < aSrc.length; i++) {
result.push(aDeep ? ICAL.helpers.clone(aSrc[i], true) : aSrc[i]);
}
return result;
} else {
var result = {};
for (var name in aSrc) {
if (aSrc.hasOwnProperty(name)) {
this.dumpn("Cloning " + name + "\n");
if (aDeep) {
result[name] = ICAL.helpers.clone(aSrc[name], true);
} else {
result[name] = aSrc[name];
}
}
}
return result;
}
},
unfoldline: function unfoldline(aState) {
// Section 3.1
// if the line ends with a CRLF
// and the next line starts with a LINEAR WHITESPACE (space, htab, ...)
// then remove the CRLF and the whitespace to unsplit the line
var moreLines = true;
var line = "";
while (moreLines) {
moreLines = false;
var pos = aState.buffer.search(/\r?\n/);
if (pos > -1) {
var len = (aState.buffer[pos] == "\r" ? 2 : 1);
var nextChar = aState.buffer.substr(pos + len, 1);
if (nextChar.match(/^[ \t]$/)) {
moreLines = true;
line += aState.buffer.substr(0, pos);
aState.buffer = aState.buffer.substr(pos + len + 1);
} else {
// We're at the end of the line, copy the found chunk
line += aState.buffer.substr(0, pos);
aState.buffer = aState.buffer.substr(pos + len);
}
} else {
line += aState.buffer;
aState.buffer = "";
}
}
return line;
},
foldline: function foldline(aLine) {
var result = "";
var line = aLine || "";
while (line.length) {
result += ICAL.newLineChar + " " + line.substr(0, ICAL.foldLength);
line = line.substr(ICAL.foldLength);
}
return result.substr(ICAL.newLineChar.length + 1);
},
ensureKeyExists: function(obj, key, defvalue) {
if (!(key in obj)) {
obj[key] = defvalue;
}
},
hasKey: function(obj, key) {
return (obj && key in obj && obj[key]);
},
pad2: function pad(data) {
if (typeof(data) !== 'string') {
data = String(data);
}
var len = data.length;
switch (len) {
case 0:
return '00';
case 1:
return '0' + data;
default:
return data;
}
},
trunc: function trunc(number) {
return (number < 0 ? Math.ceil(number) : Math.floor(number));
}
};
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
ICAL.design = (function() {
'use strict';
var ICAL_NEWLINE = /\\\\|\\;|\\,|\\[Nn]/g;
function DecorationError() {
Error.apply(this, arguments);
}
DecorationError.prototype = {
__proto__: Error.prototype
};
function isStrictlyNaN(number) {
return typeof(number) === 'number' && isNaN(number);
}
/**
* Parses a string value that is expected to be an
* integer, when the valid is not an integer throws
* a decoration error.
*
* @param {String} string raw input.
* @return {Number} integer.
*/
function strictParseInt(string) {
var result = parseInt(string, 10);
if (isStrictlyNaN(result)) {
throw new DecorationError(
'Could not extract integer from "' + string + '"'
);
}
return result;
}
function replaceNewlineReplace(string) {
switch (string) {
case "\\\\":
return "\\";
case "\\;":
return ";";
case "\\,":
return ",";
case "\\n":
case "\\N":
return "\n";
default:
return string;
}
}
function replaceNewline(value) {
// avoid regex when possible.
if (value.indexOf('\\') === -1) {
return value;
}
return value.replace(ICAL_NEWLINE, replaceNewlineReplace);
}
/**
* Design data used by the parser to decide if data is semantically correct
*/
var design = {
DecorationError: DecorationError,
defaultType: 'text',
param: {
// Although the syntax is DQUOTE uri DQUOTE, I don't think we should
// enfoce anything aside from it being a valid content line.
// "ALTREP": { ... },
// CN just wants a param-value
// "CN": { ... }
"cutype": {
values: ["INDIVIDUAL", "GROUP", "RESOURCE", "ROOM", "UNKNOWN"],
allowXName: true,
allowIanaToken: true
},
"delegated-from": {
valueType: "cal-address",
multiValue: ","
},
"delegated-to": {
valueType: "cal-address",
multiValue: ","
},
// "DIR": { ... }, // See ALTREP
"encoding": {
values: ["8BIT", "BASE64"]
},
// "FMTTYPE": { ... }, // See ALTREP
"fbtype": {
values: ["FREE", "BUSY", "BUSY-UNAVAILABLE", "BUSY-TENTATIVE"],
allowXName: true,
allowIanaToken: true
},
// "LANGUAGE": { ... }, // See ALTREP
"member": {
valueType: "cal-address",
multiValue: ","
},
"partstat": {
// TODO These values are actually different per-component
values: ["NEEDS-ACTION", "ACCEPTED", "DECLINED", "TENTATIVE",
"DELEGATED", "COMPLETED", "IN-PROCESS"],
allowXName: true,
allowIanaToken: true
},
"range": {
values: ["THISLANDFUTURE"]
},
"related": {
values: ["START", "END"]
},
"reltype": {
values: ["PARENT", "CHILD", "SIBLING"],
allowXName: true,
allowIanaToken: true
},
"role": {
values: ["REQ-PARTICIPANT", "CHAIR",
"OPT-PARTICIPANT", "NON-PARTICIPANT"],
allowXName: true,
allowIanaToken: true
},
"rsvp": {
valueType: "boolean"
},
"sent-by": {
valueType: "cal-address"
},
"tzid": {
matches: /^\//
},
"value": {
// since the value here is a 'type' lowercase is used.
values: ["binary", "boolean", "cal-address", "date", "date-time",
"duration", "float", "integer", "period", "recur", "text",
"time", "uri", "utc-offset"],
allowXName: true,
allowIanaToken: true
}
},
// When adding a value here, be sure to add it to the parameter types!
value: {
"binary": {
decorate: function(aString) {
return ICAL.icalbinary.fromString(aString);
},
undecorate: function(aBinary) {
return aBinary.toString();
}
},
"boolean": {
values: ["TRUE", "FALSE"],
fromICAL: function(aValue) {
switch(aValue) {
case 'TRUE':
return true;
case 'FALSE':
return false;
default:
//TODO: parser warning
return false;
}
},
toICAL: function(aValue) {
if (aValue) {
return 'TRUE';
}
return 'FALSE';
}
},
"cal-address": {
// needs to be an uri
},
"date": {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parseDate(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of DATE value");
return data;
},
decorate: function(aValue) {
// YYYY-MM-DD
// 2012-10-10
return new ICAL.icaltime({
year: strictParseInt(aValue.substr(0, 4)),
month: strictParseInt(aValue.substr(5, 2)),
day: strictParseInt(aValue.substr(8, 2)),
isDate: true
});
},
/**
* undecorates a time object.
*/
undecorate: function(aValue) {
// 2012-10-10
return aValue.year + '-' +
ICAL.helpers.pad2(aValue.month) + '-' +
ICAL.helpers.pad2(aValue.day);
},
fromICAL: function(aValue) {
// from: 20120901
// to: 2012-09-01
var result = aValue.substr(0, 4) + '-' +
aValue.substr(4, 2) + '-' +
aValue.substr(6, 2);
return result;
},
toICAL: function(aValue) {
// from: 2012-09-01
// to: 20120901
if (aValue.length !== 10) {
//TODO: serialize warning?
return aValue;
}
return aValue.substr(0, 4) +
aValue.substr(5, 2) +
aValue.substr(8, 2);
}
},
"date-time": {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parseDateTime(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of DATE-TIME value");
return data;
},
fromICAL: function(aValue) {
// from: 20120901T130000
// to: 2012-09-01T13:00:00
var result = aValue.substr(0, 4) + '-' +
aValue.substr(4, 2) + '-' +
aValue.substr(6, 2) + 'T' +
aValue.substr(9, 2) + ':' +
aValue.substr(11, 2) + ':' +
aValue.substr(13, 2);
if (aValue[15] === 'Z') {
result += 'Z'
}
return result;
},
toICAL: function(aValue) {
// from: 2012-09-01T13:00:00
// to: 20120901T130000
if (aValue.length < 19) {
// TODO: error
return aValue;
}
var result = aValue.substr(0, 4) +
aValue.substr(5, 2) +
// grab the (DDTHH) segment
aValue.substr(8, 5) +
// MM
aValue.substr(14, 2) +
// SS
aValue.substr(17, 2);
if (aValue[19] === 'Z') {
result += 'Z';
}
return result;
},
decorate: function(aValue) {
if (aValue.length < 19) {
throw new DecorationError(
'invalid date-time value: "' + aValue + '"'
);
}
// 2012-10-10T10:10:10(Z)?
var time = new ICAL.icaltime({
year: strictParseInt(aValue.substr(0, 4)),
month: strictParseInt(aValue.substr(5, 2)),
day: strictParseInt(aValue.substr(8, 2)),
hour: strictParseInt(aValue.substr(11, 2)),
minute: strictParseInt(aValue.substr(14, 2)),
second: strictParseInt(aValue.substr(17, 2))
});
if (aValue[19] === 'Z') {
time.zone = ICAL.icaltimezone.utc_timezone;
}
return time;
},
undecorate: function(aValue) {
var result = aValue.year + '-' +
ICAL.helpers.pad2(aValue.month) + '-' +
ICAL.helpers.pad2(aValue.day) + 'T' +
ICAL.helpers.pad2(aValue.hour) + ':' +
ICAL.helpers.pad2(aValue.minute) + ':' +
ICAL.helpers.pad2(aValue.second);
if (aValue.zone === ICAL.icaltimezone.utc_timezone) {
result += 'Z';
}
return result;
}
},
duration: {
decorate: function(aValue) {
return ICAL.icalduration.fromString(aValue);
},
undecorate: function(aValue) {
return aValue.toString();
}
},
float: {
matches: /^[+-]?\d+\.\d+$/,
decorate: function(aValue) {
return ICAL.icalvalue.fromString(aValue, "float");
},
fromICAL: function(aValue) {
var parsed = parseFloat(aValue);
if (isStrictlyNaN(parsed)) {
// TODO: parser warning
return 0.0;
}
return parsed;
},
toICAL: function(aValue) {
return String(aValue);
}
},
integer: {
fromICAL: function(aValue) {
var parsed = parseInt(aValue);
if (isStrictlyNaN(parsed)) {
return 0;
}
return parsed;
},
toICAL: function(aValue) {
return String(aValue);
}
},
period: {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parsePeriod(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of PERIOD value");
return data;
},
decorate: function(aValue) {
return ICAL.icalperiod.fromString(aValue);
},
undecorate: function(aValue) {
return aValue.toString();
}
},
recur: {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parseRecur(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of RECUR value");
return data;
},
decorate: function decorate(aValue) {
return ICAL.icalrecur.fromString(aValue);
},
undecorate: function(aRecur) {
return aRecur.toString();
}
},
text: {
matches: /.*/,
fromICAL: function(aValue, aName) {
return replaceNewline(aValue);
},
toICAL: function escape(aValue, aName) {
return aValue.replace(/\\|;|,|\n/g, function(str) {
switch (str) {
case "\\":
return "\\\\";
case ";":
return "\\;";
case ",":
return "\\,";
case "\n":
return "\\n";
default:
return str;
}
});
}
},
time: {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parseTime(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of TIME value");
return data;
},
fromICAL: function(aValue) {
// from: MMHHSS(Z)?
// to: HH:MM:SS(Z)?
if (aValue.length < 6) {
// TODO: parser exception?
return aValue;
}
// HH::MM::SSZ?
var result = aValue.substr(0, 2) + ':' +
aValue.substr(2, 2) + ':' +
aValue.substr(4, 2);
if (aValue[6] === 'Z') {
result += 'Z';
}
return result;
},
toICAL: function(aValue) {
// from: HH:MM:SS(Z)?
// to: MMHHSS(Z)?
if (aValue.length < 8) {
//TODO: error
return aValue;
}
var result = aValue.substr(0, 2) +
aValue.substr(3, 2) +
aValue.substr(6, 2);
if (aValue[8] === 'Z') {
result += 'Z';
}
return result;
}
},
uri: {
// TODO
/* ... */
},
"utc-offset": {
validate: function(aValue) {
var state = {
buffer: aValue
};
var data = ICAL.DecorationParser.parseUtcOffset(state);
ICAL.DecorationParser.expectEnd(state, "Junk at end of UTC-OFFSET value");
return data;
},
decorate: function(aValue) {
return ICAL.icalutcoffset.fromString(aValue);
},
undecorate: function(aValue) {
return aValue.toString();
}
}
},
property: {
decorate: function decorate(aData, aParent) {
return new ICAL.Property(aData, aParent);
},
"attach": {
defaultType: "uri"
},
"attendee": {
defaultType: "cal-address"
},
"categories": {
defaultType: "text",
multiValue: ","
},
"completed": {
defaultType: "date-time"
},
"created": {
defaultType: "date-time"
},
"dtend": {
defaultType: "date-time",
allowedTypes: ["date-time", "date"]
},
"dtstamp": {
defaultType: "date-time"
},
"dtstart": {
defaultType: "date-time",
allowedTypes: ["date-time", "date"]
},
"due": {
defaultType: "date-time",
allowedTypes: ["date-time", "date"]
},
"duration": {
defaultType: "duration"
},
"exdate": {
defaultType: "date-time",
allowedTypes: ["date-time", "date"],
multiValue: ','
},
"exrule": {
defaultType: "recur"
},
"freebusy": {
defaultType: "period",
multiValue: ","
},
"geo": {
defaultType: "float",
multiValue: ";"
},
/* TODO exactly 2 values */"last-modified": {
defaultType: "date-time"
},
"organizer": {
defaultType: "cal-address"
},
"percent-complete": {
defaultType: "integer"
},
"repeat": {
defaultType: "integer"
},
"rdate": {
defaultType: "date-time",
allowedTypes: ["date-time", "date", "period"],
multiValue: ','
},
"recurrence-id": {
defaultType: "date-time",
allowedTypes: ["date-time", "date"]
},
"resources": {
defaultType: "text",
multiValue: ","
},
"request-status": {
defaultType: "text",
multiValue: ";"
},
"priority": {
defaultType: "integer"
},
"rrule": {
defaultType: "recur"
},
"sequence": {
defaultType: "integer"
},
"trigger": {
defaultType: "duration",
allowedTypes: ["duration", "date-time"]
},
"tzoffsetfrom": {
defaultType: "utc-offset"
},
"tzoffsetto": {
defaultType: "utc-offset"
},
"tzurl": {
defaultType: "uri"
},
"url": {
defaultType: "uri"
}
},
component: {
decorate: function decorate(aData, aParent) {
return new ICAL.Component(aData, aParent);
},
"vevent": {}
}
};
return design;
}());
ICAL.stringify = (function() {
'use strict';
var LINE_ENDING = '\r\n';
var DEFAULT_TYPE = 'text';
var design = ICAL.design;
var helpers = ICAL.helpers;
/**
* Convert a full jCal Array into a ical document.
*
* @param {Array} jCal document.
* @return {String} ical document.
*/
function stringify(jCal) {
if (!jCal[0] || jCal[0] !== 'icalendar') {
throw new Error('must provide full jCal document');
}
// 1 because we skip the initial element.
var i = 1;
var len = jCal.length;
var result = '';
for (; i < len; i++) {
result += stringify.component(jCal[i]) + LINE_ENDING;
}
return result;
}
/**
* Converts an jCal component array into a ICAL string.
* Recursive will resolve sub-components.
*
* Exact component/property order is not saved all
* properties will come before subcomponents.
*
* @param {Array} component jCal fragment of a component.
*/
stringify.component = function(component) {
var name = component[0].toUpperCase();
var result = 'BEGIN:' + name + LINE_ENDING;
var props = component[1];
var propIdx = 0;
var propLen = props.length;
for (; propIdx < propLen; propIdx++) {
result += stringify.property(props[propIdx]) + LINE_ENDING;
}
var comps = component[2];
var compIdx = 0;
var compLen = comps.length;
for (; compIdx < compLen; compIdx++) {
result += stringify.component(comps[compIdx]) + LINE_ENDING;
}
result += 'END:' + name;
return result;
}
/**
* Converts a single property to a ICAL string.
*
* @param {Array} property jCal property.
*/
stringify.property = function(property) {
var name = property[0].toUpperCase();
var jsName = property[0];
var params = property[1];
var line = name;
var paramName;
for (paramName in params) {
if (params.hasOwnProperty(paramName)) {
line += ';' + paramName.toUpperCase();
line += '=' + stringify.propertyValue(params[paramName]);
}
}
// there is no value so return.
if (property.length === 3) {
// if no params where inserted and no value
// we given we must add a blank value.
if (!paramName) {
line += ':';
}
return line;
}
var valueType = property[2];
var propDetails;
var multiValue = false;
var isDefault = false;
if (jsName in design.property) {
propDetails = design.property[jsName];
if ('multiValue' in propDetails) {
multiValue = propDetails.multiValue;
}
if ('defaultType' in propDetails) {
if (valueType === propDetails.defaultType) {
isDefault = true;
}
} else {
if (valueType === DEFAULT_TYPE) {
isDefault = true;
}
}
} else {
if (valueType === DEFAULT_TYPE) {
isDefault = true;
}
}
// push the VALUE property if type is not the default
// for the current property.
if (!isDefault) {
// value will never contain ;/:/, so we don't escape it here.
line += ';VALUE=' + valueType.toUpperCase();
}
line += ':';
if (multiValue) {
line += stringify.multiValue(
property.slice(3), multiValue, valueType
);
} else {
line += stringify.value(property[3], valueType);
}
return ICAL.helpers.foldline(line);
}
/**
* Handles escaping of property values that may contain:
*
* COLON (:), SEMICOLON (;), or COMMA (,)
*
* If any of the above are present the result is wrapped
* in double quotes.
*
* @param {String} value raw value.
* @return {String} given or escaped value when needed.
*/
stringify.propertyValue = function(value) {
if ((helpers.unescapedIndexOf(value, ',') === -1) &&
(helpers.unescapedIndexOf(value, ':') === -1) &&
(helpers.unescapedIndexOf(value, ';') === -1)) {
return value;
}
return '"' + value + '"';
}
/**
* Converts an array of ical values into a single
* string based on a type and a delimiter value (like ",").
*
* @param {Array} values list of values to convert.
* @param {String} delim used to join the values usually (",", ";", ":").
* @param {String} type lowecase ical value type
* (like boolean, date-time, etc..).
*
* @return {String} ical string for value.
*/
stringify.multiValue = function(values, delim, type) {
var result = '';
var len = values.length;
var i = 0;
for (; i < len; i++) {
result += stringify.value(values[i], type);
if (i !== (len - 1)) {
result += delim;
}
}
return result;
}
/**
* Processes a single ical value runs the associated "toICAL"
* method from the design value type if available to convert
* the value.
*
* @param {String|Numeric} value some formatted value.
* @param {String} type lowecase ical value type
* (like boolean, date-time, etc..).
* @return {String} ical value for single value.
*/
stringify.value = function(value, type) {
if (type in design.value && 'toICAL' in design.value[type]) {
return design.value[type].toICAL(value);
}
return value;
}
return stringify;
}());
ICAL.parse = (function() {
'use strict';
var CHAR = /[^ \t]/;
var MULTIVALUE_DELIMITER = ',';
var VALUE_DELIMITER = ':';
var PARAM_DELIMITER = ';';
var PARAM_NAME_DELIMITER = '=';
var DEFAULT_TYPE = 'text';
var design = ICAL.design;
var helpers = ICAL.helpers;
function ParserError(message) {
Error.apply(this, arguments);
}
ParserError.prototype = {
__proto__: Error.prototype
};
function parser(input) {
var state = {};
var root = state.component = [
'icalendar'
];
state.stack = [root];
parser._eachLine(input, function(err, line) {
parser._handleContentLine(line, state);
});
// when there are still items on the stack
// throw a fatal error, a component was not closed
// correctly in that case.
if (state.stack.length > 1) {
throw new ParserError(
'invalid ical body, a began started but did not end'
);
}
state = null;
return root;
}
// classes & constants
parser.ParserError = ParserError;
parser._formatName = function(name) {
return name.toLowerCase();
}
parser._handleContentLine = function(line, state) {
// break up the parts of the line
var valuePos = line.indexOf(VALUE_DELIMITER);
var paramPos = line.indexOf(PARAM_DELIMITER);
var nextPos = 0;
// name of property or begin/end
var name;
var value;
var params;
/**
* Different property cases
*
*
* 1. RRULE:FREQ=foo
* // FREQ= is not a param but the value
*
* 2. ATTENDEE;ROLE=REQ-PARTICIPANT;
* // ROLE= is a param because : has not happened yet
*/
if ((paramPos !== -1 && valuePos !== -1)) {
// when the parameter delimiter is after the
// value delimiter then its not a parameter.
if (paramPos > valuePos) {
paramPos = -1;
}
}
if (paramPos !== -1) {
// when there are parameters (ATTENDEE;RSVP=TRUE;)
name = parser._formatName(line.substr(0, paramPos));
params = parser._parseParameters(line, paramPos);
if (valuePos !== -1) {
value = line.substr(valuePos + 1);
}
} else if (valuePos !== -1) {
// without parmeters (BEGIN:VCAENDAR, CLASS:PUBLIC)
name = parser._formatName(line.substr(0, valuePos));
value = line.substr(valuePos + 1);
if (name === 'begin') {
var newComponent = [parser._formatName(value), [], []];
if (state.stack.length === 1) {
state.component.push(newComponent);
} else {
state.component[2].push(newComponent);
}
state.stack.push(state.component);
state.component = newComponent;
return;
}
if (name === 'end') {
state.component = state.stack.pop();
return;
}
} else {
/**
* Invalid line.
* The rational to throw an error is we will
* never be certain that the rest of the file
* is sane and its unlikely that we can serialize
* the result correctly either.
*/
throw new ParserError(
'invalid line (no token ";" or ":") "' + line + '"'
);
}
var valueType;
var multiValue = false;
var propertyDetails;
if (name in design.property) {
propertyDetails = design.property[name];
if ('multiValue' in propertyDetails) {
multiValue = propertyDetails.multiValue;
}
}
// at this point params is mandatory per jcal spec
params = params || {};
// attempt to determine value
if (!('value' in params)) {
if (propertyDetails) {
valueType = propertyDetails.defaultType;
} else {
valueType = DEFAULT_TYPE;
}
} else {
// possible to avoid this?
valueType = params.value.toLowerCase();
delete params.value;
}
/**
* Note on `var result` juggling:
*
* I observed that building the array in pieces has adverse
* effects on performance, so where possible we inline the creation.
* Its a little ugly but resulted in ~2000 additional ops/sec.
*/
if (value) {
if (multiValue) {
var result = [name, params, valueType];
parser._parseMultiValue(value, multiValue, valueType, result);
} else {
value = parser._parseValue(value, valueType);
var result = [name, params, valueType, value];
}
} else {
var result = [name, params, valueType];
}
state.component[1].push(result);
};
/**
* @param {String} value original value.
* @param {String} type type of value.
* @return {Object} varies on type.
*/
parser._parseValue = function(value, type) {
if (type in design.value && 'fromICAL' in design.value[type]) {
return design.value[type].fromICAL(value);
}
return value;
};
/**
* Parse parameters from a string to object.
*
* @param {String} line a single unfolded line.
* @param {Numeric} start position to start looking for properties.
* @param {Numeric} maxPos position at which values start.
* @return {Object} key/value pairs.
*/
parser._parseParameters = function(line, start) {
var lastParam = start;
var pos = 0;
var delim = PARAM_NAME_DELIMITER;
var result = {};
// find the next '=' sign
// use lastParam and pos to find name
// check if " is used if so get value from "->"
// then increment pos to find next ;
while ((pos !== false) &&
(pos = helpers.unescapedIndexOf(line, delim, pos + 1)) !== -1) {
var name = line.substr(lastParam + 1, pos - lastParam - 1);
var nextChar = line[pos + 1];
var substrOffset = -2;
if (nextChar === '"') {
var valuePos = pos + 2;
pos = helpers.unescapedIndexOf(line, '"', valuePos);
var value = line.substr(valuePos, pos - valuePos);
lastParam = helpers.unescapedIndexOf(line, PARAM_DELIMITER, pos);
} else {
var valuePos = pos + 1;
substrOffset = -1;
// move to next ";"
var nextPos = helpers.unescapedIndexOf(line, PARAM_DELIMITER, valuePos);
if (nextPos === -1) {
// when there is no ";" attempt to locate ":"
nextPos = helpers.unescapedIndexOf(line, VALUE_DELIMITER, valuePos);
// no more tokens end of the line use .length
if (nextPos === -1) {
nextPos = line.length;
// because we are at the end we don't need to trim
// the found value of substr offset is zero
substrOffset = 0;
} else {
// next token is the beginning of the value
// so we must stop looking for the '=' token.
pos = false;
}
} else {
lastParam = nextPos;
}
var value = line.substr(valuePos, nextPos - valuePos);
}
var type = DEFAULT_TYPE;
if (name in design.param && design.param[name].valueType) {
type = design.param[name].valueType;
}
result[parser._formatName(name)] = parser._parseValue(value, type);
}
return result;
}
/**
* Parse a multi value string
*/
parser._parseMultiValue = function(buffer, delim, type, result) {
var pos = 0;
var lastPos = 0;
// split each piece
while ((pos = helpers.unescapedIndexOf(buffer, delim, lastPos)) !== -1) {
var value = buffer.substr(lastPos, pos - lastPos);
result.push(parser._parseValue(value, type));
lastPos = pos + 1;
}
// on the last piece take the rest of string
result.push(
parser._parseValue(buffer.substr(lastPos), type)
);
return result;
}
parser._eachLine = function(buffer, callback) {
var len = buffer.length;
var lastPos = buffer.search(CHAR);
var pos = lastPos;
var line;
var firstChar;
var newlineOffset;
do {
pos = buffer.indexOf('\n', lastPos) + 1;
if (buffer[pos - 2] === '\r') {
newlineOffset = 2;
} else {
newlineOffset = 1;
}
if (pos === 0) {
pos = len;
newlineOffset = 0;
}
firstChar = buffer[lastPos];
if (firstChar === ' ' || firstChar === '\t') {
// add to line
line += buffer.substr(
lastPos + 1,
pos - lastPos - (newlineOffset + 1)
);
} else {
if (line)
callback(null, line);
// push line
line = buffer.substr(
lastPos,
pos - lastPos - newlineOffset
);
}
lastPos = pos;
} while (pos !== len);
// extra ending line
line = line.trim();
if (line.length)
callback(null, line);
}
return parser;
}());
/* This Source Code Form is subject to the terms of the Mozilla Public
console.log()
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
/**
* home of the original parser, we have re-purposed most
* of the decoration parsing here in the icaltype classes (like period).
* Eventually we need to to through each of these and make sure
* they are as efficient as possible. Most of these are very complete
* and validate input but are slow due to their heavy use of RegExp.
*/
function ParserError(aState, aMessage) {
this.mState = aState;
this.name = "ParserError";
if (aState) {
var lineNrData = ("lineNr" in aState ? aState.lineNr + ":" : "") +
("character" in aState && !isNaN(aState.character) ?
aState.character + ":" :
"");
var message = lineNrData + aMessage;
if ("buffer" in aState) {
if (aState.buffer) {
message += " before '" + aState.buffer + "'";
} else {
message += " at end of line";
}
}
if ("line" in aState) {
message += " in '" + aState.line + "'";
}
this.message = message;
} else {
this.message = aMessage;
}
// create stack
try {
throw new Error();
} catch (e) {
var split = e.stack.split('\n');
split.shift();
this.stack = split.join('\n');
}
}
ParserError.prototype = {
__proto__: Error.prototype,
constructor: ParserError
};
var parser = {
Error: ParserError
};
ICAL.DecorationParser = parser;
parser.validateValue = function validateValue(aLineData, aValueType,
aValue, aCheckParams) {
var propertyData = ICAL.design.property[aLineData.name];
var valueData = ICAL.design.value[aValueType];
// TODO either make validators just consume the value, then check for end
// here (possibly requires returning remainder or renaming buffer<->value
// in the states) validators don't really need the whole linedata
if (!aValue.match) {
ICAL.helpers.dumpn("MAAA: " + aValue + " ? " + aValue.toString());
}
if (valueData.matches) {
// Test against regex
if (!aValue.match(valueData.matches)) {
throw new ParserError(aLineData, "Value '" + aValue + "' for " +
aLineData.name + " is not " + aValueType);
}
} else if ("validate" in valueData) {
// Validator throws an error itself if needed
var objData = valueData.validate(aValue);
// Merge in extra value data, if it exists
ICAL.helpers.mixin(aLineData, objData);
} else if ("values" in valueData) {
// Fixed list of values
if (valueData.values.indexOf(aValue) < 0) {
throw new ParserError(aLineData, "Value for " + aLineData.name +
" is not a " + aValueType);
}
}
if (aCheckParams && "requireParam" in valueData) {
var reqParam = valueData.requireParam;
for (var param in reqParam) {
if (!("parameters" in aLineData) ||
!(param in aLineData.parameters) ||
aLineData.parameters[param] != reqParam[param]) {
throw new ParserError(aLineData, "Value requires " + param + "=" +
valueData.requireParam[param]);
}
}
}
return aLineData;
};
parser.parseValue = function parseValue(aStr, aType) {
var lineData = {
value: [aStr]
};
return parser.validateValue(lineData, aType, aStr, false);
};
parser.parseDateOrDateTime = function parseDateOrDateTime(aState) {
var data = parser.parseDate(aState);
if (parser.expectOptionalRE(aState, /^T/)) {
// This has a time component, parse it
var time = parser.parseTime(aState);
if (parser.expectOptionalRE(aState, /^Z/)) {
data.timezone = "Z";
}
ICAL.helpers.mixin(data, time);
}
return data;
};
parser.parseDateTime = function parseDateTime(aState) {
var data = parser.parseDate(aState);
parser.expectRE(aState, /^T/, "Expected 'T'");
var time = parser.parseTime(aState);
if (parser.expectOptionalRE(aState, /^Z/)) {
data.timezone = "Z";
}
ICAL.helpers.mixin(data, time);
return data;
};
parser.parseDate = function parseDate(aState) {
var dateRE = /^((\d{4})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))/;
var match = parser.expectRE(aState, dateRE, "Expected YYYYMMDD Date");
return {
year: parseInt(match[2], 10),
month: parseInt(match[3], 10),
day: parseInt(match[4], 10)
};
// TODO timezone?
};
parser.parseTime = function parseTime(aState) {
var timeRE = /^(([01][0-9]|2[0-3])([0-5][0-9])([0-5][0-9]|60))/;
var match = parser.expectRE(aState, timeRE, "Expected HHMMSS Time");
return {
hour: parseInt(match[2], 10),
minute: parseInt(match[3], 10),
second: parseInt(match[4], 10)
};
};
parser.parseDuration = function parseDuration(aState) {
var error = "Expected Duration Value";
function parseDurSecond(aState) {
var secMatch = parser.expectRE(aState, /^((\d+)S)/, "Expected Seconds");
return {
seconds: parseInt(secMatch[2], 10)
};
}
function parseDurMinute(aState) {
var data = {};
var minutes = parser.expectRE(aState, /^((\d+)M)/, "Expected Minutes");
try {
data = parseDurSecond(aState);
} catch (e) {
// seconds are optional, its ok
if (!(e instanceof ParserError)) {
throw e;
}
}
data.minutes = parseInt(minutes[2], 10);
return data;
}
function parseDurHour(aState) {
var data = {};
var hours = parser.expectRE(aState, /^((\d+)H)/, "Expected Hours");
try {
data = parseDurMinute(aState);
} catch (e) {
// seconds are optional, its ok
if (!(e instanceof ParserError)) {
throw e;
}
}
data.hours = parseInt(hours[2], 10);
return data;
}
function parseDurWeek(aState) {
return {
weeks: parseInt(parser.expectRE(aState, /^((\d+)W)/, "Expected Weeks")[2], 10)
};
}
function parseDurTime(aState) {
parser.expectRE(aState, /^T/, "Expected Time Value");
return parser.parseAlternative(aState, parseDurHour,
parseDurMinute, parseDurSecond);
}
function parseDurDate(aState) {
var days = parser.expectRE(aState, /^((\d+)D)/, "Expected Days");
var data;
try {
data = parseDurTime(aState);
} catch (e) {
// Its ok if this fails
if (!(e instanceof ParserError)) {
throw e;
}
}
if (data) {
data.days = parseInt(days[2], 10);
} else {
data = {
days: parseInt(days[2], 10)
};
}
return data;
}
var factor = parser.expectRE(aState, /^([+-]?P)/, error);
var durData = parser.parseAlternative(aState, parseDurDate,
parseDurTime, parseDurWeek);
parser.expectEnd(aState, "Junk at end of DURATION value");
durData.factor = (factor[1] == "-P" ? -1 : 1);
return durData;
};
parser.parsePeriod = function parsePeriod(aState) {
var dtime = parser.parseDateTime(aState);
parser.expectRE(aState, /\//, "Expected '/'");
var dtdur = parser.parseAlternative(aState, parser.parseDateTime,
parser.parseDuration);
var data = {
start: dtime
};
if ("factor" in dtdur) {
data.duration = dtdur;
} else {
data.end = dtdur;
}
return data;
},
parser.parseRecur = function parseRecur(aState) {
// TODO this function is quite cludgy, maybe it should be done differently
function parseFreq(aState) {
parser.expectRE(aState, /^FREQ=/, "Expected Frequency");
var ruleRE = /^(SECONDLY|MINUTELY|HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY)/;
var match = parser.expectRE(aState, ruleRE, "Exepected Frequency Value");
return {
"FREQ": match[1]
};
}
function parseUntil(aState) {
parser.expectRE(aState, /^UNTIL=/, "Expected Frequency");
var untilDate = parser.parseDateOrDateTime(aState);
return {
"UNTIL": untilDate
};
}
function parseCount(aState) {
parser.expectRE(aState, /^COUNT=/, "Expected Count");
var match = parser.expectRE(aState, /^(\d+)/, "Expected Digit(s)");
return {
"COUNT": parseInt(match[1], 10)
};
}
function parseInterval(aState) {
parser.expectRE(aState, /^INTERVAL=/, "Expected Interval");
var match = parser.expectRE(aState, /^(\d+)/, "Expected Digit(s)");
return {
"INTERVAL": parseInt(match[1], 10)
};
}
function parseBySecond(aState) {
function parseSecond(aState) {
var secondRE = /^(60|[1-5][0-9]|[0-9])/;
var value = parser.expectRE(aState, secondRE, "Expected Second")[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYSECOND=/, "Expected BYSECOND");
var seconds = parser.parseList(aState, parseSecond, ",");
return {
"BYSECOND": seconds
};
}
function parseByMinute(aState) {
function parseMinute(aState) {
var minuteRE = /^([1-5][0-9]|[0-9])/;
var value = parser.expectRE(aState, minuteRE, "Expected Minute")[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYMINUTE=/, "Expected BYMINUTE");
var minutes = parser.parseList(aState, parseMinute, ",");
return {
"BYMINUTE": minutes
};
}
function parseByHour(aState) {
function parseHour(aState) {
var hourRE = /^(2[0-3]|1[0-9]|[0-9])/;
var value = parser.expectRE(aState, hourRE, "Expected Hour")[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYHOUR=/, "Expected BYHOUR");
var hours = parser.parseList(aState, parseHour, ",");
return {
"BYHOUR": hours
};
}
function parseByDay(aState) {
function parseWkDayNum(aState) {
var value = "";
var match = parser.expectOptionalRE(aState, /^([+-])/);
if (match) {
value += match[1];
}
match = parser.expectOptionalRE(aState, /^(5[0-3]|[1-4][0-9]|[1-9])/);
if (match) {
value += match[1];
}
var wkDayRE = /^(SU|MO|TU|WE|TH|FR|SA)/;
match = parser.expectRE(aState, wkDayRE, "Expected Week Ordinals");
value += match[1];
return value;
}
parser.expectRE(aState, /^BYDAY=/, "Expected BYDAY Rule");
var wkdays = parser.parseList(aState, parseWkDayNum, ",");
return {
"BYDAY": wkdays
};
}
function parseByMonthDay(aState) {
function parseMoDayNum(aState) {
var value = "";
var match = parser.expectOptionalRE(aState, /^([+-])/);
if (match) {
value += match[1];
}
match = parser.expectRE(aState, /^(3[01]|[12][0-9]|[1-9])/);
value += match[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYMONTHDAY=/, "Expected BYMONTHDAY Rule");
var modays = parser.parseList(aState, parseMoDayNum, ",");
return {
"BYMONTHDAY": modays
};
}
function parseByYearDay(aState) {
function parseYearDayNum(aState) {
var value = "";
var match = parser.expectOptionalRE(aState, /^([+-])/);
if (match) {
value += match[1];
}
var yrDayRE = /^(36[0-6]|3[0-5][0-9]|[12][0-9][0-9]|[1-9][0-9]|[1-9])/;
match = parser.expectRE(aState, yrDayRE);
value += match[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYYEARDAY=/, "Expected BYYEARDAY Rule");
var yrdays = parser.parseList(aState, parseYearDayNum, ",");
return {
"BYYEARDAY": yrdays
};
}
function parseByWeekNo(aState) {
function parseWeekNum(aState) {
var value = "";
var match = parser.expectOptionalRE(aState, /^([+-])/);
if (match) {
value += match[1];
}
match = parser.expectRE(aState, /^(5[0-3]|[1-4][0-9]|[1-9])/);
value += match[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYWEEKNO=/, "Expected BYWEEKNO Rule");
var weeknos = parser.parseList(aState, parseWeekNum, ",");
return {
"BYWEEKNO": weeknos
};
}
function parseByMonth(aState) {
function parseMonthNum(aState) {
var moNumRE = /^(1[012]|[1-9])/;
var match = parser.expectRE(aState, moNumRE, "Expected Month number");
return parseInt(match[1], 10);
}
parser.expectRE(aState, /^BYMONTH=/, "Expected BYMONTH Rule");
var monums = parser.parseList(aState, parseMonthNum, ",");
return {
"BYMONTH": monums
};
}
function parseBySetPos(aState) {
function parseSpList(aState) {
var spRE = /^(36[0-6]|3[0-5][0-9]|[12][0-9][0-9]|[1-9][0-9]|[1-9])/;
var value = parser.expectRE(aState, spRE)[1];
return parseInt(value, 10);
}
parser.expectRE(aState, /^BYSETPOS=/, "Expected BYSETPOS Rule");
var spnums = parser.parseList(aState, parseSpList, ",");
return {
"BYSETPOS": spnums
};
}
function parseWkst(aState) {
parser.expectRE(aState, /^WKST=/, "Expected WKST");
var wkstRE = /^(SU|MO|TU|WE|TH|FR|SA)/;
var match = parser.expectRE(aState, wkstRE, "Expected Weekday Name");
return {
"WKST": match[1]
};
}
function parseRulePart(aState) {
return parser.parseAlternative(aState,
parseFreq, parseUntil, parseCount, parseInterval,
parseBySecond, parseByMinute, parseByHour, parseByDay,
parseByMonthDay, parseByYearDay, parseByWeekNo,
parseByMonth, parseBySetPos, parseWkst);
}
// One or more rule parts
var value = parser.parseList(aState, parseRulePart, ";");
var data = {};
for (var key in value) {
ICAL.helpers.mixin(data, value[key]);
}
// Make sure there's no junk at the end
parser.expectEnd(aState, "Junk at end of RECUR value");
return data;
};
parser.parseUtcOffset = function parseUtcOffset(aState) {
var utcRE = /^(([+-])([01][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])?)$/;
var match = parser.expectRE(aState, utcRE, "Expected valid utc offset");
return {
factor: (match[2] == "-" ? -1 : 1),
hours: parseInt(match[3], 10),
minutes: parseInt(match[4], 10)
};
};
parser.parseAlternative = function parseAlternative(aState /*, parserFunc, ... */) {
var tokens = null;
var args = Array.prototype.slice.call(arguments);
var parser;
args.shift();
var errors = [];
while (!tokens && (parser = args.shift())) {
try {
tokens = parser(aState);
} catch (e) {
if (e instanceof ParserError) {
errors.push(e);
tokens = null;
} else {
throw e;
}
}
}
if (!tokens) {
var message = errors.join("\nOR ") || "No Tokens found";
throw new ParserError(aState, message);
}
return tokens;
},
parser.parseList = function parseList(aState, aElementFunc, aSeparator) {
var listvals = [];
listvals.push(aElementFunc(aState));
var re = new RegExp("^" + aSeparator + "");
while (parser.expectOptionalRE(aState, re)) {
listvals.push(aElementFunc(aState));
}
return listvals;
};
parser.expectOptionalRE = function expectOptionalRE(aState, aRegex) {
var match = aState.buffer.match(aRegex);
if (match) {
var count = ("1" in match ? match[1].length : match[0].length);
aState.buffer = aState.buffer.substr(count);
aState.character += count;
}
return match;
};
parser.expectRE = function expectRE(aState, aRegex, aErrorMessage) {
var match = parser.expectOptionalRE(aState, aRegex);
if (!match) {
throw new ParserError(aState, aErrorMessage);
}
return match;
};
parser.expectEnd = function expectEnd(aState, aErrorMessage) {
if (aState.buffer.length > 0) {
throw new ParserError(aState, aErrorMessage);
}
}
})();
ICAL.Component = (function() {
'use strict';
var PROPERTY_INDEX = 1;
var COMPONENT_INDEX = 2;
var NAME_INDEX = 0;
/**
* Create a wrapper for a jCal component.
*
* @param {Array|String} jCal
* raw jCal component data OR name of new component.
* @param {ICAL.Component} parent parent component to associate.
*/
function Component(jCal, parent) {
if (typeof(jCal) === 'string') {
// jCal spec (name, properties, components)
jCal = [jCal, [], []];
}
// mostly for legacy reasons.
this.jCal = jCal;
if (parent) {
this.parent = parent;
}
}
Component.prototype = {
get name() {
return this.jCal[NAME_INDEX];
},
_hydrateComponent: function(index) {
if (!this._components) {
this._components = [];
}
if (this._components[index]) {
return this._components[index];
}
var comp = new Component(
this.jCal[COMPONENT_INDEX][index],
this
);
return this._components[index] = comp;
},
_hydrateProperty: function(index) {
if (!this._properties) {
this._properties = [];
}
if (this._properties[index]) {
return this._properties[index];
}
var prop = new ICAL.Property(
this.jCal[PROPERTY_INDEX][index],
this
);
return this._properties[index] = prop;
},
/**
* Finds first sub component, optionally filtered by name.
*
* @method getFirstSubcomponent
* @param {String} [name] optional name to filter by.
*/
getFirstSubcomponent: function(name) {
if (name) {
var i = 0;
var comps = this.jCal[COMPONENT_INDEX];
var len = comps.length;
for (; i < len; i++) {
if (comps[i][NAME_INDEX] === name) {
var result = this._hydrateComponent(i);
return result;
}
}
} else {
if (this.jCal[COMPONENT_INDEX].length) {
return this._hydrateComponent(0);
}
}
// ensure we return a value (strict mode)
return null;
},
/**
* Finds all sub components, optionally filtering by name.
*
* @method getAllSubcomponents
* @param {String} [name] optional name to filter by.
*/
getAllSubcomponents: function(name) {
var jCalLen = this.jCal[COMPONENT_INDEX].length;
if (name) {
var comps = this.jCal[COMPONENT_INDEX];
var result = [];
var i = 0;
for (; i < jCalLen; i++) {
if (name === comps[i][NAME_INDEX]) {
result.push(
this._hydrateComponent(i)
);
}
}
return result;
} else {
if (!this._components ||
(this._components.length !== jCalLen)) {
var i = 0;
for (; i < jCalLen; i++) {
this._hydrateComponent(i);
}
}
return this._components;
}
},
/**
* Returns true when a named property exists.
*
* @param {String} name property name.
* @return {Boolean} true when property is found.
*/
hasProperty: function(name) {
var props = this.jCal[PROPERTY_INDEX];
var len = props.length;
var i = 0;
for (; i < len; i++) {
// 0 is property name
if (props[i][NAME_INDEX] === name) {
return true;
}
}
return false;
},
/**
* Finds first property.
*
* @param {String} [name] lowercase name of property.
* @return {ICAL.Property} found property.
*/
getFirstProperty: function(name) {
if (name) {
var i = 0;
var props = this.jCal[PROPERTY_INDEX];
var len = props.length;
for (; i < len; i++) {
if (props[i][NAME_INDEX] === name) {
var result = this._hydrateProperty(i);
return result;
}
}
} else {
if (this.jCal[PROPERTY_INDEX].length) {
return this._hydrateProperty(0);
}
}
return null;
},
/**
* Returns first properties value if available.
*
* @param {String} [name] (lowecase) property name.
* @return {String} property value.
*/
getFirstPropertyValue: function(name) {
var prop = this.getFirstProperty(name);
if (prop) {
return prop.getFirstValue();
}
return null;
},
/**
* get all properties in the component.
*
* @param {String} [name] (lowercase) property name.
* @return {Array[ICAL.Property]} list of properties.
*/
getAllProperties: function(name) {
var jCalLen = this.jCal[PROPERTY_INDEX].length;
if (name) {
var props = this.jCal[PROPERTY_INDEX];
var result = [];
var i = 0;
for (; i < jCalLen; i++) {
if (name === props[i][NAME_INDEX]) {
result.push(
this._hydrateProperty(i)
);
}
}
return result;
} else {
if (!this._properties ||
(this._properties.length !== jCalLen)) {
var i = 0;
for (; i < jCalLen; i++) {
this._hydrateProperty(i);
}
}
return this._properties;
}
return null;
},
_removeObjectByIndex: function(jCalIndex, cache, index) {
// remove cached version
if (cache && cache[index]) {
cache.splice(index, 1);
}
// remove it from the jCal
this.jCal[jCalIndex].splice(index, 1);
},
_removeObject: function(jCalIndex, cache, nameOrObject) {
var i = 0;
var objects = this.jCal[jCalIndex];
var len = objects.length;
var cached = this[cache];
if (typeof(nameOrObject) === 'string') {
for (; i < len; i++) {
if (objects[i][NAME_INDEX] === nameOrObject) {
this._removeObjectByIndex(jCalIndex, cached, i);
return true;
}
}
} else if (cached) {
for (; i < len; i++) {
if (cached[i] && cached[i] === nameOrObject) {
this._removeObjectByIndex(jCalIndex, cached, i);
return true;
}
}
}
return false;
},
_removeAllObjects: function(jCalIndex, cache, name) {
var cached = this[cache];
if (name) {
var objects = this.jCal[jCalIndex];
var i = objects.length - 1;
// descending search required because splice
// is used and will effect the indices.
for (; i >= 0; i--) {
if (objects[i][NAME_INDEX] === name) {
this._removeObjectByIndex(jCalIndex, cached, i);
}
}
} else {
if (cache in this) {
// I think its probable that when we remove all
// of a type we may want to add to it again so it
// makes sense to reuse the object in that case.
// For now we remove the contents of the array.
this[cache].length = 0;
}
this.jCal[jCalIndex].length = 0;
}
},
/**
* Adds a single sub component.
*
* @param {ICAL.Component} component to add.
*/
addSubcomponent: function(component) {
if (!this._components) {
this._components = [];
}
var idx = this.jCal[COMPONENT_INDEX].push(component.jCal);
this._components[idx - 1] = component;
},
/**
* Removes a single component by name or
* the instance of a specific component.
*
* @param {ICAL.Component|String} nameOrComp comp type.
* @return {Boolean} true when comp is removed.
*/
removeSubcomponent: function(nameOrComp) {
return this._removeObject(COMPONENT_INDEX, '_components', nameOrComp);
},
/**
* Removes all components or (if given) all
* components by a particular name.
*
* @param {String} [name] (lowercase) component name.
*/
removeAllSubcomponents: function(name) {
return this._removeAllObjects(COMPONENT_INDEX, '_components', name);
},
/**
* Adds a property to the component.
*
* @param {ICAL.Property} property object.
*/
addProperty: function(property) {
if (!(property instanceof ICAL.Property)) {
throw new TypeError('must instance of ICAL.Property');
}
var idx = this.jCal[PROPERTY_INDEX].push(property.jCal);
property.component = this;
if (!this._properties) {
this._properties = [];
}
this._properties[idx - 1] = property;
},
/**
* Helper method to add a property with a value to the component.
*
* @param {String} name property name to add.
* @param {Object} value property value.
*/
addPropertyWithValue: function(name, value) {
var prop = new ICAL.Property(name, this);
prop.setValue(value);
this.addProperty(prop, this);
return prop;
},
/**
* Helper method that will update or create a property
* of the given name and sets its value.
*
* @param {String} name property name.
* @param {Object} value property value.
* @return {ICAL.Property} property.
*/
updatePropertyWithValue: function(name, value) {
var prop = this.getFirstProperty(name);
if (prop) {
prop.setValue(value);
} else {
prop = this.addPropertyWithValue(name, value);
}
return prop;
},
/**
* Removes a single property by name or
* the instance of the specific property.
*
* @param {String|ICAL.Property} nameOrProp to remove.
* @return {Boolean} true when deleted.
*/
removeProperty: function(nameOrProp) {
return this._removeObject(PROPERTY_INDEX, '_properties', nameOrProp);
},
/**
* Removes all properties associated with this component.
*
* @param {String} [name] (lowecase) optional property name.
*/
removeAllProperties: function(name) {
return this._removeAllObjects(PROPERTY_INDEX, '_properties', name);
},
toJSON: function() {
return this.jCal;
},
toString: function() {
return ICAL.stringify.component(
this.jCal
);
}
};
return Component;
}());
ICAL.Property = (function() {
'use strict';
var NAME_INDEX = 0;
var PROP_INDEX = 1;
var TYPE_INDEX = 2;
var VALUE_INDEX = 3;
var design = ICAL.design;
/**
* Provides a nicer interface to any kind of property.
* Its important to note that mutations done in the wrapper
* directly effect (mutate) the jCal object used to initialize.
*
* Can also be used to create new properties by passing
* the name of the property (as a String).
*
*
* @param {Array|String} jCal raw jCal representation OR
* the new name of the property (when creating).
*
* @param {ICAL.Component} [component] parent component.
*/
function Property(jCal, component) {
if (typeof(jCal) === 'string') {
// because we a creating by name we need
// to find the type when creating the property.
var name = jCal;
if (name in design.property) {
var prop = design.property[name];
if ('defaultType' in prop) {
var type = prop.defaultType;
} else {
var type = design.defaultType;
}
} else {
var type = design.defaultType;
}
jCal = [name, {}, type];
}
this.jCal = jCal;
this.component = component;
this._updateType();
}
Property.prototype = {
get type() {
return this.jCal[TYPE_INDEX];
},
get name() {
return this.jCal[NAME_INDEX];
},
_updateType: function() {
if (this.type in design.value) {
var designType = design.value[this.type];
if ('decorate' in design.value[this.type]) {
this.isDecorated = true;
} else {
this.isDecorated = false;
}
if (this.name in design.property) {
if ('multiValue' in design.property[this.name]) {
this.isMultiValue = true;
} else {
this.isMultiValue = false;
}
}
}
},
/**
* Hydrate a single value.
*/
_hydrateValue: function(index) {
if (this._values && this._values[index]) {
return this._values[index];
}
// for the case where there is no value.
if (this.jCal.length <= (VALUE_INDEX + index)) {
return null;
}
if (this.isDecorated) {
if (!this._values) {
this._values = [];
}
return this._values[index] = this._decorate(
this.jCal[VALUE_INDEX + index]
);
} else {
return this.jCal[VALUE_INDEX + index];
}
},
_decorate: function(value) {
return design.value[this.type].decorate(value);
},
_undecorate: function(value) {
return design.value[this.type].undecorate(value);
},
_setDecoratedValue: function(value, index) {
if (!this._values) {
this._values = [];
}
if (typeof(value) === 'object' && 'icaltype' in value) {
// decorated value
this.jCal[VALUE_INDEX + index] = this._undecorate(value);
this._values[index] = value;
} else {
// undecorated value
this.jCal[VALUE_INDEX + index] = value;
this._values[index] = this._decorate(value);
}
},
/**
* Gets a param on the property.
*
* @param {String} name prop name (lowercase).
* @return {String} prop value.
*/
getParameter: function(name) {
return this.jCal[PROP_INDEX][name];
},
/**
* Sets a param on the property.
*
* @param {String} value property value.
*/
setParameter: function(name, value) {
this.jCal[PROP_INDEX][name] = value;
},
/**
* Removes a parameter
*
* @param {String} name prop name (lowercase).
*/
removeParameter: function(name) {
return delete this.jCal[PROP_INDEX][name];
},
/**
* Sets type of property and clears out any
* existing values of the current type.
*
* @param {String} type new iCAL type (see design.values).
*/
resetType: function(type) {
this.removeAllValues();
this.jCal[TYPE_INDEX] = type;
this._updateType();
},
/**
* Finds first property value.
*
* @return {String} first property value.
*/
getFirstValue: function() {
return this._hydrateValue(0);
},
/**
* Gets all values on the property.
*
* NOTE: this creates an array during each call.
*
* @return {Array} list of values.
*/
getValues: function() {
var len = this.jCal.length - VALUE_INDEX;
if (len < 1) {
// its possible for a property to have no value.
return;
}
var i = 0;
var result = [];
for (; i < len; i++) {
result[i] = this._hydrateValue(i);
}
return result;
},
removeAllValues: function() {
if (this._values) {
this._values.length = 0;
}
this.jCal.length = 3;
},
/**
* Sets the values of the property.
* Will overwrite the existing values.
*
* @param {Array} values an array of values.
*/
setValues: function(values) {
if (!this.isMultiValue) {
throw new Error(
this.name + ': does not not support mulitValue.\n' +
'override isMultiValue'
);
}
var len = values.length;
var i = 0;
this.removeAllValues();
if (this.isDecorated) {
for (; i < len; i++) {
this._setDecoratedValue(values[i], i);
}
} else {
for (; i < len; i++) {
this.jCal[VALUE_INDEX + i] = values[i];
}
}
},
/**
* Sets the current value of the property.
*
* @param {String|Object} value new prop value.
*/
setValue: function(value) {
if (this.isDecorated) {
this._setDecoratedValue(value, 0);
} else {
this.jCal[VALUE_INDEX] = value;
}
},
/**
* Returns the jCal representation of this property.
*
* @return {Object} jCal.
*/
toJSON: function() {
return this.jCal;
},
toICAL: function() {
return ICAL.stringify.property(
this.jCal
);
}
};
return Property;
}());
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
ICAL.icalvalue = function icalvalue(aData, aParent, aType) {
this.parent = aParent;
this.fromData(aData, aType);
};
ICAL.icalvalue.prototype = {
data: null,
parent: null,
icaltype: null,
fromData: function icalvalue_fromData(aData, aType) {
var type = (aType || (aData && aData.type) || this.icaltype);
this.icaltype = type;
if (aData && type) {
aData.type = type;
}
this.data = aData;
},
fromString: function icalvalue_fromString(aString, aType) {
var type = aType || this.icaltype;
this.fromData(ICAL.DecorationParser.parseValue(aString, type), type);
},
undecorate: function icalvalue_undecorate() {
return this.toString();
},
toString: function() {
return this.data.value.toString();
}
};
ICAL.icalvalue.fromString = function icalvalue_fromString(aString, aType) {
var val = new ICAL.icalvalue();
val.fromString(aString, aType);
return val;
};
ICAL.icalvalue._createFromString = function icalvalue__createFromString(ctor) {
ctor.fromString = function icalvalue_derived_fromString(aStr) {
var val = new ctor();
val.fromString(aStr);
return val;
};
};
ICAL.icalbinary = function icalbinary(aData, aParent) {
ICAL.icalvalue.call(this, aData, aParent, "binary");
};
ICAL.icalbinary.prototype = {
__proto__: ICAL.icalvalue.prototype,
icaltype: "binary",
decodeValue: function decodeValue() {
return this._b64_decode(this.data.value);
},
setEncodedValue: function setEncodedValue(val) {
this.data.value = this._b64_encode(val);
},
_b64_encode: function base64_encode(data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['atob'] == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
},
_b64_decode: function base64_decode(data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec;
}
};
ICAL.icalvalue._createFromString(ICAL.icalbinary);
ICAL.icalutcoffset = function icalutcoffset(aData, aParent) {
ICAL.icalvalue.call(this, aData, aParent, "utc-offset");
};
ICAL.icalutcoffset.prototype = {
__proto__: ICAL.icalvalue.prototype,
hours: null,
minutes: null,
factor: null,
icaltype: "utc-offset",
fromData: function fromData(aData) {
if (aData) {
this.hours = aData.hours;
this.minutes = aData.minutes;
this.factor = aData.factor;
}
},
toString: function toString() {
return (this.factor == 1 ? "+" : "-") +
ICAL.helpers.pad2(this.hours) +
ICAL.helpers.pad2(this.minutes);
}
};
ICAL.icalvalue._createFromString(ICAL.icalutcoffset);
})();
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
ICAL.icalperiod = function icalperiod(aData) {
this.wrappedJSObject = this;
this.fromData(aData);
};
ICAL.icalperiod.prototype = {
start: null,
end: null,
duration: null,
icalclass: "icalperiod",
icaltype: "period",
getDuration: function duration() {
if (this.duration) {
return this.duration;
} else {
return this.end.subtractDate(this.start);
}
},
toString: function toString() {
return this.start + "/" + (this.end || this.duration);
},
fromData: function fromData(data) {
if (data) {
this.start = ("start" in data ? new ICAL.icaltime(data.start) : null);
this.end = ("end" in data ? new ICAL.icaltime(data.end) : null);
this.duration = ("duration" in data ? new ICAL.icalduration(data.duration) : null);
}
}
};
ICAL.icalperiod.fromString = function fromString(str) {
var data = ICAL.DecorationParser.parseValue(str, "period");
return ICAL.icalperiod.fromData(data);
};
ICAL.icalperiod.fromData = function fromData(aData) {
return new ICAL.icalperiod(aData);
};
})();
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
var DURATION_LETTERS = /([PDWHMTS]{1,1})/;
ICAL.icalduration = function icalduration(data) {
this.wrappedJSObject = this;
this.fromData(data);
};
ICAL.icalduration.prototype = {
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
isNegative: false,
icalclass: "icalduration",
icaltype: "duration",
clone: function clone() {
return ICAL.icalduration.fromData(this);
},
toSeconds: function toSeconds() {
var seconds = this.seconds + 60 * this.minutes + 3600 * this.hours +
86400 * this.days + 7 * 86400 * this.weeks;
return (this.isNegative ? -seconds : seconds);
},
fromSeconds: function fromSeconds(aSeconds) {
var secs = Math.abs(aSeconds);
this.isNegative = (aSeconds < 0);
this.days = ICAL.helpers.trunc(secs / 86400);
// If we have a flat number of weeks, use them.
if (this.days % 7 == 0) {
this.weeks = this.days / 7;
this.days = 0;
} else {
this.weeks = 0;
}
secs -= (this.days + 7 * this.weeks) * 86400;
this.hours = ICAL.helpers.trunc(secs / 3600);
secs -= this.hours * 3600;
this.minutes = ICAL.helpers.trunc(secs / 60);
secs -= this.minutes * 60;
this.seconds = secs;
return this;
},
fromData: function fromData(aData) {
var propsToCopy = ["weeks", "days", "hours",
"minutes", "seconds", "isNegative"];
for (var key in propsToCopy) {
var prop = propsToCopy[key];
if (aData && prop in aData) {
this[prop] = aData[prop];
} else {
this[prop] = 0;
}
}
if (aData && "factor" in aData) {
this.isNegative = (aData.factor == "-1");
}
},
reset: function reset() {
this.isNegative = false;
this.weeks = 0;
this.days = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
},
compare: function compare(aOther) {
var thisSeconds = this.toSeconds();
var otherSeconds = aOther.toSeconds();
return (thisSeconds > otherSeconds) - (thisSeconds < otherSeconds);
},
normalize: function normalize() {
this.fromSeconds(this.toSeconds());
return this;
},
toString: function toString() {
if (this.toSeconds() == 0) {
return "PT0S";
} else {
var str = "";
if (this.isNegative) str += "-";
str += "P";
if (this.weeks) str += this.weeks + "W";
if (this.days) str += this.days + "D";
if (this.hours || this.minutes || this.seconds) {
str += "T";
if (this.hours) str += this.hours + "H";
if (this.minutes) str += this.minutes + "M";
if (this.seconds) str += this.seconds + "S";
}
return str;
}
}
};
ICAL.icalduration.fromSeconds = function icalduration_from_seconds(aSeconds) {
return (new ICAL.icalduration()).fromSeconds();
};
/**
* Internal helper function to handle a chunk of a duration.
*
* @param {String} letter type of duration chunk.
* @param {String} number numeric value or -/+.
* @param {Object} dict target to assign values to.
*/
function parseDurationChunk(letter, number, object) {
var type;
switch (letter) {
case 'P':
if (number && number === '-') {
object.isNegative = true;
} else {
object.isNegative = false;
}
// period
break;
case 'D':
type = 'days';
break;
case 'W':
type = 'weeks';
break;
case 'H':
type = 'hours';
break;
case 'M':
type = 'minutes';
break;
case 'S':
type = 'seconds';
break;
}
if (type) {
object[type] = parseInt(number);
}
}
ICAL.icalduration.fromString = function icalduration_from_string(aStr) {
var pos = 0;
var dict = Object.create(null);
while ((pos = aStr.search(DURATION_LETTERS)) !== -1) {
var type = aStr[pos];
var numeric = aStr.substr(0, pos);
aStr = aStr.substr(pos + 1);
parseDurationChunk(type, numeric, dict);
}
return new ICAL.icalduration(dict);
};
ICAL.icalduration.fromData = function icalduration_from_data(aData) {
return new ICAL.icalduration(aData);
};
})();
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
ICAL.icaltimezone = function icaltimezone(data) {
this.wrappedJSObject = this;
this.fromData(data);
};
ICAL.icaltimezone.prototype = {
tzid: "",
location: "",
tznames: "",
latitude: 0.0,
longitude: 0.0,
component: null,
expand_end_year: 0,
expand_start_year: 0,
changes: null,
icalclass: "icaltimezone",
fromData: function fromData(aData) {
var propsToCopy = ["tzid", "location", "tznames",
"latitude", "longitude"];
for (var key in propsToCopy) {
var prop = propsToCopy[key];
if (aData && prop in aData) {
this[prop] = aData[prop];
} else {
this[prop] = 0;
}
}
this.expand_end_year = 0;
this.expand_start_year = 0;
if (aData && "component" in aData) {
if (typeof aData.component == "string") {
this.component = this.componentFromString(aData.component);
} else {
this.component = ICAL.helpers.clone(aData.component, true);
}
} else {
this.component = null;
}
return this;
},
componentFromString: function componentFromString(str) {
this.component = ICAL.toJSON(str, true);
return this.component;
},
utc_offset: function utc_offset(tt) {
if (this == ICAL.icaltimezone.utc_timezone || this == ICAL.icaltimezone.local_timezone) {
return 0;
}
this.ensure_coverage(tt.year);
if (!this.changes || this.changes.length == 0) {
return 0;
}
var tt_change = {
year: tt.year,
month: tt.month,
day: tt.day,
hour: tt.hour,
minute: tt.minute,
second: tt.second
};
var change_num = this.find_nearby_change(tt_change);
var change_num_to_use = -1;
var step = 1;
for (;;) {
var change = ICAL.helpers.clone(this.changes[change_num], true);
if (change.utc_offset < change.prev_utc_offset) {
ICAL.helpers.dumpn("Adjusting " + change.utc_offset);
ICAL.icaltimezone.adjust_change(change, 0, 0, 0, change.utc_offset);
} else {
ICAL.helpers.dumpn("Adjusting prev " + change.prev_utc_offset);
ICAL.icaltimezone.adjust_change(change, 0, 0, 0,
change.prev_utc_offset);
}
var cmp = ICAL.icaltimezone._compare_change_fn(tt_change, change);
ICAL.helpers.dumpn("Compare" + cmp + " / " + change.toString());
if (cmp >= 0) {
change_num_to_use = change_num;
} else {
step = -1;
}
if (step == -1 && change_num_to_use != -1) {
break;
}
change_num += step;
if (change_num < 0) {
return 0;
}
if (change_num >= this.changes.length) {
break;
}
}
var zone_change = this.changes[change_num_to_use];
var utc_offset_change = zone_change.utc_offset - zone_change.prev_utc_offset;
if (utc_offset_change < 0 && change_num_to_use > 0) {
var tmp_change = ICAL.helpers.clone(zone_change, true);
ICAL.icaltimezone.adjust_change(tmp_change, 0, 0, 0,
tmp_change.prev_utc_offset);
if (ICAL.icaltimezone._compare_change_fn(tt_change, tmp_change) < 0) {
var prev_zone_change = this.changes[change_num_to_use - 1];
var want_daylight = false; // TODO
if (zone_change.is_daylight != want_daylight &&
prev_zone_change.is_daylight == want_daylight) {
zone_change = prev_zone_change;
}
}
}
// TODO return is_daylight?
return zone_change.utc_offset;
},
find_nearby_change: function icaltimezone_find_nearby_change(change) {
var lower = 0,
middle = 0;
var upper = this.changes.length;
while (lower < upper) {
middle = ICAL.helpers.trunc(lower + upper / 2);
var zone_change = this.changes[middle];
var cmp = ICAL.icaltimezone._compare_change_fn(change, zone_change);
if (cmp == 0) {
break;
} else if (cmp > 0) {
upper = middle;
} else {
lower = middle;
}
}
return middle;
},
ensure_coverage: function ensure_coverage(aYear) {
if (ICAL.icaltimezone._minimum_expansion_year == -1) {
var today = ICAL.icaltime.now();
ICAL.icaltimezone._minimum_expansion_year = today.year;
}
var changes_end_year = aYear;
if (changes_end_year < ICAL.icaltimezone._minimum_expansion_year) {
changes_end_year = ICAL.icaltimezone._minimum_expansion_year;
}
changes_end_year += ICAL.icaltimezone.EXTRA_COVERAGE;
if (changes_end_year > ICAL.icaltimezone.MAX_YEAR) {
changes_end_year = ICAL.icaltimezone.MAX_YEAR;
}
if (!this.changes || this.expand_end_year < aYear) {
this.expand_changes(changes_end_year);
}
},
expand_changes: function expand_changes(aYear) {
var changes = [];
if (this.component) {
// HACK checking for component only needed for floating
// tz, which is not in core libical.
var subcomps = this.component.getAllSubcomponents();
for (var compkey in subcomps) {
this.expand_vtimezone(subcomps[compkey], aYear, changes);
}
this.changes = changes.concat(this.changes || []);
this.changes.sort(ICAL.icaltimezone._compare_change_fn);
}
this.change_end_year = aYear;
},
expand_vtimezone: function expand_vtimezone(aComponent, aYear, changes) {
if (!aComponent.hasProperty("DTSTART") ||
!aComponent.hasProperty("TZOFFSETTO") ||
!aComponent.hasProperty("TZOFFSETFROM")) {
return null;
}
var dtstart = aComponent.getFirstProperty("DTSTART").getFirstValue();
function convert_tzoffset(offset) {
return offset.factor * (offset.hours * 3600 + offset.minutes * 60);
}
function init_changes() {
var changebase = {};
changebase.is_daylight = (aComponent.name == "DAYLIGHT");
changebase.utc_offset = convert_tzoffset(aComponent.getFirstProperty("TZOFFSETTO").data);
changebase.prev_utc_offset = convert_tzoffset(aComponent.getFirstProperty("TZOFFSETFROM").data);
return changebase;
}
if (!aComponent.hasProperty("RRULE") && !aComponent.hasProperty("RDATE")) {
var change = init_changes();
change.year = dtstart.year;
change.month = dtstart.month;
change.day = dtstart.day;
change.hour = dtstart.hour;
change.minute = dtstart.minute;
change.second = dtstart.second;
ICAL.icaltimezone.adjust_change(change, 0, 0, 0,
-change.prev_utc_offset);
changes.push(change);
} else {
var props = aComponent.getAllProperties("RDATE");
for (var rdatekey in props) {
var rdate = props[rdatekey];
var change = init_changes();
change.year = rdate.time.year;
change.month = rdate.time.month;
change.day = rdate.time.day;
if (rdate.time.isDate) {
change.hour = dtstart.hour;
change.minute = dtstart.minute;
change.second = dtstart.second;
} else {
change.hour = rdate.time.hour;
change.minute = rdate.time.minute;
change.second = rdate.time.second;
if (rdate.time.zone == ICAL.icaltimezone.utc_timezone) {
ICAL.icaltimezone.adjust_change(change, 0, 0, 0,
-change.prev_utc_offset);
}
}
changes.push(change);
}
var rrule = aComponent.getFirstProperty("RRULE").getFirstValue();
// TODO multiple rrules?
var change = init_changes();
if (rrule.until && rrule.until.zone == ICAL.icaltimezone.utc_timezone) {
rrule.until.adjust(0, 0, 0, change.prev_utc_offset);
rrule.until.zone = ICAL.icaltimezone.local_timezone;
}
var iterator = rrule.iterator(dtstart);
var occ;
while ((occ = iterator.next())) {
var change = init_changes();
if (occ.year > aYear || !occ) {
break;
}
change.year = occ.year;
change.month = occ.month;
change.day = occ.day;
change.hour = occ.hour;
change.minute = occ.minute;
change.second = occ.second;
change.isDate = occ.isDate;
ICAL.icaltimezone.adjust_change(change, 0, 0, 0,
-change.prev_utc_offset);
changes.push(change);
}
}
return changes;
},
toString: function toString() {
return (this.tznames ? this.tznames : this.tzid);
}
};
ICAL.icaltimezone._compare_change_fn = function icaltimezone_compare_change_fn(a, b) {
if (a.year < b.year) return -1;
else if (a.year > b.year) return 1;
if (a.month < b.month) return -1;
else if (a.month > b.month) return 1;
if (a.day < b.day) return -1;
else if (a.day > b.day) return 1;
if (a.hour < b.hour) return -1;
else if (a.hour > b.hour) return 1;
if (a.minute < b.minute) return -1;
else if (a.minute > b.minute) return 1;
if (a.second < b.second) return -1;
else if (a.second > b.second) return 1;
return 0;
};
ICAL.icaltimezone.convert_time = function icaltimezone_convert_time(tt, from_zone, to_zone) {
if (tt.isDate ||
from_zone.tzid == to_zone.tzid ||
from_zone == ICAL.icaltimezone.local_timezone ||
to_zone == ICAL.icaltimezone.local_timezone) {
tt.zone = to_zone;
return tt;
}
var utc_offset = from_zone.utc_offset(tt);
tt.adjust(0, 0, 0, - utc_offset);
utc_offset = to_zone.utc_offset(tt);
tt.adjust(0, 0, 0, utc_offset);
return null;
};
ICAL.icaltimezone.fromData = function icaltimezone_fromData(aData) {
var tt = new ICAL.icaltimezone();
return tt.fromData(aData);
};
ICAL.icaltimezone.utc_timezone = ICAL.icaltimezone.fromData({
tzid: "UTC"
});
ICAL.icaltimezone.local_timezone = ICAL.icaltimezone.fromData({
tzid: "floating"
});
ICAL.icaltimezone.adjust_change = function icaltimezone_adjust_change(change, days, hours, minutes, seconds) {
return ICAL.icaltime.prototype.adjust.call(change, days, hours, minutes, seconds);
};
ICAL.icaltimezone._minimum_expansion_year = -1;
ICAL.icaltimezone.MAX_YEAR = 2035; // TODO this is because of time_t, which we don't need. Still usefull?
ICAL.icaltimezone.EXTRA_COVERAGE = 5;
})();
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
ICAL.icaltime = function icaltime(data) {
this.wrappedJSObject = this;
this.fromData(data);
};
ICAL.icaltime.prototype = {
year: 0,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
isDate: false,
zone: null,
auto_normalize: false,
icalclass: "icaltime",
icaltype: "date-time",
clone: function icaltime_clone() {
return new ICAL.icaltime(this);
},
reset: function icaltime_reset() {
this.fromData(ICAL.icaltime.epoch_time);
this.zone = ICAL.icaltimezone.utc_timezone;
},
resetTo: function icaltime_resetTo(year, month, day,
hour, minute, second, timezone) {
this.fromData({
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
zone: timezone
});
},
fromString: function icaltime_fromString(str) {
var data;
try {
data = ICAL.DecorationParser.parseValue(str, "date");
data.isDate = true;
} catch (e) {
data = ICAL.DecorationParser.parseValue(str, "date-time");
data.isDate = false;
}
return this.fromData(data);
},
fromJSDate: function icaltime_fromJSDate(aDate, useUTC) {
if (!aDate) {
this.reset();
} else {
if (useUTC) {
this.zone = ICAL.icaltimezone.utc_timezone;
this.year = aDate.getUTCFullYear();
this.month = aDate.getUTCMonth() + 1;
this.day = aDate.getUTCDate();
this.hour = aDate.getUTCHours();
this.minute = aDate.getUTCMinutes();
this.second = aDate.getUTCSeconds();
} else {
this.zone = ICAL.icaltimezone.local_timezone;
this.year = aDate.getFullYear();
this.month = aDate.getMonth() + 1;
this.day = aDate.getDate();
this.hour = aDate.getHours();
this.minute = aDate.getMinutes();
this.second = aDate.getSeconds();
}
}
return this;
},
fromData: function fromData(aData) {
// TODO given we're switching formats, this may not be needed
var old_auto_normalize = this.auto_normalize;
this.auto_normalize = false;
var propsToCopy = {
year: 0,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0
};
for (var key in propsToCopy) {
if (aData && key in aData) {
this[key] = aData[key];
} else {
this[key] = propsToCopy[key];
}
}
if (aData && !("isDate" in aData)) {
this.isDate = !("hour" in aData);
} else if (aData && ("isDate" in aData)) {
this.isDate = aData.isDate;
}
if (aData && "timezone" in aData) {
var timezone = aData.timezone;
//TODO: replace with timezone service
switch (timezone) {
case 'Z':
case ICAL.icaltimezone.utc_timezone.tzid:
this.zone = ICAL.icaltimezone.utc_timezone;
break;
case ICAL.icaltimezone.local_timezone.tzid:
this.zone = ICAL.icaltimezone.local_timezone;
break;
}
}
if (aData && "zone" in aData) {
this.zone = aData.zone;
}
if (!this.zone) {
this.zone = ICAL.icaltimezone.local_timezone;
}
if (aData && "auto_normalize" in aData) {
this.auto_normalize = aData.auto_normalize;
} else {
this.auto_normalize = old_auto_normalize;
}
if (this.auto_normalize) {
this.normalize();
}
return this;
},
dayOfWeek: function icaltime_dayOfWeek() {
// Using Zeller's algorithm
var q = this.day;
var m = this.month + (this.month < 3 ? 12 : 0);
var Y = this.year - (this.month < 3 ? 1 : 0);
var h = (q + Y + ICAL.helpers.trunc(((m + 1) * 26) / 10) + ICAL.helpers.trunc(Y / 4));
if (true /* gregorian */) {
h += ICAL.helpers.trunc(Y / 100) * 6 + ICAL.helpers.trunc(Y / 400);
} else {
h += 5;
}
// Normalize to 1 = sunday
h = ((h + 6) % 7) + 1;
return h;
},
dayOfYear: function icaltime_dayOfYear() {
var is_leap = (ICAL.icaltime.is_leap_year(this.year) ? 1 : 0);
var diypm = ICAL.icaltime._days_in_year_passed_month;
return diypm[is_leap][this.month - 1] + this.day;
},
startOfWeek: function startOfWeek() {
var result = this.clone();
result.day -= this.dayOfWeek() - 1;
return result.normalize();
},
end_of_week: function end_of_week() {
var result = this.clone();
result.day += 7 - this.dayOfWeek();
return result.normalize();
},
start_of_month: function start_of_month() {
var result = this.clone();
result.day = 1;
result.isDate = true;
result.hour = 0;
result.minute = 0;
result.second = 0;
return result;
},
end_of_month: function end_of_month() {
var result = this.clone();
result.day = ICAL.icaltime.daysInMonth(result.month, result.year);
result.isDate = true;
result.hour = 0;
result.minute = 0;
result.second = 0;
return result;
},
start_of_year: function start_of_year() {
var result = this.clone();
result.day = 1;
result.month = 1;
result.isDate = true;
result.hour = 0;
result.minute = 0;
result.second = 0;
return result;
},
end_of_year: function end_of_year() {
var result = this.clone();
result.day = 31;
result.month = 12;
result.isDate = true;
result.hour = 0;
result.minute = 0;
result.second = 0;
return result;
},
start_doy_week: function start_doy_week(aFirstDayOfWeek) {
var firstDow = aFirstDayOfWeek || ICAL.icaltime.SUNDAY;
var delta = this.dayOfWeek() - firstDow;
if (delta < 0) delta += 7;
return this.dayOfYear() - delta;
},
/**
* Finds the nthWeekDay relative to the current month (not day).
* The returned value is a day relative the month that this
* month belongs to so 1 would indicate the first of the month
* and 40 would indicate a day in the following month.
*
* @param {Numeric} aDayOfWeek day of the week see the day name constants.
* @param {Numeric} aPos nth occurrence of a given week day
* values of 1 and 0 both indicate the first
* weekday of that type. aPos may be either positive
* or negative.
*
* @return {Numeric} numeric value indicating a day relative
* to the current month of this time object.
*/
nthWeekDay: function icaltime_nthWeekDay(aDayOfWeek, aPos) {
var daysInMonth = ICAL.icaltime.daysInMonth(this.month, this.year);
var weekday;
var pos = aPos;
var start = 0;
var otherDay = this.clone();
if (pos >= 0) {
otherDay.day = 1;
// because 0 means no position has been given
// 1 and 0 indicate the same day.
if (pos != 0) {
// remove the extra numeric value
pos--;
}
// set current start offset to current day.
start = otherDay.day;
// find the current day of week
var startDow = otherDay.dayOfWeek();
// calculate the difference between current
// day of the week and desired day of the week
var offset = aDayOfWeek - startDow;
// if the offset goes into the past
// week we add 7 so its goes into the next
// week. We only want to go forward in time here.
if (offset < 0)
// this is really important otherwise we would
// end up with dates from in the past.
offset += 7;
// add offset to start so start is the same
// day of the week as the desired day of week.
start += offset;
// because we are going to add (and multiply)
// the numeric value of the day we subtract it
// from the start position so not to add it twice.
start -= aDayOfWeek;
// set week day
weekday = aDayOfWeek;
} else {
// then we set it to the last day in the current month
otherDay.day = daysInMonth;
// find the ends weekday
var endDow = otherDay.dayOfWeek();
pos++;
weekday = (endDow - aDayOfWeek);
if (weekday < 0) {
weekday += 7;
}
weekday = daysInMonth - weekday;
}
weekday += pos * 7;
return start + weekday;
},
/**
* Checks if current time is the nthWeekDay.
* Relative to the current month.
*
* Will always return false when rule resolves
* outside of current month.
*
* @param {Numeric} aDayOfWeek day of week.
* @param {Numeric} aPos position.
* @param {Numeric} aMax maximum valid day.
*/
isNthWeekDay: function(aDayOfWeek, aPos) {
var dow = this.dayOfWeek();
if (aPos === 0 && dow === aDayOfWeek) {
return true;
}
// get pos
var day = this.nthWeekDay(aDayOfWeek, aPos);
if (day === this.day) {
return true;
}
return false;
},
week_number: function week_number(aWeekStart) {
// This function courtesty of Julian Bucknall, published under the MIT license
// http://www.boyet.com/articles/publishedarticles/calculatingtheisoweeknumb.html
var doy = this.dayOfYear();
var dow = this.dayOfWeek();
var year = this.year;
var week1;
var dt = this.clone();
dt.isDate = true;
var first_dow = dt.dayOfWeek();
var isoyear = this.year;
if (dt.month == 12 && dt.day > 28) {
week1 = ICAL.icaltime.week_one_starts(isoyear + 1, aWeekStart);
if (dt.compare(week1) < 0) {
week1 = ICAL.icaltime.week_one_starts(isoyear, aWeekStart);
} else {
isoyear++;
}
} else {
week1 = ICAL.icaltime.week_one_starts(isoyear, aWeekStart);
if (dt.compare(week1) < 0) {
week1 = ICAL.icaltime.week_one_starts(--isoyear, aWeekStart);
}
}
var daysBetween = (dt.subtractDate(week1).toSeconds() / 86400);
return ICAL.helpers.trunc(daysBetween / 7) + 1;
},
addDuration: function icaltime_add(aDuration) {
var mult = (aDuration.isNegative ? -1 : 1);
this.second += mult * aDuration.seconds;
this.minute += mult * aDuration.minutes;
this.hour += mult * aDuration.hours;
this.day += mult * aDuration.days;
this.day += mult * 7 * aDuration.weeks;
this.normalize();
},
subtractDate: function icaltime_subtract(aDate) {
function leap_years_until(aYear) {
return ICAL.helpers.trunc(aYear / 4) -
ICAL.helpers.trunc(aYear / 100) +
ICAL.helpers.trunc(aYear / 400);
}
function leap_years_between(aStart, aEnd) {
if (aStart >= aEnd) {
return 0;
} else {
return leap_years_until(aEnd - 1) - leap_years_until(aStart);
}
}
var dur = new ICAL.icalduration();
dur.seconds = this.second - aDate.second;
dur.minutes = this.minute - aDate.minute;
dur.hours = this.hour - aDate.hour;
if (this.year == aDate.year) {
var this_doy = this.dayOfYear();
var that_doy = aDate.dayOfYear();
dur.days = this_doy - that_doy;
} else if (this.year < aDate.year) {
var days_left_thisyear = 365 +
(ICAL.icaltime.is_leap_year(this.year) ? 1 : 0) -
this.dayOfYear();
dur.days -= days_left_thisyear + aDate.dayOfYear();
dur.days -= leap_years_between(this.year + 1, aDate.year);
dur.days -= 365 * (aDate.year - this.year - 1);
} else {
var days_left_thatyear = 365 +
(ICAL.icaltime.is_leap_year(aDate.year) ? 1 : 0) -
aDate.dayOfYear();
dur.days += days_left_thatyear + this.dayOfYear();
dur.days += leap_years_between(aDate.year + 1, this.year);
dur.days += 365 * (this.year - aDate.year - 1);
}
return dur.normalize();
},
compare: function icaltime_compare(other) {
function cmp(attr) {
return ICAL.icaltime._cmp_attr(a, b, attr);
}
if (!other) return 0;
if (this.isDate || other.isDate) {
return this.compare_date_only_tz(other, this.zone);
}
var target_zone;
if (this.zone == ICAL.icaltimezone.local_timezone ||
other.zone == ICAL.icaltimezone.local_timezone) {
target_zone = ICAL.icaltimezone.local_timezone;
} else {
target_zone = ICAL.icaltimezone.utc_timezone;
}
var a = this.convert_to_zone(target_zone);
var b = other.convert_to_zone(target_zone);
var rc = 0;
if ((rc = cmp("year")) != 0) return rc;
if ((rc = cmp("month")) != 0) return rc;
if ((rc = cmp("day")) != 0) return rc;
if (a.isDate && b.isDate) {
// If both are dates, we are done
return 0;
} else if (b.isDate) {
// If b is a date, then a is greater
return 1;
} else if (a.isDate) {
// If a is a date, then b is greater
return -1;
}
if ((rc = cmp("hour")) != 0) return rc;
if ((rc = cmp("minute")) != 0) return rc;
if ((rc = cmp("second")) != 0) return rc;
// Now rc is 0 and the dates are equal
return rc;
},
compare_date_only_tz: function icaltime_compare_date_only_tz(other, tz) {
function cmp(attr) {
return ICAL.icaltime._cmp_attr(a, b, attr);
}
var a = this.convert_to_zone(tz);
var b = other.convert_to_zone(tz);
var rc = 0;
if ((rc = cmp("year")) != 0) return rc;
if ((rc = cmp("month")) != 0) return rc;
if ((rc = cmp("day")) != 0) return rc;
return rc;
},
convert_to_zone: function convert_to_zone(zone) {
var copy = this.clone();
var zone_equals = (this.zone.tzid == zone.tzid);
if (!this.isDate && !zone_equals) {
ICAL.icaltimezone.convert_time(copy, this.zone, zone);
}
copy.zone = zone;
return copy;
},
utc_offset: function utc_offset() {
if (this.zone == ICAL.icaltimezone.local_timezone ||
this.zone == ICAL.icaltimezone.utc_timezone) {
return 0;
} else {
return this.zone.utc_offset(this);
}
},
toString: function toString() {
return ("0000" + this.year).substr(-4) +
("00" + this.month).substr(-2) +
("00" + this.day).substr(-2) +
(this.isDate ? "" :
"T" +
("00" + this.hour).substr(-2) +
("00" + this.minute).substr(-2) +
("00" + this.second).substr(-2) +
(this.zone && this.zone.tzid == "UTC" ? "Z" : "")
);
},
toJSDate: function toJSDate() {
if (this.zone == ICAL.icaltimezone.local_timezone) {
if (this.isDate) {
return new Date(this.year, this.month - 1, this.day);
} else {
return new Date(this.year, this.month - 1, this.day,
this.hour, this.minute, this.second, 0);
}
} else {
var utcDate = this.convert_to_zone(ICAL.icaltimezone.utc_timezone);
if (this.isDate) {
return Date.UTC(this.year, this.month - 1, this.day);
} else {
return Date.UTC(this.year, this.month - 1, this.day,
this.hour, this.minute, this.second, 0);
}
}
},
normalize: function icaltime_normalize() {
if (this.isDate) {
this.hour = 0;
this.minute = 0;
this.second = 0;
}
this.icaltype = (this.isDate ? "date" : "date-time");
this.adjust(0, 0, 0, 0);
return this;
},
adjust: function icaltime_adjust(aExtraDays, aExtraHours,
aExtraMinutes, aExtraSeconds) {
var second, minute, hour, day;
var minutes_overflow, hours_overflow, days_overflow = 0,
years_overflow = 0;
var daysInMonth;
if (!this.isDate) {
second = this.second + aExtraSeconds;
this.second = second % 60;
minutes_overflow = ICAL.helpers.trunc(second / 60);
if (this.second < 0) {
this.second += 60;
minutes_overflow--;
}
minute = this.minute + aExtraMinutes + minutes_overflow;
this.minute = minute % 60;
hours_overflow = ICAL.helpers.trunc(minute / 60);
if (this.minute < 0) {
this.minute += 60;
hours_overflow--;
}
hour = this.hour + aExtraHours + hours_overflow;
this.hour = hour % 24;
days_overflow = ICAL.helpers.trunc(hour / 24);
if (this.hour < 0) {
this.hour += 24;
days_overflow--;
}
}
// Adjust month and year first, because we need to know what month the day
// is in before adjusting it.
if (this.month > 12) {
years_overflow = ICAL.helpers.trunc((this.month - 1) / 12);
} else if (this.month < 1) {
years_overflow = ICAL.helpers.trunc(this.month / 12) - 1;
}
this.year += years_overflow;
this.month -= 12 * years_overflow;
// Now take care of the days (and adjust month if needed)
day = this.day + aExtraDays + days_overflow;
if (day > 0) {
for (;;) {
var daysInMonth = ICAL.icaltime.daysInMonth(this.month, this.year);
if (day <= daysInMonth) {
break;
}
this.month++;
if (this.month > 12) {
this.year++;
this.month = 1;
}
day -= daysInMonth;
}
} else {
while (day <= 0) {
if (this.month == 1) {
this.year--;
this.month = 12;
} else {
this.month--;
}
day += ICAL.icaltime.daysInMonth(this.month, this.year);
}
}
this.day = day;
return this;
},
fromUnixTime: function fromUnixTime(seconds) {
var epoch = ICAL.icaltime.epoch_time.clone();
epoch.adjust(0, 0, 0, seconds);
this.fromData(epoch);
this.zone = ICAL.icaltimezone.utc_timezone;
},
toUnixTime: function toUnixTime() {
var dur = this.subtractDate(ICAL.icaltime.epoch_time);
return dur.toSeconds();
},
/**
* Converts time to into Object
* which can be serialized then re-created
* using the constructor.
*
* Example:
*
* // toJSON will automatically be called
* var json = JSON.stringify(mytime);
*
* var deserialized = JSON.parse(json);
*
* var time = new ICAL.icaltime(deserialized);
*
*/
toJSON: function() {
var copy = [
'year',
'month',
'day',
'hour',
'minute',
'second',
'isDate'
];
var result = Object.create(null);
var i = 0;
var len = copy.length;
var prop;
for (; i < len; i++) {
prop = copy[i];
result[prop] = this[prop];
}
if (this.zone) {
result.timezone = this.zone.tzid;
}
return result;
}
};
(function setupNormalizeAttributes() {
// This needs to run before any instances are created!
function addAutoNormalizeAttribute(attr, mattr) {
ICAL.icaltime.prototype[mattr] = ICAL.icaltime.prototype[attr];
Object.defineProperty(ICAL.icaltime.prototype, attr, {
get: function() {
return this[mattr];
},
set: function(val) {
this[mattr] = val;
if (this.auto_normalize) {
var old_normalize = this.auto_normalize;
this.auto_normalize = false;
this.normalize();
this.auto_normalize = old_normalize;
}
return val;
}
});
}
if ("defineProperty" in Object) {
addAutoNormalizeAttribute("year", "mYear");
addAutoNormalizeAttribute("month", "mMonth");
addAutoNormalizeAttribute("day", "mDay");
addAutoNormalizeAttribute("hour", "mHour");
addAutoNormalizeAttribute("minute", "mMinute");
addAutoNormalizeAttribute("second", "mSecond");
addAutoNormalizeAttribute("isDate", "mIsDate");
ICAL.icaltime.prototype.auto_normalize = true;
}
})();
ICAL.icaltime.daysInMonth = function icaltime_daysInMonth(month, year) {
var _daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var days = 30;
if (month < 1 || month > 12) return days;
days = _daysInMonth[month];
if (month == 2) {
days += ICAL.icaltime.is_leap_year(year);
}
return days;
};
ICAL.icaltime.is_leap_year = function icaltime_is_leap_year(year) {
if (year <= 1752) {
return ((year % 4) == 0);
} else {
return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
};
ICAL.icaltime.fromDayOfYear = function icaltime_fromDayOfYear(aDayOfYear, aYear) {
var year = aYear;
var doy = aDayOfYear;
var tt = new ICAL.icaltime();
tt.auto_normalize = false;
var is_leap = (ICAL.icaltime.is_leap_year(year) ? 1 : 0);
if (doy < 1) {
year--;
is_leap = (ICAL.icaltime.is_leap_year(year) ? 1 : 0);
doy += ICAL.icaltime._days_in_year_passed_month[is_leap][12];
} else if (doy > ICAL.icaltime._days_in_year_passed_month[is_leap][12]) {
is_leap = (ICAL.icaltime.is_leap_year(year) ? 1 : 0);
doy -= ICAL.icaltime._days_in_year_passed_month[is_leap][12];
year++;
}
tt.year = year;
tt.isDate = true;
for (var month = 11; month >= 0; month--) {
if (doy > ICAL.icaltime._days_in_year_passed_month[is_leap][month]) {
tt.month = month + 1;
tt.day = doy - ICAL.icaltime._days_in_year_passed_month[is_leap][month];
break;
}
}
tt.auto_normalize = true;
return tt;
};
ICAL.icaltime.fromStringv2 = function fromString(str) {
return new ICAL.icaltime({
year: parseInt(str.substr(0, 4), 10),
month: parseInt(str.substr(5, 2), 10),
day: parseInt(str.substr(8, 2), 10),
isDate: true
});
};
ICAL.icaltime.fromString = function fromString(str) {
var tt = new ICAL.icaltime();
return tt.fromString(str);
};
ICAL.icaltime.fromJSDate = function fromJSDate(aDate, useUTC) {
var tt = new ICAL.icaltime();
return tt.fromJSDate(aDate, useUTC);
};
ICAL.icaltime.fromData = function fromData(aData) {
var t = new ICAL.icaltime();
return t.fromData(aData);
};
ICAL.icaltime.now = function icaltime_now() {
return ICAL.icaltime.fromJSDate(new Date(), false);
};
ICAL.icaltime.week_one_starts = function week_one_starts(aYear, aWeekStart) {
var t = ICAL.icaltime.fromData({
year: aYear,
month: 1,
day: 4,
isDate: true
});
var fourth_dow = t.dayOfWeek();
t.day += (1 - fourth_dow) + ((aWeekStart || ICAL.icaltime.SUNDAY) - 1);
return t;
};
ICAL.icaltime.epoch_time = ICAL.icaltime.fromData({
year: 1970,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
isDate: false,
timezone: "Z"
});
ICAL.icaltime._cmp_attr = function _cmp_attr(a, b, attr) {
if (a[attr] > b[attr]) return 1;
if (a[attr] < b[attr]) return -1;
return 0;
};
ICAL.icaltime._days_in_year_passed_month = [
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365],
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
];
ICAL.icaltime.SUNDAY = 1;
ICAL.icaltime.MONDAY = 2;
ICAL.icaltime.TUESDAY = 3;
ICAL.icaltime.WEDNESDAY = 4;
ICAL.icaltime.THURSDAY = 5;
ICAL.icaltime.FRIDAY = 6;
ICAL.icaltime.SATURDAY = 7;
ICAL.icaltime.DEFAULT_WEEK_START = ICAL.icaltime.MONDAY;
})();
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Portions Copyright (C) Philipp Kewisch, 2011-2012 */
(typeof(ICAL) === 'undefined')? ICAL = {} : '';
(function() {
var DOW_MAP = {
SU: ICAL.icaltime.SUNDAY,
MO: ICAL.icaltime.MONDAY,
TU: ICAL.icaltime.TUESDAY,
WE: ICAL.icaltime.WEDNESDAY,
TH: ICAL.icaltime.THURSDAY,
FR: ICAL.icaltime.FRIDAY,
SA: ICAL.icaltime.SATURDAY
};
var REVERSE_DOW_MAP = {};
for (var key in DOW_MAP) {
REVERSE_DOW_MAP[DOW_MAP[key]] = key;
}
ICAL.icalrecur = function icalrecur(data) {
this.wrappedJSObject = this;
this.parts = {};
this.fromData(data);
};
ICAL.icalrecur.prototype = {
parts: null,
interval: 1,
wkst: ICAL.icaltime.MONDAY,
until: null,
count: null,
freq: null,
icalclass: "icalrecur",
icaltype: "recur",
iterator: function(aStart) {
return new ICAL.icalrecur_iterator({
rule: this,
dtstart: aStart
});
},
clone: function clone() {
return ICAL.icalrecur.fromData(this);
//return ICAL.icalrecur.fromIcalProperty(this.toIcalProperty());
},
isFinite: function isfinite() {
return !!(this.count || this.until);
},
isByCount: function isbycount() {
return !!(this.count && !this.until);
},
addComponent: function addPart(aType, aValue) {
if (!(aType in this.parts)) {
this.parts[aType] = [aValue];
} else {
this.parts[aType].push(aValue);
}
},
setComponent: function setComponent(aType, aValues) {
this.parts[aType] = aValues;
},
getComponent: function getComponent(aType, aCount) {
var ucName = aType.toUpperCase();
var components = (ucName in this.parts ? this.parts[ucName] : []);
if (aCount) aCount.value = components.length;
return components;
},
getNextOccurrence: function getNextOccurrence(aStartTime, aRecurrenceId) {
ICAL.helpers.dumpn("GNO: " + aRecurrenceId + " / " + aStartTime);
var iter = this.iterator(aStartTime);
var next, cdt;
do {
next = iter.next();
ICAL.helpers.dumpn("Checking " + next + " <= " + aRecurrenceId);
} while (next && next.compare(aRecurrenceId) <= 0);
if (next && aRecurrenceId.zone) {
next.zone = aRecurrenceId.zone;
}
return next;
},
toJSON: function() {
//XXX: extract this list up to proto?
var propsToCopy = [
"freq",
"count",
"until",
"wkst",
"interval",
"parts"
];
var result = Object.create(null);
var i = 0;
var len = propsToCopy.length;
var prop;
for (; i < len; i++) {
var prop = propsToCopy[i];
result[prop] = this[prop];
}
if (result.until instanceof ICAL.icaltime) {
result.until = result.until.toJSON();
}
return result;
},
fromData: function fromData(aData) {
var propsToCopy = ["freq", "count", "until", "wkst", "interval"];
for (var key in propsToCopy) {
var prop = propsToCopy[key];
if (aData && prop.toUpperCase() in aData) {
this[prop] = aData[prop.toUpperCase()];
// TODO casing sucks, fix the parser!
} else if (aData && prop in aData) {
this[prop] = aData[prop];
// TODO casing sucks, fix the parser!
}
}
// wkst is usually in SU, etc.. format we need
// to convert it from the string
if (typeof(this.wkst) === 'string') {
this.wkst = ICAL.icalrecur.icalDayToNumericDay(this.wkst);
}
// Another hack for multiple construction of until value.
if (this.until) {
if (this.until instanceof ICAL.icaltime) {
this.until = this.until.clone();
} else {
this.until = ICAL.icaltime.fromData(this.until);
}
}
var partsToCopy = ["BYSECOND", "BYMINUTE", "BYHOUR", "BYDAY",
"BYMONTHDAY", "BYYEARDAY", "BYWEEKNO",
"BYMONTH", "BYSETPOS"];
this.parts = {};
if (aData) {
for (var key in partsToCopy) {
var prop = partsToCopy[key];
if (prop in aData) {
this.parts[prop] = aData[prop];
// TODO casing sucks, fix the parser!
}
}
// TODO oh god, make it go away!
if (aData.parts) {
for (var key in partsToCopy) {
var prop = partsToCopy[key];
if (prop in aData.parts) {
this.parts[prop] = aData.parts[prop];
// TODO casing sucks, fix the parser!
}
}
}
}
return this;
},
toString: function icalrecur_toString() {
// TODO retain order
var str = "FREQ=" + this.freq;
if (this.count) {
str += ";COUNT=" + this.count;
}
if (this.interval != 1) {
str += ";INTERVAL=" + this.interval;
}
for (var k in this.parts) {
str += ";" + k + "=" + this.parts[k];
}
if (this.until ){
str += ';UNTIL=' + this.until.toString();
}
if ('wkst' in this && this.wkst !== ICAL.icaltime.DEFAULT_WEEK_START) {
str += ';WKST=' + REVERSE_DOW_MAP[this.wkst];
}
return str;
},
toIcalProperty: function toIcalProperty() {
try {
var valueData = {
name: this.isNegative ? "EXRULE" : "RRULE",
type: "RECUR",
value: [this.toString()]
// TODO more props?
};
return ICAL.Property.fromData(valueData);
} catch (e) {
ICAL.helpers.dumpn("EICALPROP: " + this.toString() + "//" + e);
ICAL.helpers.dumpn(e.stack);
return null;
}
return null;
},
fromIcalProperty: function fromIcalProperty(aProp) {
var propval = aProp.getFirstValue();
this.fromData(propval);
this.parts = ICAL.helpers.clone(propval.parts, true);
if (aProp.name == "EXRULE") {
this.isNegative = true;
} else if (aProp.name == "RRULE") {
this.isNegative = false;
} else {
throw new Error("Invalid Property " + aProp.name + " passed");
}
}
};
ICAL.icalrecur.fromData = function icalrecur_fromData(data) {
return (new ICAL.icalrecur(data));
}
ICAL.icalrecur.fromString = function icalrecur_fromString(str) {
var data = ICAL.DecorationParser.parseValue(str, "recur");
return ICAL.icalrecur.fromData(data);
};
ICAL.icalrecur.fromIcalProperty = function icalrecur_fromIcalProperty(prop) {
var recur = new ICAL.icalrecur();
recur.fromIcalProperty(prop);
return recur;
};
/**
* Convert an ical representation of a day (SU, MO, etc..)
* into a numeric value of that day.
*
* @param {String} day ical day.
* @return {Numeric} numeric value of given day.
*/
ICAL.icalrecur.icalDayToNumericDay = function toNumericDay(string) {
//XXX: this is here so we can deal
// with possibly invalid string values.
return DOW_MAP[string];
};
})();
ICAL.icalrecur_iterator = (function() {
/**
* Options:
* - rule: (ICAL.icalrecur) instance
* - dtstart: (ICAL.icaltime) start date of recurrence rule
* - initialized: (Boolean) when true will assume options
* are from previously constructed
* iterator and will not re-initialize
* iterator but resume its state from given data.
*
* - by_data: (for iterator de-serialization)
* - days: "
* - last: "
* - by_indices: "
*/
function icalrecur_iterator(options) {
this.fromData(options);
}
icalrecur_iterator.prototype = {
/**
* True when iteration is finished.
*/
completed: false,
rule: null,
dtstart: null,
last: null,
occurrence_number: 0,
by_indices: null,
initialized: false,
by_data: null,
days: null,
days_index: 0,
fromData: function(options) {
this.rule = ICAL.helpers.formatClassType(options.rule, ICAL.icalrecur);
if (!this.rule) {
throw new Error('iterator requires a (ICAL.icalrecur) rule');
}
this.dtstart = ICAL.helpers.formatClassType(options.dtstart, ICAL.icaltime);
if (!this.dtstart) {
throw new Error('iterator requires a (ICAL.icaltime) dtstart');
}
if (options.by_data) {
this.by_data = options.by_data;
} else {
this.by_data = ICAL.helpers.clone(this.rule.parts, true);
}
if (options.occurrence_number)
this.occurrence_number = options.occurrence_number;
this.days = options.days || [];
this.last = ICAL.helpers.formatClassType(options.last, ICAL.icaltime);
this.by_indices = options.by_indices;
if (!this.by_indices) {
this.by_indices = {
"BYSECOND": 0,
"BYMINUTE": 0,
"BYHOUR": 0,
"BYDAY": 0,
"BYMONTH": 0,
"BYWEEKNO": 0,
"BYMONTHDAY": 0
};
}
this.initialized = options.initialized || false;
if (!this.initialized) {
this.init();
}
},
init: function icalrecur_iterator_init() {
this.initialized = true;
this.last = this.dtstart.clone();
var parts = this.by_data;
if ("BYDAY" in parts) {
// libical does this earlier when the rule is loaded, but we postpone to
// now so we can preserve the original order.
this.sort_byday_rules(parts.BYDAY, this.rule.wkst);
}
// If the BYYEARDAY appares, no other date rule part may appear
if ("BYYEARDAY" in parts) {
if ("BYMONTH" in parts || "BYWEEKNO" in parts ||
"BYMONTHDAY" in parts || "BYDAY" in parts) {
throw new Error("Invalid BYYEARDAY rule");
}
}
// BYWEEKNO and BYMONTHDAY rule parts may not both appear
if ("BYWEEKNO" in parts && "BYMONTHDAY" in parts) {
throw new Error("BYWEEKNO does not fit to BYMONTHDAY");
}
// For MONTHLY recurrences (FREQ=MONTHLY) neither BYYEARDAY nor
// BYWEEKNO may appear.
if (this.rule.freq == "MONTHLY" &&
("BYYEARDAY" in parts || "BYWEEKNO" in parts)) {
throw new Error("For MONTHLY recurrences neither BYYEARDAY nor BYWEEKNO may appear");
}
// For WEEKLY recurrences (FREQ=WEEKLY) neither BYMONTHDAY nor
// BYYEARDAY may appear.
if (this.rule.freq == "WEEKLY" &&
("BYYEARDAY" in parts || "BYMONTHDAY" in parts)) {
throw new Error("For WEEKLY recurrences neither BYMONTHDAY nor BYYEARDAY may appear");
}
// BYYEARDAY may only appear in YEARLY rules
if (this.rule.freq != "YEARLY" && "BYYEARDAY" in parts) {
throw new Error("BYYEARDAY may only appear in YEARLY rules");
}
this.last.second = this.setup_defaults("BYSECOND", "SECONDLY", this.dtstart.second);
this.last.minute = this.setup_defaults("BYMINUTE", "MINUTELY", this.dtstart.minute);
this.last.hour = this.setup_defaults("BYHOUR", "HOURLY", this.dtstart.hour);
this.last.day = this.setup_defaults("BYMONTHDAY", "DAILY", this.dtstart.day);
this.last.month = this.setup_defaults("BYMONTH", "MONTHLY", this.dtstart.month);
if (this.rule.freq == "WEEKLY") {
if ("BYDAY" in parts) {
var parts = this.ruleDayOfWeek(parts.BYDAY[0]);
var pos = parts[0];
var rule_dow = parts[1];
var dow = rule_dow - this.last.dayOfWeek();
if ((this.last.dayOfWeek() < rule_dow && dow >= 0) || dow < 0) {
// Initial time is after first day of BYDAY data
this.last.day += dow;
this.last.normalize();
}
} else {
var wkMap = icalrecur_iterator._wkdayMap[this.dtstart.dayOfWeek()];
parts.BYDAY = [wkMap];
}
}
if (this.rule.freq == "YEARLY") {
for (;;) {
this.expand_year_days(this.last.year);
if (this.days.length > 0) {
break;
}
this.increment_year(this.rule.interval);
}
var next = ICAL.icaltime.fromDayOfYear(this.days[0], this.last.year);
this.last.day = next.day;
this.last.month = next.month;
}
if (this.rule.freq == "MONTHLY" && this.has_by_data("BYDAY")) {
var coded_day = this.by_data.BYDAY[this.by_indices.BYDAY];
var parts = this.ruleDayOfWeek(coded_day);
var pos = parts[0];
var dow = parts[1];
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
var poscount = 0;
if (pos >= 0) {
for (this.last.day = 1; this.last.day <= daysInMonth; this.last.day++) {
if (this.last.dayOfWeek() == dow) {
if (++poscount == pos || pos == 0) {
break;
}
}
}
} else {
pos = -pos;
for (this.last.day = daysInMonth; this.last.day != 0; this.last.day--) {
if (this.last.dayOfWeek() == dow) {
if (++poscount == pos) {
break;
}
}
}
}
//XXX: This feels like a hack, but we need to initialize
// the BYMONTHDAY case correctly and byDayAndMonthDay handles
// this case. It accepts a special flag which will avoid incrementing
// the initial value without the flag days that match the start time
// would be missed.
if (this.has_by_data('BYMONTHDAY')) {
this._byDayAndMonthDay(true);
}
if (this.last.day > daysInMonth || this.last.day == 0) {
throw new Error("Malformed values in BYDAY part");
}
} else if (this.has_by_data("BYMONTHDAY")) {
if (this.last.day < 0) {
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
this.last.day = daysInMonth + this.last.day + 1;
}
this.last.normalize();
}
},
next: function icalrecur_iterator_next() {
var before = (this.last ? this.last.clone() : null);
if ((this.rule.count && this.occurrence_number >= this.rule.count) ||
(this.rule.until && this.last.compare(this.rule.until) > 0)) {
//XXX: right now this is just a flag and has no impact
// we can simplify the above case to check for completed later.
this.completed = true;
return null;
}
if (this.occurrence_number == 0 && this.last.compare(this.dtstart) >= 0) {
// First of all, give the instance that was initialized
this.occurrence_number++;
return this.last;
}
do {
var valid = 1;
switch (this.rule.freq) {
case "SECONDLY":
this.next_second();
break;
case "MINUTELY":
this.next_minute();
break;
case "HOURLY":
this.next_hour();
break;
case "DAILY":
this.next_day();
break;
case "WEEKLY":
this.next_week();
break;
case "MONTHLY":
valid = this.next_month();
break;
case "YEARLY":
this.next_year();
break;
default:
return null;
}
} while (!this.check_contracting_rules() ||
this.last.compare(this.dtstart) < 0 ||
!valid);
// TODO is this valid?
if (this.last.compare(before) == 0) {
throw new Error("Same occurrence found twice, protecting " +
"you from death by recursion");
}
if (this.rule.until && this.last.compare(this.rule.until) > 0) {
this.completed = true;
return null;
} else {
this.occurrence_number++;
return this.last;
}
},
next_second: function next_second() {
return this.next_generic("BYSECOND", "SECONDLY", "second", "minute");
},
increment_second: function increment_second(inc) {
return this.increment_generic(inc, "second", 60, "minute");
},
next_minute: function next_minute() {
return this.next_generic("BYMINUTE", "MINUTELY",
"minute", "hour", "next_second");
},
increment_minute: function increment_minute(inc) {
return this.increment_generic(inc, "minute", 60, "hour");
},
next_hour: function next_hour() {
return this.next_generic("BYHOUR", "HOURLY", "hour",
"monthday", "next_minute");
},
increment_hour: function increment_hour(inc) {
this.increment_generic(inc, "hour", 24, "monthday");
},
next_day: function next_day() {
var has_by_day = ("BYDAY" in this.by_data);
var this_freq = (this.rule.freq == "DAILY");
if (this.next_hour() == 0) {
return 0;
}
if (this_freq) {
this.increment_monthday(this.rule.interval);
} else {
this.increment_monthday(1);
}
return 0;
},
next_week: function next_week() {
var end_of_data = 0;
if (this.next_weekday_by_week() == 0) {
return end_of_data;
}
if (this.has_by_data("BYWEEKNO")) {
var idx = ++this.by_indices.BYWEEKNO;
if (this.by_indices.BYWEEKNO == this.by_data.BYWEEKNO.length) {
this.by_indices.BYWEEKNO = 0;
end_of_data = 1;
}
// HACK should be first month of the year
this.last.month = 1;
this.last.day = 1;
var week_no = this.by_data.BYWEEKNO[this.by_indices.BYWEEKNO];
this.last.day += 7 * week_no;
this.last.normalize();
if (end_of_data) {
this.increment_year(1);
}
} else {
// Jump to the next week
this.increment_monthday(7 * this.rule.interval);
}
return end_of_data;
},
/**
* normalize each by day rule for a given year/month.
* Takes into account ordering and negative rules
*
* @param {Numeric} year current year.
* @param {Numeric} month current month.
* @param {Array} rules array of rules.
*
* @return {Array} sorted and normalized rules.
* Negative rules will be expanded to their
* correct positive values for easier processing.
*/
normalizeByMonthDayRules: function(year, month, rules) {
var daysInMonth = ICAL.icaltime.daysInMonth(month, year);
// XXX: This is probably bad for performance to allocate
// a new array for each month we scan, if possible
// we should try to optimize this...
var newRules = [];
var ruleIdx = 0;
var len = rules.length;
var rule;
for (; ruleIdx < len; ruleIdx++) {
rule = rules[ruleIdx];
// if this rule falls outside of given
// month discard it.
if (Math.abs(rule) > daysInMonth) {
continue;
}
// negative case
if (rule < 0) {
// we add (not subtract its a negative number)
// one from the rule because 1 === last day of month
rule = daysInMonth + (rule + 1);
} else if (rule === 0) {
// skip zero its invalid.
continue;
}
// only add unique items...
if (newRules.indexOf(rule) === -1) {
newRules.push(rule);
}
}
// unique and sort
return newRules.sort();
},
/**
* NOTES:
* We are given a list of dates in the month (BYMONTHDAY) (23, etc..)
* Also we are given a list of days (BYDAY) (MO, 2SU, etc..) when
* both conditions match a given date (this.last.day) iteration stops.
*
* @param {Boolean} [isInit] when given true will not
* increment the current day (this.last).
*/
_byDayAndMonthDay: function(isInit) {
var byMonthDay; // setup in initMonth
var byDay = this.by_data.BYDAY;
var date;
var dateIdx = 0;
var dateLen; // setup in initMonth
var dayIdx = 0;
var dayLen = byDay.length;
// we are not valid by default
var dataIsValid = 0;
var daysInMonth;
var self = this;
function initMonth() {
daysInMonth = ICAL.icaltime.daysInMonth(
self.last.month, self.last.year
);
byMonthDay = self.normalizeByMonthDayRules(
self.last.year,
self.last.month,
self.by_data.BYMONTHDAY
);
dateLen = byMonthDay.length;
}
function nextMonth() {
self.last.day = 1;
self.increment_month();
initMonth();
dateIdx = 0;
dayIdx = 0;
}
initMonth();
// should come after initMonth
if (isInit) {
this.last.day -= 1;
}
while (!dataIsValid) {
// find next date
var next = byMonthDay[dateIdx++];
// increment the current date. This is really
// important otherwise we may fall into the infinite
// loop trap. The initial date takes care of the case
// where the current date is the date we are looking
// for.
date = this.last.day + 1;
if (date > daysInMonth) {
nextMonth();
continue;
}
// after verify that the next date
// is in the current month we can increment
// it permanently.
this.last.day = date;
// this logic is dependant on the BYMONTHDAYS
// being in order (which is done by #normalizeByMonthDayRules)
if (next >= this.last.day) {
// if the next month day is in the future jump to it.
this.last.day = next;
} else {
// in this case the 'next' monthday has past
// we must move to the month.
nextMonth();
continue;
}
// Now we can loop through the day rules to see
// if one matches the current month date.
for (dayIdx = 0; dayIdx < dayLen; dayIdx++) {
var parts = this.ruleDayOfWeek(byDay[dayIdx]);
var pos = parts[0];
var dow = parts[1];
if (this.last.isNthWeekDay(dow, pos)) {
// when we find the valid one we can mark
// the conditions as met and break the loop.
// (Because we have this condition above
// it will also break the parent loop).
dataIsValid = 1;
break;
}
}
// Its completely possible that the combination
// cannot be matched in the current month.
// When we reach the end of possible combinations
// in the current month we iterate to the next one.
if (!dataIsValid && dateIdx === (dateLen - 1)) {
nextMonth();
continue;
}
}
return dataIsValid;
},
next_month: function next_month() {
var this_freq = (this.rule.freq == "MONTHLY");
var data_valid = 1;
if (this.next_hour() == 0) {
return data_valid;
}
if (this.has_by_data("BYDAY") && this.has_by_data("BYMONTHDAY")) {
data_valid = this._byDayAndMonthDay();
} else if (this.has_by_data("BYDAY")) {
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
var setpos = 0;
if (this.has_by_data("BYSETPOS")) {
var last_day = this.last.day;
for (var day = 1; day <= daysInMonth; day++) {
this.last.day = day;
if (this.is_day_in_byday(this.last) && day <= last_day) {
setpos++;
}
}
this.last.day = last_day;
}
for (var day = this.last.day + 1; day <= daysInMonth; day++) {
this.last.day = day;
if (this.is_day_in_byday(this.last)) {
if (!this.has_by_data("BYSETPOS") ||
this.check_set_position(++setpos) ||
this.check_set_position(setpos - this.by_data.BYSETPOS.length - 1)) {
data_valid = 1;
break;
}
}
}
if (day > daysInMonth) {
this.last.day = 1;
this.increment_month();
if (this.is_day_in_byday(this.last)) {
if (!this.has_by_data("BYSETPOS") || this.check_set_position(1)) {
data_valid = 1;
}
} else {
data_valid = 0;
}
}
} else if (this.has_by_data("BYMONTHDAY")) {
this.by_indices.BYMONTHDAY++;
if (this.by_indices.BYMONTHDAY >= this.by_data.BYMONTHDAY.length) {
this.by_indices.BYMONTHDAY = 0;
this.increment_month();
}
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
var day = this.by_data.BYMONTHDAY[this.by_indices.BYMONTHDAY];
if (day < 0) {
day = daysInMonth + day + 1;
}
if (day > daysInMonth) {
this.last.day = 1;
data_valid = this.is_day_in_byday(this.last);
}
this.last.day = day;
} else {
this.last.day = this.by_data.BYMONTHDAY[0];
this.increment_month();
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
this.last.day = Math.min(this.last.day, daysInMonth);
}
return data_valid;
},
next_weekday_by_week: function next_weekday_by_week() {
var end_of_data = 0;
if (this.next_hour() == 0) {
return end_of_data;
}
if (!this.has_by_data("BYDAY")) {
return 1;
}
for (;;) {
var tt = new ICAL.icaltime();
tt.auto_normalize = false;
this.by_indices.BYDAY++;
if (this.by_indices.BYDAY == this.by_data.BYDAY.length) {
this.by_indices.BYDAY = 0;
end_of_data = 1;
}
var coded_day = this.by_data.BYDAY[this.by_indices.BYDAY];
var parts = this.ruleDayOfWeek(coded_day);
var dow = parts[1];
dow -= this.rule.wkst;
if (dow < 0) {
dow += 7;
}
tt.year = this.last.year;
tt.month = this.last.month;
tt.day = this.last.day;
var startOfWeek = tt.start_doy_week(this.rule.wkst);
if (dow + startOfWeek < 1) {
// The selected date is in the previous year
if (!end_of_data) {
continue;
}
}
var next = ICAL.icaltime.fromDayOfYear(startOfWeek + dow,
this.last.year);
this.last.day = next.day;
this.last.month = next.month;
this.last.year = next.year;
return end_of_data;
}
},
next_year: function next_year() {
if (this.next_hour() == 0) {
return 0;
}
if (++this.days_index == this.days.length) {
this.days_index = 0;
do {
this.increment_year(this.rule.interval);
this.expand_year_days(this.last.year);
} while (this.days.length == 0);
}
var next = ICAL.icaltime.fromDayOfYear(this.days[this.days_index],
this.last.year);
this.last.day = next.day;
this.last.month = next.month;
return 1;
},
ruleDayOfWeek: function ruleDayOfWeek(dow) {
var matches = dow.match(/([+-]?[0-9])?(MO|TU|WE|TH|FR|SA|SU)/);
if (matches) {
var pos = parseInt(matches[1] || 0, 10);
dow = ICAL.icalrecur.icalDayToNumericDay(matches[2]);
return [pos, dow];
} else {
return [0, 0];
}
},
next_generic: function next_generic(aRuleType, aInterval, aDateAttr,
aFollowingAttr, aPreviousIncr) {
var has_by_rule = (aRuleType in this.by_data);
var this_freq = (this.rule.freq == aInterval);
var end_of_data = 0;
if (aPreviousIncr && this[aPreviousIncr]() == 0) {
return end_of_data;
}
if (has_by_rule) {
this.by_indices[aRuleType]++;
var idx = this.by_indices[aRuleType];
var dta = this.by_data[aRuleType];
if (this.by_indices[aRuleType] == dta.length) {
this.by_indices[aRuleType] = 0;
end_of_data = 1;
}
this.last[aDateAttr] = dta[this.by_indices[aRuleType]];
} else if (this_freq) {
this["increment_" + aDateAttr](this.rule.interval);
}
if (has_by_rule && end_of_data && this_freq) {
this["increment_" + aFollowingAttr](1);
}
return end_of_data;
},
increment_monthday: function increment_monthday(inc) {
for (var i = 0; i < inc; i++) {
var daysInMonth = ICAL.icaltime.daysInMonth(this.last.month, this.last.year);
this.last.day++;
if (this.last.day > daysInMonth) {
this.last.day -= daysInMonth;
this.increment_month();
}
}
},
increment_month: function increment_month() {
if (this.has_by_data("BYMONTH")) {
this.by_indices.BYMONTH++;
if (this.by_indices.BYMONTH == this.by_data.BYMONTH.length) {
this.by_indices.BYMONTH = 0;
this.increment_year(1);
}
this.last.month = this.by_data.BYMONTH[this.by_indices.BYMONTH];
} else {
var inc;
if (this.rule.freq == "MONTHLY") {
this.last.month += this.rule.interval;
} else {
this.last.month++;
}
this.last.month--;
var years = ICAL.helpers.trunc(this.last.month / 12);
this.last.month %= 12;
this.last.month++;
if (years != 0) {
this.increment_year(years);
}
}
},
increment_year: function increment_year(inc) {
this.last.year += inc;
},
increment_generic: function increment_generic(inc, aDateAttr,
aFactor, aNextIncrement) {
this.last[aDateAttr] += inc;
var nextunit = ICAL.helpers.trunc(this.last[aDateAttr] / aFactor);
this.last[aDateAttr] %= aFactor;
if (nextunit != 0) {
this["increment_" + aNextIncrement](nextunit);
}
},
has_by_data: function has_by_data(aRuleType) {
return (aRuleType in this.rule.parts);
},
expand_year_days: function expand_year_days(aYear) {
var t = new ICAL.icaltime();
this.days = [];
// We need our own copy with a few keys set
var parts = {};
var rules = ["BYDAY", "BYWEEKNO", "BYMONTHDAY", "BYMONTH", "BYYEARDAY"];
for (var p in rules) {
var part = rules[p];
if (part in this.rule.parts) {
parts[part] = this.rule.parts[part];
}
}
if ("BYMONTH" in parts && "BYWEEKNO" in parts) {
var valid = 1;
var validWeeks = {};
t.year = aYear;
t.isDate = true;
for (var monthIdx = 0; monthIdx < this.by_data.BYMONTH.length; monthIdx++) {
var month = this.by_data.BYMONTH[monthIdx];
t.month = month;
t.day = 1;
var first_week = t.week_number(this.rule.wkst);
t.day = ICAL.icaltime.daysInMonth(month, aYear);
var last_week = t.week_number(this.rule.wkst);
for (monthIdx = first_week; monthIdx < last_week; monthIdx++) {
validWeeks[monthIdx] = 1;
}
}
for (var weekIdx = 0; weekIdx < this.by_data.BYWEEKNO.length && valid; weekIdx++) {
var weekno = this.by_data.BYWEEKNO[weekIdx];
if (weekno < 52) {
valid &= validWeeks[weekIdx];
} else {
valid = 0;
}
}
if (valid) {
delete parts.BYMONTH;
} else {
delete parts.BYWEEKNO;
}
}
var partCount = Object.keys(parts).length;
if (partCount == 0) {
var t = this.dtstart.clone();
t.year = this.last.year;
this.days.push(t.dayOfYear());
} else if (partCount == 1 && "BYMONTH" in parts) {
for (var monthkey in this.by_data.BYMONTH) {
var t2 = this.dtstart.clone();
t2.year = aYear;
t2.month = this.by_data.BYMONTH[monthkey];
t2.isDate = true;
this.days.push(t2.dayOfYear());
}
} else if (partCount == 1 && "BYMONTHDAY" in parts) {
for (var monthdaykey in this.by_data.BYMONTHDAY) {
var t2 = this.dtstart.clone();
t2.day = this.by_data.BYMONTHDAY[monthdaykey];
t2.year = aYear;
t2.isDate = true;
this.days.push(t2.dayOfYear());
}
} else if (partCount == 2 &&
"BYMONTHDAY" in parts &&
"BYMONTH" in parts) {
for (var monthkey in this.by_data.BYMONTH) {
for (var monthdaykey in this.by_data.BYMONTHDAY) {
t.day = this.by_data.BYMONTHDAY[monthdaykey];
t.month = this.by_data.BYMONTH[monthkey];
t.year = aYear;
t.isDate = true;
this.days.push(t.dayOfYear());
}
}
} else if (partCount == 1 && "BYWEEKNO" in parts) {
// TODO unimplemented in libical
} else if (partCount == 2 &&
"BYWEEKNO" in parts &&
"BYMONTHDAY" in parts) {
// TODO unimplemented in libical
} else if (partCount == 1 && "BYDAY" in parts) {
this.days = this.days.concat(this.expand_by_day(aYear));
} else if (partCount == 2 && "BYDAY" in parts && "BYMONTH" in parts) {
for (var monthkey in this.by_data.BYMONTH) {
month = this.by_data.BYMONTH[monthkey];
var daysInMonth = ICAL.icaltime.daysInMonth(month, aYear);
t.year = aYear;
t.month = this.by_data.BYMONTH[monthkey];
t.day = 1;
t.isDate = true;
var first_dow = t.dayOfWeek();
var doy_offset = t.dayOfYear() - 1;
t.day = daysInMonth;
var last_dow = t.dayOfWeek();
if (this.has_by_data("BYSETPOS")) {
var set_pos_counter = 0;
var by_month_day = [];
for (var day = 1; day <= daysInMonth; day++) {
t.day = day;
if (this.is_day_in_byday(t)) {
by_month_day.push(day);
}
}
for (var spIndex = 0; spIndex < by_month_day.length; spIndex++) {
if (this.check_set_position(spIndex + 1) ||
this.check_set_position(spIndex - by_month_day.length)) {
this.days.push(doy_offset + by_month_day[spIndex]);
}
}
} else {
for (var daycodedkey in this.by_data.BYDAY) {
//TODO: This should return dates in order of occurrence
// (1,2,3, etc...) instead of by weekday (su, mo, etc..)
var coded_day = this.by_data.BYDAY[daycodedkey];
var parts = this.ruleDayOfWeek(coded_day);
var pos = parts[0];
var dow = parts[1];
var month_day;
var first_matching_day = ((dow + 7 - first_dow) % 7) + 1;
var last_matching_day = daysInMonth - ((last_dow + 7 - dow) % 7);
if (pos == 0) {
for (var day = first_matching_day; day <= daysInMonth; day += 7) {
this.days.push(doy_offset + day);
}
} else if (pos > 0) {
month_day = first_matching_day + (pos - 1) * 7;
if (month_day <= daysInMonth) {
this.days.push(doy_offset + month_day);
}
} else {
month_day = last_matching_day + (pos + 1) * 7;
if (month_day > 0) {
this.days.push(doy_offset + month_day);
}
}
}
}
}
} else if (partCount == 2 && "BYDAY" in parts && "BYMONTHDAY" in parts) {
var expandedDays = this.expand_by_day(aYear);
for (var daykey in expandedDays) {
var day = expandedDays[daykey];
var tt = ICAL.icaltime.fromDayOfYear(day, aYear);
if (this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) {
this.days.push(day);
}
}
} else if (partCount == 3 &&
"BYDAY" in parts &&
"BYMONTHDAY" in parts &&
"BYMONTH" in parts) {
var expandedDays = this.expand_by_day(aYear);
for (var daykey in expandedDays) {
var day = expandedDays[daykey];
var tt = ICAL.icaltime.fromDayOfYear(day, aYear);
if (this.by_data.BYMONTH.indexOf(tt.month) >= 0 &&
this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) {
this.days.push(day);
}
}
} else if (partCount == 2 && "BYDAY" in parts && "BYWEEKNO" in parts) {
var expandedDays = this.expand_by_day(aYear);
for (var daykey in expandedDays) {
var day = expandedDays[daykey];
var tt = ICAL.icaltime.fromDayOfYear(day, aYear);
var weekno = tt.week_number(this.rule.wkst);
if (this.by_data.BYWEEKNO.indexOf(weekno)) {
this.days.push(day);
}
}
} else if (partCount == 3 &&
"BYDAY" in parts &&
"BYWEEKNO" in parts &&
"BYMONTHDAY" in parts) {
// TODO unimplemted in libical
} else if (partCount == 1 && "BYYEARDAY" in parts) {
this.days = this.days.concat(this.by_data.BYYEARDAY);
} else {
this.days = [];
}
return 0;
},
expand_by_day: function expand_by_day(aYear) {
var days_list = [];
var tmp = this.last.clone();
tmp.year = aYear;
tmp.month = 1;
tmp.day = 1;
tmp.isDate = true;
var start_dow = tmp.dayOfWeek();
tmp.month = 12;
tmp.day = 31;
tmp.isDate = true;
var end_dow = tmp.dayOfWeek();
var end_year_day = tmp.dayOfYear();
for (var daykey in this.by_data.BYDAY) {
var day = this.by_data.BYDAY[daykey];
var parts = this.ruleDayOfWeek(day);
var pos = parts[0];
var dow = parts[1];
if (pos == 0) {
var tmp_start_doy = ((dow + 7 - start_dow) % 7) + 1;
for (var doy = tmp_start_doy; doy <= end_year_day; doy += 7) {
days_list.push(doy);
}
} else if (pos > 0) {
var first;
if (dow >= start_dow) {
first = dow - start_dow + 1;
} else {
first = dow - start_dow + 8;
}
days_list.push(first + (pos - 1) * 7);
} else {
var last;
pos = -pos;
if (dow <= end_dow) {
last = end_year_day - end_dow + dow;
} else {
last = end_year_day - end_dow + dow - 7;
}
days_list.push(last - (pos - 1) * 7);
}
}
return days_list;
},
is_day_in_byday: function is_day_in_byday(tt) {
for (var daykey in this.by_data.BYDAY) {
var day = this.by_data.BYDAY[daykey];
var parts = this.ruleDayOfWeek(day);
var pos = parts[0];
var dow = parts[1];
var this_dow = tt.dayOfWeek();
if ((pos == 0 && dow == this_dow) ||
(tt.nthWeekDay(dow, pos) == tt.day)) {
return 1;
}
}
return 0;
},
/**
* Checks if given value is in BYSETPOS.
*
* @param {Numeric} aPos position to check for.
* @return {Boolean} false unless BYSETPOS rules exist
* and the given value is present in rules.
*/
check_set_position: function check_set_position(aPos) {
if (this.has_by_data('BYSETPOS')) {
var idx = this.by_data.BYSETPOS.indexOf(aPos);
// negative numbers are not false-y
return idx !== -1;
}
return false;
},
sort_byday_rules: function icalrecur_sort_byday_rules(aRules, aWeekStart) {
for (var i = 0; i < aRules.length; i++) {
for (var j = 0; j < i; j++) {
var one = this.ruleDayOfWeek(aRules[j])[1];
var two = this.ruleDayOfWeek(aRules[i])[1];
one -= aWeekStart;
two -= aWeekStart;
if (one < 0) one += 7;
if (two < 0) two += 7;
if (one > two) {
var tmp = aRules[i];
aRules[i] = aRules[j];
aRules[j] = tmp;
}
}
}
},
check_contract_restriction: function check_contract_restriction(aRuleType, v) {
var indexMapValue = icalrecur_iterator._indexMap[aRuleType];
var ruleMapValue = icalrecur_iterator._expandMap[this.rule.freq][indexMapValue];
var pass = false;
if (aRuleType in this.by_data &&
ruleMapValue == icalrecur_iterator.CONTRACT) {
var ruleType = this.by_data[aRuleType];
for (var bydatakey in ruleType) {
if (ruleType[bydatakey] == v) {
pass = true;
break;
}
}
} else {
// Not a contracting byrule or has no data, test passes
pass = true;
}
return pass;
},
check_contracting_rules: function check_contracting_rules() {
var dow = this.last.dayOfWeek();
var weekNo = this.last.week_number(this.rule.wkst);
var doy = this.last.dayOfYear();
return (this.check_contract_restriction("BYSECOND", this.last.second) &&
this.check_contract_restriction("BYMINUTE", this.last.minute) &&
this.check_contract_restriction("BYHOUR", this.last.hour) &&
this.check_contract_restriction("BYDAY", icalrecur_iterator._wkdayMap[dow]) &&
this.check_contract_restriction("BYWEEKNO", weekNo) &&
this.check_contract_restriction("BYMONTHDAY", this.last.day) &&
this.check_contract_restriction("BYMONTH", this.last.month) &&
this.check_contract_restriction("BYYEARDAY", doy));
},
setup_defaults: function setup_defaults(aRuleType, req, deftime) {
var indexMapValue = icalrecur_iterator._indexMap[aRuleType];
var ruleMapValue = icalrecur_iterator._expandMap[this.rule.freq][indexMapValue];
if (ruleMapValue != icalrecur_iterator.CONTRACT) {
if (!(aRuleType in this.by_data)) {
this.by_data[aRuleType] = [deftime];
}
if (this.rule.freq != req) {
return this.by_data[aRuleType][0];
}
}
return deftime;
},
/**
* Convert iterator into a serialize-able object.
* Will preserve current iteration sequence to ensure
* the seamless continuation of the recurrence rule.
*/
toJSON: function() {
var result = Object.create(null);
result.initialized = this.initialized;
result.rule = this.rule.toJSON();
result.dtstart = this.dtstart.toJSON();
result.by_data = this.by_data;
result.days = this.days;
result.last = this.last.toJSON();
result.by_indices = this.by_indices;
result.occurrence_number = this.occurrence_number;
return result;
}
};
icalrecur_iterator._wkdayMap = ["", "SU", "MO", "TU", "WE", "TH", "FR", "SA"];
icalrecur_iterator._indexMap = {
"BYSECOND": 0,
"BYMINUTE": 1,
"BYHOUR": 2,
"BYDAY": 3,
"BYMONTHDAY": 4,
"BYYEARDAY": 5,
"BYWEEKNO": 6,
"BYMONTH": 7,
"BYSETPOS": 8
};
icalrecur_iterator._expandMap = {
"SECONDLY": [1, 1, 1, 1, 1, 1, 1, 1],
"MINUTELY": [2, 1, 1, 1, 1, 1, 1, 1],
"HOURLY": [2, 2, 1, 1, 1, 1, 1, 1],
"DAILY": [2, 2, 2, 1, 1, 1, 1, 1],
"WEEKLY": [2, 2, 2, 2, 3, 3, 1, 1],
"MONTHLY": [2, 2, 2, 2, 2, 3, 3, 1],
"YEARLY": [2, 2, 2, 2, 2, 2, 2, 2]
};
icalrecur_iterator.UNKNOWN = 0;
icalrecur_iterator.CONTRACT = 1;
icalrecur_iterator.EXPAND = 2;
icalrecur_iterator.ILLEGAL = 3;
return icalrecur_iterator;
}());
ICAL.RecurExpansion = (function() {
function formatTime(item) {
return ICAL.helpers.formatClassType(item, ICAL.icaltime);
}
function compareTime(a, b) {
return a.compare(b);
}
function isRecurringComponent(comp) {
return comp.hasProperty('rdate') ||
comp.hasProperty('rrule') ||
comp.hasProperty('recurrence-id');
}
/**
* Primary class for expanding recurring rules.
* Can take multiple rrules, rdates, exdate(s)
* and iterate (in order) over each next occurrence.
*
* Once initialized this class can also be serialized
* saved and continue iteration from the last point.
*
* NOTE: it is intended that this class is to be used
* with ICAL.Event which handles recurrence exceptions.
*
* Options:
* - dtstart: (ICAL.icaltime) start time of event (required)
* - component: (ICAL.Component) component (required unless resuming)
*
* Examples:
*
* // assuming event is a parsed ical component
* var event;
*
* var expand = new ICAL.RecurExpansion({
* component: event,
* start: event.getFirstPropertyValue('DTSTART')
* });
*
* // remember there are infinite rules
* // so its a good idea to limit the scope
* // of the iterations then resume later on.
*
* // next is always an ICAL.icaltime or null
* var next;
*
* while(someCondition && (next = expand.next())) {
* // do something with next
* }
*
* // save instance for later
* var json = JSON.stringify(expand);
*
* //...
*
* // NOTE: if the component's properties have
* // changed you will need to rebuild the
* // class and start over. This only works
* // when the component's recurrence info is the same.
* var expand = new ICAL.RecurExpansion(JSON.parse(json));
*
*
* @param {Object} options see options block.
*/
function RecurExpansion(options) {
this.ruleDates = [];
this.exDates = [];
this.fromData(options);
}
RecurExpansion.prototype = {
/**
* True when iteration is fully completed.
*/
complete: false,
/**
* Array of rrule iterators.
*
* @type Array[ICAL.icalrecur_iterator]
* @private
*/
ruleIterators: null,
/**
* Array of rdate instances.
*
* @type Array[ICAL.icaltime]
* @private
*/
ruleDates: null,
/**
* Array of exdate instances.
*
* @type Array[ICAL.icaltime]
* @private
*/
exDates: null,
/**
* Current position in ruleDates array.
* @type Numeric
* @private
*/
ruleDateInc: 0,
/**
* Current position in exDates array
* @type Numeric
* @private
*/
exDateInc: 0,
/**
* Current negative date.
*
* @type ICAL.icaltime
* @private
*/
exDate: null,
/**
* Current additional date.
*
* @type ICAL.icaltime
* @private
*/
ruleDate: null,
/**
* Start date of recurring rules.
*
* @type ICAL.icaltime
*/
dtstart: null,
/**
* Last expanded time
*
* @type ICAL.icaltime
*/
last: null,
fromData: function(options) {
var start = ICAL.helpers.formatClassType(options.dtstart, ICAL.icaltime);
if (!start) {
throw new Error('.dtstart (ICAL.icaltime) must be given');
} else {
this.dtstart = start;
}
if (options.component) {
this._init(options.component);
} else {
this.last = formatTime(options.last);
this.ruleIterators = options.ruleIterators.map(function(item) {
return ICAL.helpers.formatClassType(item, ICAL.icalrecur_iterator);
});
this.ruleDateInc = options.ruleDateInc;
this.exDateInc = options.exDateInc;
if (options.ruleDates) {
this.ruleDates = options.ruleDates.map(formatTime);
this.ruleDate = this.ruleDates[this.ruleDateInc];
}
if (options.exDates) {
this.exDates = options.exDates.map(formatTime);
this.exDate = this.exDates[this.exDateInc];
}
if (typeof(options.complete) !== 'undefined') {
this.complete = options.complete;
}
}
},
next: function() {
var iter;
var ruleOfDay;
var next;
var compare;
var maxTries = 500;
var currentTry = 0;
while (true) {
if (currentTry++ > maxTries) {
throw new Error(
'max tries have occured, rule may be impossible to forfill.'
);
}
next = this.ruleDate;
iter = this._nextRecurrenceIter(this.last);
// no more matches
// because we increment the rule day or rule
// _after_ we choose a value this should be
// the only spot where we need to worry about the
// end of events.
if (!next && !iter) {
// there are no more iterators or rdates
this.complete = true;
break;
}
// no next rule day or recurrence rule is first.
if (!next || (iter && next.compare(iter.last) > 0)) {
// must be cloned, recur will reuse the time element.
next = iter.last.clone();
// move to next so we can continue
iter.next();
}
// if the ruleDate is still next increment it.
if (this.ruleDate === next) {
this._nextRuleDay();
}
this.last = next;
// check the negative rules
if (this.exDate) {
compare = this.exDate.compare(this.last);
if (compare < 0) {
this._nextExDay();
}
// if the current rule is excluded skip it.
if (compare === 0) {
this._nextExDay();
continue;
}
}
//XXX: The spec states that after we resolve the final
// list of dates we execute exdate this seems somewhat counter
// intuitive to what I have seen most servers do so for now
// I exclude based on the original date not the one that may
// have been modified by the exception.
return this.last;
}
},
/**
* Converts object into a serialize-able format.
*/
toJSON: function() {
function toJSON(item) {
return item.toJSON();
}
var result = Object.create(null);
result.ruleIterators = this.ruleIterators.map(toJSON);
if (this.ruleDates) {
result.ruleDates = this.ruleDates.map(toJSON);
}
if (this.exDates) {
result.exDates = this.exDates.map(toJSON);
}
result.ruleDateInc = this.ruleDateInc;
result.exDateInc = this.exDateInc;
result.last = this.last.toJSON();
result.dtstart = this.dtstart.toJSON();
result.complete = this.complete;
return result;
},
_extractDates: function(component, property) {
var result = [];
var props = component.getAllProperties(property);
var len = props.length;
var i = 0;
var prop;
var idx;
for (; i < len; i++) {
prop = props[i].getFirstValue();
idx = ICAL.helpers.binsearchInsert(
result,
prop,
compareTime
);
// ordered insert
result.splice(idx, 0, prop);
}
return result;
},
_init: function(component) {
this.ruleIterators = [];
this.last = this.dtstart.clone();
// to provide api consistency non-recurring
// events can also use the iterator though it will
// only return a single time.
if (!isRecurringComponent(component)) {
this.ruleDate = this.last.clone();
this.complete = true;
return;
}
if (component.hasProperty('rrule')) {
var rules = component.getAllProperties('rrule');
var i = 0;
var len = rules.length;
var rule;
var iter;
for (; i < len; i++) {
rule = rules[i].getFirstValue();
iter = rule.iterator(this.dtstart);
this.ruleIterators.push(iter);
// increment to the next occurrence so future
// calls to next return times beyond the initial iteration.
// XXX: I find this suspicious might be a bug?
iter.next();
}
}
if (component.hasProperty('rdate')) {
this.ruleDates = this._extractDates(component, 'rdate');
this.ruleDateInc = ICAL.helpers.binsearchInsert(
this.ruleDates,
this.last,
compareTime
);
this.ruleDate = this.ruleDates[this.ruleDateInc];
}
if (component.hasProperty('exdate')) {
this.exDates = this._extractDates(component, 'exdate');
// if we have a .last day we increment the index to beyond it.
this.exDateInc = ICAL.helpers.binsearchInsert(
this.exDates,
this.last,
compareTime
);
this.exDate = this.exDates[this.exDateInc];
}
},
_nextExDay: function() {
this.exDate = this.exDates[++this.exDateInc];
},
_nextRuleDay: function() {
this.ruleDate = this.ruleDates[++this.ruleDateInc];
},
/**
* Find and return the recurrence rule with the most
* recent event and return it.
*
* @return {Object} iterator.
*/
_nextRecurrenceIter: function() {
var iters = this.ruleIterators;
if (iters.length === 0) {
return null;
}
var len = iters.length;
var iter;
var iterTime;
var iterIdx = 0;
var chosenIter;
// loop through each iterator
for (; iterIdx < len; iterIdx++) {
iter = iters[iterIdx];
iterTime = iter.last;
// if iteration is complete
// then we must exclude it from
// the search and remove it.
if (iter.completed) {
len--;
if (iterIdx !== 0) {
iterIdx--;
}
iters.splice(iterIdx, 1);
continue;
}
// find the most recent possible choice
if (!chosenIter || chosenIter.last.compare(iterTime) > 0) {
// that iterator is saved
chosenIter = iter;
}
}
// the chosen iterator is returned but not mutated
// this iterator contains the most recent event.
return chosenIter;
}
};
return RecurExpansion;
}());
ICAL.Event = (function() {
function Event(component, options) {
if (!(component instanceof ICAL.Component)) {
options = component;
component = null;
}
if (component) {
this.component = component;
} else {
this.component = new ICAL.Component('vevent');
}
this.exceptions = Object.create(null);
if (options && options.exceptions) {
options.exceptions.forEach(this.relateException, this);
}
}
Event.prototype = {
/**
* List of related event exceptions.
*
* @type Array[ICAL.Event]
*/
exceptions: null,
/**
* Relates a given event exception to this object.
* If the given component does not share the UID of
* this event it cannot be related and will throw an
* exception.
*
* If this component is an exception it cannot have other
* exceptions related to it.
*
* @param {ICAL.Component|ICAL.Event} obj component or event.
*/
relateException: function(obj) {
if (this.isRecurrenceException()) {
throw new Error('cannot relate exception to exceptions');
}
if (obj instanceof ICAL.Component) {
obj = new ICAL.Event(obj);
}
if (obj.uid !== this.uid) {
throw new Error('attempted to relate unrelated exception');
}
// we don't sort or manage exceptions directly
// here the recurrence expander handles that.
this.exceptions[obj.recurrenceId.toString()] = obj;
},
/**
* Returns the occurrence details based on its start time.
* If the occurrence has an exception will return the details
* for that exception.
*
* NOTE: this method is intend to be used in conjunction
* with the #iterator method.
*
* @param {ICAL.icaltime} occurrence time occurrence.
*/
getOccurrenceDetails: function(occurrence) {
var id = occurrence.toString();
var result = {
//XXX: Clone?
recurrenceId: occurrence
};
if (id in this.exceptions) {
var item = result.item = this.exceptions[id];
result.startDate = item.startDate;
result.endDate = item.endDate;
result.item = item;
} else {
var end = occurrence.clone();
end.addDuration(this.duration);
result.endDate = end;
result.startDate = occurrence;
result.item = this;
}
return result;
},
/**
* Builds a recur expansion instance for a specific
* point in time (defaults to startDate).
*
* @return {ICAL.RecurExpansion} expander object.
*/
iterator: function(startTime) {
return new ICAL.RecurExpansion({
component: this.component,
dtstart: startTime || this.startDate
});
},
isRecurring: function() {
var comp = this.component;
return comp.hasProperty('rrule') || comp.hasProperty('rdate');
},
isRecurrenceException: function() {
return this.component.hasProperty('recurrence-id');
},
/**
* Returns the types of recurrences this event may have.
*
* Returned as an object with the following possible keys:
*
* - YEARLY
* - MONTHLY
* - WEEKLY
* - DAILY
* - MINUTELY
* - SECONDLY
*
* @return {Object} object of recurrence flags.
*/
getRecurrenceTypes: function() {
var rules = this.component.getAllProperties('rrule');
var i = 0;
var len = rules.length;
var result = Object.create(null);
for (; i < len; i++) {
var value = rules[i].getFirstValue();
result[value.freq] = true;
}
return result;
},
get uid() {
return this._firstProp('uid');
},
set uid(value) {
this._setProp('uid', value);
},
get startDate() {
return this._firstProp('dtstart');
},
set startDate(value) {
this._setProp('dtstart', value);
},
get endDate() {
return this._firstProp('dtend');
},
set endDate(value) {
this._setProp('dtend', value);
},
get duration() {
// cached because its dynamically calculated
// and may be frequently used. This could be problematic
// later if we modify the underlying start/endDate.
//
// When do add that functionality it should expire this cache...
if (typeof(this._duration) === 'undefined') {
this._duration = this.endDate.subtractDate(this.startDate);
}
return this._duration;
},
get location() {
return this._firstProp('location');
},
set location(value) {
return this._setProp('location', value);
},
get attendees() {
//XXX: This is way lame we should have a better
// data structure for this later.
return this.component.getAllProperties('attendee');
},
get summary() {
return this._firstProp('summary');
},
set summary(value) {
this._setProp('summary', value);
},
get description() {
return this._firstProp('description');
},
set description(value) {
this._setProp('description', value);
},
get organizer() {
return this._firstProp('organizer');
},
set organizer(value) {
this._setProp('organizer', value);
},
get sequence() {
return this._firstProp('sequence');
},
set sequence(value) {
this._setProp('sequence', value);
},
get recurrenceId() {
return this._firstProp('recurrence-id');
},
set recurrenceId(value) {
this._setProp('recurrence-id', value);
},
_setProp: function(name, value) {
this.component.updatePropertyWithValue(name, value);
},
_firstProp: function(name) {
return this.component.getFirstPropertyValue(name);
},
toString: function() {
return this.component.toString();
}
};
return Event;
}());
ICAL.ComponentParser = (function() {
/**
* Component parser initializer.
*
* Usage:
*
* var options = {
* // when false no events will be emitted for type
* parseEvent: true,
* parseTimezone: true
* };
*
* var parser = new ICAL.ComponentParser(options);
*
* parser.onevent() {
* //...
* }
*
* // ontimezone, etc...
*
* parser.oncomplete = function() {
*
* };
*
* parser.process(string | component);
*
*
* @param {Object} options component parser options.
*/
function ComponentParser(options) {
if (typeof(options) === 'undefined') {
options = {};
}
var key;
for (key in options) {
if (options.hasOwnProperty(key)) {
this[key] = options[key];
}
}
}
ComponentParser.prototype = {
/**
* When true parse events
*
* @type Boolean
*/
parseEvent: true,
/**
* when true parse timezones
*
* @type Boolean
*/
parseTimezone: true,
/* SAX like events here for reference */
/**
* Fired when parsing is complete
*/
oncomplete: function() {},
/**
* Fired if an error occurs during parsing.
*
* @param {Error} err details of error.
*/
onerror: function(err) {},
/**
* Fired when a top level component (vtimezone) is found
*
* @param {ICAL.icaltimezone} timezone object.
*/
ontimezone: function(component) {},
/*
* Fired when a top level component (VEVENT) is found.
* @param {ICAL.Event} component top level component.
*/
onevent: function(component) {},
/**
* Process a string or parse ical object.
* This function itself will return nothing but
* will start the parsing process.
*
* Events must be registered prior to calling this method.
*
* @param {String|Object} ical string or parsed ical object.
*/
process: function(ical) {
//TODO: this is sync now in the future we will have a incremental parser.
if (typeof(ical) === 'string') {
ical = ICAL.parse(ical)[1];
}
if (!(ical instanceof ICAL.Component)) {
ical = new ICAL.Component(ical);
}
var components = ical.getAllSubcomponents();
var i = 0;
var len = components.length;
var component;
for (; i < len; i++) {
component = components[i];
switch (component.name) {
case 'vevent':
if (this.parseEvent) {
this.onevent(new ICAL.Event(component));
}
break;
default:
continue;
}
}
//XXX: ideally we should do a "nextTick" here
// so in all cases this is actually async.
this.oncomplete();
}
};
return ComponentParser;
}());
|