ctucx.git: tinyDAV

[php] Cal-/ CardDAV server with a simple web-GUI based on SabreDAV

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 
/*
InfCloud - the open source CalDAV/CardDAV Web Client
Copyright (C) 2011-2015
    Jan Mate <jan.mate@inf-it.com>
    Andrej Lezo <andrej.lezo@inf-it.com>
    Matej Mihalik <matej.mihalik@inf-it.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

var globalSettings={
	version: {value: (typeof globalSettingsVersion!='undefined' && globalSettingsVersion!=null) ? globalSettingsVersion : 1, locked:false},
	resourcealphabetsorting: {value: (typeof globalResourceAlphabetSorting!='undefined' && globalResourceAlphabetSorting!=null) ? globalResourceAlphabetSorting : true, locked:false},
	usejqueryauth: {value:  (typeof globalUseJqueryAuth!='undefined' && globalUseJqueryAuth!=null) ? globalUseJqueryAuth : false, locked:false},
	settingstype: {value:  (typeof globalSettingsType!='undefined' && globalSettingsType!=null && globalSettingsType!='') ? globalSettingsType : 'principal-URL', locked:false},
	defaultactiveapp: {value:  (typeof globalDefaultActiveApp!='undefined' && globalDefaultActiveApp!=null && globalDefaultActiveApp!='') ? globalDefaultActiveApp : null, locked:false},
	islastdefaultactiveapp: {value:  false, locked:false},
	datepickerfirstdayofweek: {value:  (typeof globalDatepickerFirstDayOfWeek!='undefined' && globalDatepickerFirstDayOfWeek!=null) ? globalDatepickerFirstDayOfWeek : 1, locked:false},
	syncresourcesinterval: {value: (typeof globalSyncResourcesInterval!='undefined' && globalSyncResourcesInterval!=null) ? globalSyncResourcesInterval :300000, locked:false},
	datepickerformat: {value: (typeof globalDatepickerFormat!='undefined' && globalDatepickerFormat!=null && globalDatepickerFormat!='') ? globalDatepickerFormat : localization[globalInterfaceLanguage]._default_datepicker_format_, locked:false},
	backgroundsync: {value: (typeof globalBackgroundSync!='undefined' && globalBackgroundSync!=null) ? globalBackgroundSync : true, locked:false},
	enablekbnavigation: {value: (typeof globalEnableKbNavigation!='undefined' && globalEnableKbNavigation!=null) ? globalEnableKbNavigation : true, locked:false},
	rewritetimezonecomponent: {value:  (typeof globalRewriteTimezoneComponent!='undefined' && globalRewriteTimezoneComponent!=null) ? globalRewriteTimezoneComponent : true, locked:false},
	removeunknowntimezone: {value:  (typeof globalRemoveUnknownTimezone!='undefined' && globalRemoveUnknownTimezone!=null) ? globalRemoveUnknownTimezone : false, locked:false},
	mozillasupport: {value:  (typeof globalMozillaSupport!='undefined' && globalMozillaSupport!=null) ? globalMozillaSupport : false, locked:false},
	appleremindersmode: {value:  (typeof globalAppleRemindersMode!='undefined' && globalAppleRemindersMode!=null) ? globalAppleRemindersMode : false, locked:false},
	titleformatmonth: {value:  localization[globalInterfaceLanguage]._default_title_format_month_, locked:false},
	titleformatweek: {value:  localization[globalInterfaceLanguage]._default_title_format_week_, locked:false},
	titleformatday: {value:  localization[globalInterfaceLanguage]._default_title_format_day_, locked:false},
	titleformattable: {value:  localization[globalInterfaceLanguage]._default_title_format_table_, locked:false},
	columnformatagenda: {value:  localization[globalInterfaceLanguage]._default_column_format_agenda_, locked:false},
	activecalendarcollections: {value:  (typeof globalActiveCalendarCollections!='undefined' && globalActiveCalendarCollections!=null) ? globalActiveCalendarCollections : new Array(), locked:false},
	activetodocollections: {value:  (typeof globalActiveTodoCollections!='undefined' && globalActiveTodoCollections!=null) ? globalActiveTodoCollections : new Array(), locked:false},
	loadedcalendarcollections: {value:  (typeof globalLoadedCalendarCollections!='undefined' && globalLoadedCalendarCollections!=null) ? globalLoadedCalendarCollections : new Array(), locked:false},
	loadedtodocollections: {value:  (typeof globalLoadedTodoCollections!='undefined' && globalLoadedTodoCollections!=null) ? globalLoadedTodoCollections : new Array(), locked:false},
	todolistfilterselected: {value:  (typeof globalTodoListFilterSelected!='undefined' && globalTodoListFilterSelected!=null && globalTodoListFilterSelected!='') ? globalTodoListFilterSelected : ['filterAction', 'filterProgress'], locked:false},
	activeview: {value:  (typeof globalActiveView!='undefined' && globalActiveView!=null && globalActiveView!='') ? globalActiveView : 'multiWeek', locked:false},
	islastactiveview: {value:  true, locked:false},
	calendarselected: {value:  (typeof globalCalendarSelected!='undefined' && globalCalendarSelected!=null && globalCalendarSelected!='') ? globalCalendarSelected : '', locked:false},
	todocalendarselected: {value:  (typeof globalTodoCalendarSelected!='undefined' && globalTodoCalendarSelected!=null && globalTodoCalendarSelected!='') ? globalTodoCalendarSelected : '', locked:false},
	timezone: {value:  (typeof globalTimeZone!='undefined' && globalTimeZone!=null && globalTimeZone!='') ? globalTimeZone : 'local', locked:false},
	islasttimezone: {value: true, locked:false},
	openformmode: {value:  (typeof globalOpenFormMode!='undefined' && globalOpenFormMode!=null && globalOpenFormMode!='') ? globalOpenFormMode : 'double', locked:false},
	calendarstartofbusiness: {value:  (typeof globalCalendarStartOfBusiness!='undefined' && globalCalendarStartOfBusiness!=null) ? globalCalendarStartOfBusiness : 8, locked:false},
	calendarendofbusiness: {value:  (typeof globalCalendarEndOfBusiness!='undefined' && globalCalendarEndOfBusiness!=null) ? globalCalendarEndOfBusiness : 17, locked:false},
	defaulteventduration: {value:  (typeof globalDefaultEventDuration!='undefined' && globalDefaultEventDuration!=null && globalDefaultEventDuration>=0) ? globalDefaultEventDuration : null, locked:false},
	ampmformat: {value:  (typeof globalAMPMFormat!='undefined' && globalAMPMFormat!=null) ? globalAMPMFormat : localization[globalInterfaceLanguage]._default_AMPM_format_, locked:false},
	timeformatagenda: {value:  (typeof globalTimeFormatAgenda!='undefined' && globalTimeFormatAgenda!=null && globalTimeFormatAgenda!='') ? globalTimeFormatAgenda : null, locked:false},
	timeformatbasic: {value:  (typeof globalTimeFormatBasic!='undefined' && globalTimeFormatBasic!=null && globalTimeFormatBasic!='') ? globalTimeFormatBasic : null, locked:false},
	displayhiddenevents: {value:  (typeof globalDisplayHiddenEvents!='undefined' && globalDisplayHiddenEvents!=null) ? globalDisplayHiddenEvents : false, locked:false},
	timezonesupport: {value:  (typeof globalTimeZoneSupport!='undefined' && globalTimeZoneSupport!=null) ? globalTimeZoneSupport : true, locked:false},
	timezonesenabled: {value:  (typeof globalTimeZonesEnabled!='undefined' && globalTimeZonesEnabled!=null && globalTimeZonesEnabled!='') ? globalTimeZonesEnabled : [], locked:false},
	showhiddenalarms: {value:  (typeof globalShowHiddenAlarms!='undefined' && globalShowHiddenAlarms!=null) ? globalShowHiddenAlarms : false, locked:false},
	ignorecompletedorcancelledalarms: {value: (typeof globalIgnoreCompletedOrCancelledAlarms!='undefined' && globalIgnoreCompletedOrCancelledAlarms!=null) ? globalIgnoreCompletedOrCancelledAlarms : true, locked:false},
	weekenddays: {value: (typeof globalWeekendDays!='undefined' && globalWeekendDays!=null && globalWeekendDays!='') ? globalWeekendDays : [0, 6], locked:false},
	eventstartpastlimit: {value:  (typeof globalEventStartPastLimit!='undefined' && globalEventStartPastLimit!=null) ? globalEventStartPastLimit : 3, locked:false},
	todopastlimit: {value:  (typeof globalTodoPastLimit!='undefined' && globalTodoPastLimit!=null) ? globalTodoPastLimit : 3, locked:false},
	eventstartfuturelimit: {value:  (typeof globalEventStartFutureLimit!='undefined' && globalEventStartFutureLimit!=null) ? globalEventStartFutureLimit : 3, locked:false},
	compatibility: {value: (typeof globalCompatibility!='undefined' && globalCompatibility!=null && globalCompatibility!='') ? globalCompatibility : {anniversaryOutputFormat: ['apple']}, locked:false},
	contactstorefn: {value: (typeof globalContactStoreFN!='undefined' && globalContactStoreFN!=null && globalContactStoreFN!='') ? globalContactStoreFN : ['prefix',' last',' middle',' first',' suffix'], locked:false},
	urihandlertel: {value: (typeof globalUriHandlerTel!='undefined' && globalUriHandlerTel!=null && globalUriHandlerTel!='') ? globalUriHandlerTel : 'tel:', locked:false},
	urihandleremail: {value: (typeof globalUriHandlerEmail!='undefined' && globalUriHandlerEmail!=null && globalUriHandlerEmail!='') ? globalUriHandlerEmail : 'mailto:', locked:false},
	urihandlerurl: {value: (typeof globalUriHandlerUrl!='undefined' && globalUriHandlerUrl!=null && globalUriHandlerUrl!='') ? globalUriHandlerUrl : 'http://', locked:false},
	urihandlerprofile: {value: (typeof globalUriHandlerProfile!='undefined' && globalUriHandlerProfile!=null && globalUriHandlerProfile!='') ? globalUriHandlerProfile : {'twitter': 'http://twitter.com/%u', 'facebook': 'http://www.facebook.com/%u', 'flickr': 'http://www.flickr.com/photos/%u', 'linkedin': 'http://www.linkedin.com/in/%u', 'myspace': 'http://www.myspace.com/%u', 'sinaweibo': 'http://weibo.com/n/%u'}, locked:false},
	addresscountryequivalence: {value: (typeof globalAddressCountryEquivalence!='undefined' && globalAddressCountryEquivalence!=null && globalAddressCountryEquivalence!='') ? globalAddressCountryEquivalence : [{country: 'de', regex: '^\\W*Deutschland\\W*$'}, {country: 'sk', regex: '^\\W*Slovensko\\W*$'}], locked:false},
	addressbookselected: {value:  (typeof globalAddressbookSelected!='undefined' && globalAddressbookSelected!=null && globalAddressbookSelected!='') ? globalAddressbookSelected : '', locked:false},
	collectiondisplay: {value:  (typeof globalCollectionDisplay!='undefined' && globalCollectionDisplay!=null && globalCollectionDisplay!='') ? globalCollectionDisplay : (
		(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies) ?
		[{label: '{Name}', value: {company: ['{Company}', ' [{Department}]'], personal: ['{LastName}', ' {MiddleName}', ' {FirstName}']}}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}] :
		[{label: '{Name}', value: ['{LastName}', ' {MiddleName}', ' {FirstName}']}, {label: '{Company} [{Department}]', value: ['{Company}', ' [{Department}]']}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}]
		), locked:false},
	collectionsort: {value:  (typeof globalCollectionSort!='undefined' && globalCollectionSort!=null && globalCollectionSort!='') ? globalCollectionSort : '', locked:false},
	defaultaddresscountry: {value:  (typeof globalDefaultAddressCountry!='undefined' && globalDefaultAddressCountry!=null && globalDefaultAddressCountry!='') ? globalDefaultAddressCountry :'us', locked:false},
	addresscountryfavorites: {value:  (typeof globalAddressCountryFavorites!='undefined' && globalAddressCountryFavorites!=null && globalAddressCountryFavorites!='') ? globalAddressCountryFavorites :[], locked:false},
	activeaddressbookcollections: {value:  (typeof globalActiveAddressbookCollections!='undefined' && globalActiveAddressbookCollections!=null) ? globalActiveAddressbookCollections : new Array(), locked:false},
	loadedaddressbookcollections: {value:  (typeof globalLoadedAddressbookCollections!='undefined' && globalLoadedAddressbookCollections!=null) ? globalLoadedAddressbookCollections : new Array(), locked:false}
};


function resetSettings()
{
	globalSettings={
		version: {value: (typeof globalSettingsVersion!='undefined' && globalSettingsVersion!=null) ? globalSettingsVersion : 1, locked:false},
		resourcealphabetsorting: {value: (typeof globalResourceAlphabetSorting!='undefined' && globalResourceAlphabetSorting!=null) ? globalResourceAlphabetSorting : true, locked:false},
		usejqueryauth: {value:  (typeof globalUseJqueryAuth!='undefined' && globalUseJqueryAuth!=null) ? globalUseJqueryAuth : false, locked:false},
		settingstype: {value:  (typeof globalSettingsType!='undefined' && globalSettingsType!=null && globalSettingsType!='') ? globalSettingsType : 'principal-URL', locked:false},
		defaultactiveapp: {value:  (typeof globalDefaultActiveApp!='undefined' && globalDefaultActiveApp!=null && globalDefaultActiveApp!='') ? globalDefaultActiveApp : null, locked:false},
		islastdefaultactiveapp: {value:  false, locked:false},
		datepickerfirstdayofweek: {value:  (typeof globalDatepickerFirstDayOfWeek!='undefined' && globalDatepickerFirstDayOfWeek!=null) ? globalDatepickerFirstDayOfWeek : 1, locked:false},
		syncresourcesinterval: {value: (typeof globalSyncResourcesInterval!='undefined' && globalSyncResourcesInterval!=null) ? globalSyncResourcesInterval :300000, locked:false},
		datepickerformat: {value: (typeof globalDatepickerFormat!='undefined' && globalDatepickerFormat!=null && globalDatepickerFormat!='') ? globalDatepickerFormat : localization[globalInterfaceLanguage]._default_datepicker_format_, locked:false},
		backgroundsync: {value: (typeof globalBackgroundSync!='undefined' && globalBackgroundSync!=null) ? globalBackgroundSync : true, locked:false},
		enablekbnavigation: {value: (typeof globalEnableKbNavigation!='undefined' && globalEnableKbNavigation!=null) ? globalEnableKbNavigation : true, locked:false},
		rewritetimezonecomponent: {value:  (typeof globalRewriteTimezoneComponent!='undefined' && globalRewriteTimezoneComponent!=null) ? globalRewriteTimezoneComponent : true, locked:false},
		removeunknowntimezone: {value:  (typeof globalRemoveUnknownTimezone!='undefined' && globalRemoveUnknownTimezone!=null) ? globalRemoveUnknownTimezone : false, locked:false},
		mozillasupport: {value:  (typeof globalMozillaSupport!='undefined' && globalMozillaSupport!=null) ? globalMozillaSupport : false, locked:false},
		appleremindersmode: {value:  (typeof globalAppleRemindersMode!='undefined' && globalAppleRemindersMode!=null) ? globalAppleRemindersMode : false, locked:false},
		titleformatmonth: {value:  localization[globalInterfaceLanguage]._default_title_format_month_, locked:false},
		titleformatweek: {value:  localization[globalInterfaceLanguage]._default_title_format_week_, locked:false},
		titleformatday: {value:  localization[globalInterfaceLanguage]._default_title_format_day_, locked:false},
		titleformattable: {value:  localization[globalInterfaceLanguage]._default_title_format_table_, locked:false},
		columnformatagenda: {value:  localization[globalInterfaceLanguage]._default_column_format_agenda_, locked:false},
		activecalendarcollections: {value:  (typeof globalActiveCalendarCollections!='undefined' && globalActiveCalendarCollections!=null) ? globalActiveCalendarCollections : new Array(), locked:false},
		activetodocollections: {value:  (typeof globalActiveTodoCollections!='undefined' && globalActiveTodoCollections!=null) ? globalActiveTodoCollections : new Array(), locked:false},
		loadedcalendarcollections: {value:  (typeof globalLoadedCalendarCollections!='undefined' && globalLoadedCalendarCollections!=null) ? globalLoadedCalendarCollections : new Array(), locked:false},
		loadedtodocollections: {value:  (typeof globalLoadedTodoCollections!='undefined' && globalLoadedTodoCollections!=null) ? globalLoadedTodoCollections : new Array(), locked:false},
		todolistfilterselected: {value:  (typeof globalTodoListFilterSelected!='undefined' && globalTodoListFilterSelected!=null && globalTodoListFilterSelected!='') ? globalTodoListFilterSelected : ['filterAction', 'filterProgress'], locked:false},
		activeview: {value:  (typeof globalActiveView!='undefined' && globalActiveView!=null && globalActiveView!='') ? globalActiveView : 'multiWeek', locked:false},
		islastactiveview: {value:  true, lockedlocked:false},
		calendarselected: {value:  (typeof globalCalendarSelected!='undefined' && globalCalendarSelected!=null && globalCalendarSelected!='') ? globalCalendarSelected : '', locked:false},
		todocalendarselected: {value:  (typeof globalTodoCalendarSelected!='undefined' && globalTodoCalendarSelected!=null && globalTodoCalendarSelected!='') ? globalTodoCalendarSelected : '', locked:false},
		timezone: {value:  (typeof globalTimeZone!='undefined' && globalTimeZone!=null && globalTimeZone!='') ? globalTimeZone : 'local', locked:false},
		islasttimezone: {value: true, locked:false},
		openformmode: {value:  (typeof globalOpenFormMode!='undefined' && globalOpenFormMode!=null && globalOpenFormMode!='') ? globalOpenFormMode : 'double', locked:false},
		calendarstartofbusiness: {value:  (typeof globalCalendarStartOfBusiness!='undefined' && globalCalendarStartOfBusiness!=null) ? globalCalendarStartOfBusiness : 8, locked:false},
		calendarendofbusiness: {value:  (typeof globalCalendarEndOfBusiness!='undefined' && globalCalendarEndOfBusiness!=null) ? globalCalendarEndOfBusiness : 17, locked:false},
		defaulteventduration: {value:  (typeof globalDefaultEventDuration!='undefined' && globalDefaultEventDuration!=null && globalDefaultEventDuration>=0) ? globalDefaultEventDuration : null, locked:false},
		ampmformat: {value:  (typeof globalAMPMFormat!='undefined' && globalAMPMFormat!=null) ? globalAMPMFormat : localization[globalInterfaceLanguage]._default_AMPM_format_, locked:false},
		timeformatagenda: {value:  (typeof globalTimeFormatAgenda!='undefined' && globalTimeFormatAgenda!=null && globalTimeFormatAgenda!='') ? globalTimeFormatAgenda : null, locked:false},
		timeformatbasic: {value:  (typeof globalTimeFormatBasic!='undefined' && globalTimeFormatBasic!=null && globalTimeFormatBasic!='') ? globalTimeFormatBasic : null, locked:false},
		displayhiddenevents: {value:  (typeof globalDisplayHiddenEvents!='undefined' && globalDisplayHiddenEvents!=null) ? globalDisplayHiddenEvents : false, locked:false},
		timezonesupport: {value:  (typeof globalTimeZoneSupport!='undefined' && globalTimeZoneSupport!=null) ? globalTimeZoneSupport : true, locked:false},
		timezonesenabled: {value:  (typeof globalTimeZonesEnabled!='undefined' && globalTimeZonesEnabled!=null && globalTimeZonesEnabled!='') ? globalTimeZonesEnabled : [], locked:false},
		showhiddenalarms: {value:  (typeof globalShowHiddenAlarms!='undefined' && globalShowHiddenAlarms!=null) ? globalShowHiddenAlarms : false, locked:false},
		ignorecompletedorcancelledalarms: {value: (typeof globalIgnoreCompletedOrCancelledAlarms!='undefined' && globalIgnoreCompletedOrCancelledAlarms!=null) ? globalIgnoreCompletedOrCancelledAlarms : true, locked:false},
		weekenddays: {value: (typeof globalWeekendDays!='undefined' && globalWeekendDays!=null && globalWeekendDays!='') ? globalWeekendDays : [0, 6], locked:false},
		eventstartpastlimit: {value:  (typeof globalEventStartPastLimit!='undefined' && globalEventStartPastLimit!=null) ? globalEventStartPastLimit : 3, locked:false},
		todopastlimit: {value:  (typeof globalTodoPastLimit!='undefined' && globalTodoPastLimit!=null) ? globalTodoPastLimit : 3, locked:false},
		eventstartfuturelimit: {value:  (typeof globalEventStartFutureLimit!='undefined' && globalEventStartFutureLimit!=null) ? globalEventStartFutureLimit : 3, locked:false},
		compatibility: {value: (typeof globalCompatibility!='undefined' && globalCompatibility!=null && globalCompatibility!='') ? globalCompatibility : {anniversaryOutputFormat: ['apple']}, locked:false},
		contactstorefn: {value: (typeof globalContactStoreFN!='undefined' && globalContactStoreFN!=null && globalContactStoreFN!='') ? globalContactStoreFN : ['prefix',' last',' middle',' first',' suffix'], locked:false},
		urihandlertel: {value: (typeof globalUriHandlerTel!='undefined' && globalUriHandlerTel!=null && globalUriHandlerTel!='') ? globalUriHandlerTel : 'tel:', locked:false},
		urihandleremail: {value: (typeof globalUriHandlerEmail!='undefined' && globalUriHandlerEmail!=null && globalUriHandlerEmail!='') ? globalUriHandlerEmail : 'mailto:', locked:false},
		urihandlerurl: {value: (typeof globalUriHandlerUrl!='undefined' && globalUriHandlerUrl!=null && globalUriHandlerUrl!='') ? globalUriHandlerUrl : 'http://', locked:false},
		urihandlerprofile: {value: (typeof globalUriHandlerProfile!='undefined' && globalUriHandlerProfile!=null && globalUriHandlerProfile!='') ? globalUriHandlerProfile : {'twitter': 'http://twitter.com/%u', 'facebook': 'http://www.facebook.com/%u', 'flickr': 'http://www.flickr.com/photos/%u', 'linkedin': 'http://www.linkedin.com/in/%u', 'myspace': 'http://www.myspace.com/%u', 'sinaweibo': 'http://weibo.com/n/%u'}, locked:false},
		addresscountryequivalence: {value: (typeof globalAddressCountryEquivalence!='undefined' && globalAddressCountryEquivalence!=null && globalAddressCountryEquivalence!='') ? globalAddressCountryEquivalence : [{country: 'de', regex: '^\\W*Deutschland\\W*$'}, {country: 'sk', regex: '^\\W*Slovensko\\W*$'}], locked:false},
		addressbookselected: {value:  (typeof globalAddressbookSelected!='undefined' && globalAddressbookSelected!=null && globalAddressbookSelected!='') ? globalAddressbookSelected : '', locked:false},
		collectiondisplay: {value:  (typeof globalCollectionDisplay!='undefined' && globalCollectionDisplay!=null && globalCollectionDisplay!='') ? globalCollectionDisplay : (
			(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies) ?
			[{label: '{Name}', value: {company: ['{Company}', ' [{Department}]'], personal: ['{LastName}', ' {MiddleName}', ' {FirstName}']}}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}] :
			[{label: '{Name}', value: ['{LastName}', ' {MiddleName}', ' {FirstName}']}, {label: '{Company} [{Department}]', value: ['{Company}', ' [{Department}]']}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}]
		), locked:false},
		collectionsort: {value:  (typeof globalCollectionSort!='undefined' && globalCollectionSort!=null && globalCollectionSort!='') ? globalCollectionSort : '', locked:false},
		defaultaddresscountry: {value:  (typeof globalDefaultAddressCountry!='undefined' && globalDefaultAddressCountry!=null && globalDefaultAddressCountry!='') ? globalDefaultAddressCountry :'us', locked:false},
		addresscountryfavorites: {value:  (typeof globalAddressCountryFavorites!='undefined' && globalAddressCountryFavorites!=null && globalAddressCountryFavorites!='') ? globalAddressCountryFavorites :[], locked:false},
		activeaddressbookcollections: {value:  (typeof globalActiveAddressbookCollections!='undefined' && globalActiveAddressbookCollections!=null) ? globalActiveAddressbookCollections : new Array(), locked:false},
		loadedaddressbookcollections: {value:  (typeof globalLoadedAddressbookCollections!='undefined' && globalLoadedAddressbookCollections!=null) ? globalLoadedAddressbookCollections : new Array(), locked:false}
	};
}

function transformToServer(inSettings)
{
	var serverSettings={};

	for(var prop in inSettings)
	{
		serverSettings[prop]=inSettings[prop].value;
	}

	return serverSettings;
}
var globalWindowFocus=true;
var globalLoginUsername='';
var globalLoginPassword='';
var isUserLogged=false;
var isDelegationLoaded=false;
var globalActiveApp='';
var globalAvailableAppsArray=new Array();
var globalEnableAppSwitch=true;
var globalAppName='InfCloud';
var globalVersion='0.13.1';
var globalBuildNo=1442928610;
var globalXMLCache=null;
var globalVersionCheckURL=(location.protocol=='file:' ? 'http:' : location.protocol)+'//www.inf-it.com/versioncheck/'+globalAppName+'/?v='+globalVersion;
var globalXClientHeader=globalAppName+' '+globalVersion+' (Inf-IT CalDAV/CardDAV Web Client)';
var globalResourceNumberCount=0;
var globalResourceNumber=0;
var globalResourceIntervalID=null;
var globalFirstLoadNextApp=false;
var globalObjectLoading=false;
var settingsLoaded=false;
var globalKBNavigationPaddingRate=0.2;
var globalParallelAjaxCallCardDAVEnabled=true;
var globalParallelAjaxCallCalDAVEnabled=true;
var globalCacheUpdateInterval=null;
var isIntegrated=false;
var SVG_select='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="19px" height="19px" viewBox="0 0 19 19" overflow="visible" enable-background="new 0 0 19 19" xml:space="preserve"><defs></defs><rect x="2" fill="#585858" width="17" height="19"/><polygon fill="#FFFFFF" points="14,7 10.5,13 7,7 "/><rect fill="#FFFFFF" width="2" height="19"/></svg>';
var SVG_select_inv='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="19px" height="19px" viewBox="0 0 19 19" overflow="visible" enable-background="new 0 0 19 19" xml:space="preserve"><defs></defs><rect x="2" fill="#585858" width="17" height="19"/><polygon fill="#FFFFFF" points="14,13 10.5,7 7,13"/><rect fill="#FFFFFF" width="2" height="19"/></svg>';
var SVG_select_b='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="19px" height="19px" viewBox="0 0 19 19" overflow="visible" enable-background="new 0 0 19 19" xml:space="preserve"><defs></defs><rect x="2" fill="#585858" width="17" height="19"/><polygon fill="#FFFFFF" points="14,7 10.5,13 7,7 "/><rect fill="#F0F0F0" width="2" height="19"/></svg>';
var SVG_select_login='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="19px" height="28px" viewBox="0 0 19 28" overflow="visible" enable-background="new 0 0 19 28" xml:space="preserve"><defs></defs><rect fill="#FFFFFF" width="19" height="28"/></svg>';
var SVG_select_dis='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="22px" height="19px" viewBox="0 0 22 19" overflow="visible" enable-background="new 0 0 22 19" xml:space="preserve"><defs></defs><rect fill="#FFFFFF" width="22" height="19"/></svg>';
var globalDefinedSettings = new Array();
var globalLoadedPrincipals = new Array();
var globalEnableAllResourceSync = true;
if(typeof isSettingsAvaible == 'undefined')
	var globalPreviousSupportedSettings = ['activecalendarcollections','activetodocollections', 'activeaddressbookcollections','todolistfilterselected','activeview','defaultactiveapp','calendarselected', 'todocalendarselected','addressbookselected','timezone', 'loadedtodocollections', 'loadedcalendarcollections', 'loadedaddressbookcollections', 'version'];
var globalSettingsSaving = '';
var globalFirstHideLoader = true;
var globalLoadedCollectionsNumber = 0;
var globalLoadedCollectionsCount = 0;
var ignoreServerSettings=false;
var globalPreventLogoutSync=false;
var globalEmailAddress='';
var globalSettingsVersion=3;
var globalSyncSettingsSave=false;

// Timepicker hack (prevent IE to re-open the datepicker on date click + focus)
var globalTmpTimePickerHackTime=new Object();

function isAvaible(app)
{
	return globalAvailableAppsArray.indexOf(app)!=-1
}

function loadAllResources()
{
	if(globalResourceIntervalID==null)
		netFindResource(globalAccountSettings[0], 0, true, 0);
}

function getAccount(accountUID)
{
	// find the original settings for the resource and user
	var tmp=accountUID.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)','i'));
	var resource_href=tmp[1]+tmp[3]+tmp[4];
	var resource_user=tmp[2];

	for(var i=0;i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href==resource_href && globalAccountSettings[i].userAuth.userName==resource_user)
			resourceSettings=globalAccountSettings[i];
	return resourceSettings;
}

function checkForUnloadedResources()
{
	var rex=new RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)', 'i');

	for(var i=globalLoadedPrincipals.length-1; i>=0;i--)
	{
		var resourceCounter = 0;
		if(isAvaible('CardDavMATE'))
			for(var j=0; j<globalResourceCardDAVList.collections.length;j++)
				if(globalResourceCardDAVList.collections[j].uid!=undefined&&globalResourceCardDAVList.collections[j].makeLoaded)
				{
					var tmp=globalResourceCardDAVList.collections[j].accountUID.match(rex);
					var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
					if(globalLoadedPrincipals[i]==resourceCalDAV_href)
						resourceCounter++;
				}

		if(isAvaible('CalDavZAP'))
		{
			for(var j=0; j<globalResourceCalDAVList.collections.length;j++)
				if(globalResourceCalDAVList.collections[j].uid!=undefined&&globalResourceCalDAVList.collections[j].makeLoaded)
				{
					var tmp=globalResourceCalDAVList.collections[j].accountUID.match(rex);
					var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
					if(globalLoadedPrincipals[i]==resourceCalDAV_href)
						resourceCounter++;
				}

			for(var j=0; j<globalResourceCalDAVList.TodoCollections.length;j++)
				if(globalResourceCalDAVList.TodoCollections[j].uid!=undefined&&globalResourceCalDAVList.TodoCollections[j].makeLoaded)
				{
					var tmp=globalResourceCalDAVList.TodoCollections[j].accountUID.match(rex);
					var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
					if(globalLoadedPrincipals[i]==resourceCalDAV_href)
						resourceCounter++;
				}
		}
		if(resourceCounter==0)
			globalLoadedPrincipals.splice(i,1);
	}
}

function reloadResources(dontSaveSettings, loadArray)
{
	if((isAvaible('CardDavMATE')&&(globalCardDAVInitLoad||globalCardDAVResourceSync)) || (isAvaible('CalDavZAP')&&(globalCalDAVInitLoad||globalCalDAVResourceSync))
	|| (isAvaible('Projects')&&!isProjectsLoaded) || (isAvaible('Settings')&&(!isSettingsLoaded || (globalSettingsSaving!=''&&!dontSaveSettings))) || (isAvaible('CalDavZAP')&&(globalLimitLoading!='' || globalLimitTodoLoading!='')))
		return false;
	if(globalWindowFocus==false)
		return false;
	globalCardDAVResourceSync=true;
	globalCalDAVResourceSync=true;
	if(isAvaible('CalDavZAP'))
	{
		globalCalDAVResourceSync = true;
		globalToday.setHours(0);
		globalToday.setMinutes(0);
		globalToday.setSeconds(0);
		globalToday.setMilliseconds(0);

		var currentToday=new Date();
		currentToday.setHours(0);
		currentToday.setMinutes(0);
		currentToday.setSeconds(0);
		currentToday.setMilliseconds(0);
		if(currentToday.getTime()!=globalToday.getTime())
		{
			if(isAvaible('CalDavZAP'))
				$('.date').datepicker('refresh');
			if(isAvaible('CardDavMATE'))
				$('#vCardEditor').find('input[data-type^="date_"]').datepicker('refresh');
			if(isAvaible('Projects'))
				$('.project_date').datepicker('refresh');
			$('#calendar').fullCalendar('updateToday');
			$('#calendar').fullCalendar('gotoDate', currentToday);
			$('#todoList').fullCalendar('gotoDate', currentToday);
			if(currentToday.getTime()>globalToday.getTime())
			{
				getNextMonths($('#calendar').fullCalendar('getView').end);
				getNextMonthsTodo();
			}
			else //support for timezone with backward time flow
			{
				getPrevMonths($('#calendar').fullCalendar('getView').start);
				getPrevMonthsTodo();
			}
			globalToday=currentToday;
		}
	}
	checkForUnloadedResources();
	if(!globalEnableAllResourceSync&&(typeof loadArray=='undefined' || loadArray==null))
		netFindResource(globalAccountSettings[0], 0, false, 0, globalLoadedPrincipals);
	else
		netFindResource(globalAccountSettings[0], 0, false, 0, loadArray);
}
function ifLoadCollections()
{
	if((isAvaible('CardDavMATE') && (globalCardDAVInitLoad || globalCardDAVResourceSync)) || (isAvaible('CalDavZAP') && (globalCalDAVInitLoad || globalCalDAVResourceSync)))
		return false;

	var changeCounter = 0;
	if(isAvaible('CardDavMATE'))
		for(var i=0; i<globalResourceCardDAVList.collections.length;i++)
			if(globalResourceCardDAVList.collections[i].uid!=undefined && globalResourceCardDAVList.collections[i].someChanged)
				changeCounter++;

	if(isAvaible('CalDavZAP'))
	{
		for(var i=0; i<globalResourceCalDAVList.collections.length;i++)
			if(globalResourceCalDAVList.collections[i].uid!=undefined && globalResourceCalDAVList.collections[i].someChanged)
				changeCounter++;

		for(var i=0; i<globalResourceCalDAVList.TodoCollections.length;i++)
			if(globalResourceCalDAVList.TodoCollections[i].uid!=undefined && globalResourceCalDAVList.TodoCollections[i].someChanged)
				changeCounter++;
	}

	if(changeCounter>0 || globalSettingsSaving!='')
		loadNextApplication(false);
}

function bindColorPickerClick(newElement)
{
	newElement.click(function(event){
		var collectionType=null;
		var resourceSelectedClass=null;
		var resourceItems=null;

		if(newElement.parent().hasClass('resourceCalDAV_item'))
		{
			if(globalEventCollectionsLoading)
				return false;
			collectionType='event';
			resourceSelectedClass='resourceCalDAV_item_selected';
			resourceItems=newElement.parent().siblings('.resourceCalDAV_item_selected');
		}
		else if(newElement.parent().hasClass('resourceCalDAVTODO_item'))
		{
			if(globalTodoCollectionsLoading)
				return false;
			collectionType='todo';
			resourceSelectedClass='resourceCalDAV_item_selected';
			resourceItems=newElement.parent().siblings('.resourceCalDAV_item_selected');
		}
		else if(newElement.hasClass('resourceCardDAVColor'))
		{
			if(globalAddressbookCollectionsLoading)
				return false;
			collectionType='addressbook';
			resourceSelectedClass='resourceCardDAV_selected';
			resourceItems=newElement.parent().parent().siblings().find('.resourceCardDAV_selected');
		}

		var showInput = event.shiftKey;
		var colorpicker=$(this).siblings('.colorPicker');

		if(!$(this).hasClass('hasColorpicker'))
		{
			$(this).addClass('hasColorpicker');
			colorpicker.spectrum({
				chooseText: localization[globalInterfaceLanguage].buttonSave,
				cancelText: localization[globalInterfaceLanguage].buttonCancel,
				color: newElement.css('background-color'),
				showInput: showInput,
				preferredFormat: 'hex6',
				move: function(color)
				{
					newElement.css('background', color);
				},
				hide: function(color)
				{
					if(newElement.css('background-color') != colorpicker.spectrum('get').toRgbString())
						newElement.css('background', colorpicker.spectrum('get').toRgbString());
				},
				change: function(color)
				{
					newElement.css('background', color);
					if(collectionType=='event')
					{
						var coll = globalResourceCalDAVList.getEventCollectionByUID($(this).parent().attr('data-id'));
						netSaveProperty(coll, (typeof globalCalendarColorPropertyXmlns!='undefined'&&globalCalendarColorPropertyXmlns!=null&&globalCalendarColorPropertyXmlns!='' ? globalCalendarColorPropertyXmlns : 'http://apple.com/ns/ical/'), 'calendar-color', color.toHexString())
					}
					else if(collectionType=='todo')
					{
						var coll = globalResourceCalDAVList.getTodoCollectionByUID($(this).parent().attr('data-id'));
						netSaveProperty(coll, (typeof globalCalendarColorPropertyXmlns!='undefined'&&globalCalendarColorPropertyXmlns!=null&&globalCalendarColorPropertyXmlns!='' ? globalCalendarColorPropertyXmlns : 'http://apple.com/ns/ical/'), 'calendar-color', color.toHexString())
					}
					else if(collectionType=='addressbook')
					{
						var coll = globalResourceCardDAVList.getCollectionByUID($(this).parent().attr('data-id'));
						netSaveProperty(coll, (typeof globalAddrColorPropertyXmlns!='undefined'&&globalAddrColorPropertyXmlns!=null&&globalAddrColorPropertyXmlns!='' ? globalAddrColorPropertyXmlns : 'http://inf-it.com/ns/ab/'),  'addressbook-color', color.toHexString())
					}
				}
			});
		}
		else if(showInput!=colorpicker.spectrum('option', 'showInput'))
			colorpicker.spectrum('option', 'showInput',showInput);

		var container = colorpicker.spectrum('container');
		if(container.is(':visible')) {
			colorpicker.spectrum('hide');
		}
		else {
			var offset=$(this).offset();
			colorpicker.spectrum('show');

			if(event.pageY<$(window).height()/2) {
				offset.top+=$(this).outerHeight();
				container.removeClass('sp-inverse');
			}
			else {
				offset.top-=container.outerHeight();
				container.addClass('sp-inverse');
			}
			container.offset(offset);
		}

		resourceItems.removeClass(resourceSelectedClass);
		newElement.parent().addClass(resourceSelectedClass);

		return false;
	});
}

function loadNextApplication(forceLoad)
{
	if(!globalFirstLoadNextApp)
	{
		if(isAvaible('CardDavMATE'))
			setAddressbookNumber();
		if(isAvaible('CalDavZAP'))
			setCalendarNumber(true);
		globalFirstLoadNextApp=true;
	}
	if(isAvaible('CardDavMATE') && !globalCardDAVCollectionSync && globalResourceCardDAVList.collections.length>0)
	{
		globalCardDAVCollectionSync=true;
		CardDAVnetLoadCollection(globalResourceCardDAVList.collections[0], forceLoad, false, null, 0, globalResourceCardDAVList.collections,true);
	}
	else if(isAvaible('CalDavZAP') && !globalCalDAVCollectionSync && globalResourceCalDAVList.collections.length>0)
	{
		globalCalDAVCollectionSync=true;
		CalDAVnetLoadCollection(globalResourceCalDAVList.collections[0], forceLoad, true, 0, globalResourceCalDAVList.collections);
	}
	else if(isAvaible('Projects') && !globalProjectSync && !isProjectsLoaded && getLoggedUser()!=null)
	{
		$('#MainLoaderInner').html('Loading projects');
		globalProjectSync=true;
		if(typeof globalCRMSettings != 'undefined')
			netLoadXSLT(globalCRMSettings.XSLTHref);
		else
		{
			console.log("Error: globalCRMSettings is not defined");
			loadNextApplication(false);
		}
	}
	else if(isAvaible('Reports') && !globalReportsSync && !isReportsLoaded && getLoggedUser()!=null)
	{
		$('#MainLoaderInner').html('Loading Reports');
		globalReportsSync=true;
		if(typeof globalCRMSettings != 'undefined')
			netLoadReportList(globalCRMSettings);
		else
		{
			console.log("Error: globalCRMSettings is not defined");
			loadNextApplication(false);
		}
	}
	else if(isAvaible('Settings') && !globalSettingsSync && !isSettingsLoaded && getLoggedUser()!=null)
	{
		globalSettingsSync = true;
		if(!isSettingsLoaded)
			loadNextApplication(false);
		if($('#ResourceSettingsList').children('.resourceSettings_item').length)
			$('#ResourceSettingsList').children().eq(0).trigger('click');
	}
	else
	{
		if((isAvaible('CalDavZAP') && !isCalDAVLoaded) || (isAvaible('CardDavMATE') && !isCardDAVLoaded))
			$('#MainLoader').fadeOut(1200, function(){$('#MainLoader').css('left','50px');});
		if(isAvaible('CardDavMATE'))
		{
			globalCardDAVCollectionSync=false;
			if(!isCardDAVLoaded)
				isCardDAVLoaded=true;
		}
		if(isAvaible('CalDavZAP'))
		{
			globalCalDAVCollectionSync=false;
			if(!isCalDAVLoaded)
				isCalDAVLoaded=true;
		}
		if(isAvaible('Projects'))
		{
			globalProjectSync=false;
			isProjectsLoaded = true;
		}
		if(isAvaible('Reports'))
		{
			globalReportsSync=false;
			isReportsLoaded = true;
		}
		if(isAvaible('Settings'))
		{
			globalSettingsSync=false;
			isSettingsLoaded = true;
		}
	}
}

function checkForApplication(inputApp)
{
	if(!globalEnableAppSwitch || globalObjectLoading)
		return false;

	globalEnableAppSwitch=false;
	globalActiveApp=inputApp;

	var inputID = 'System'+inputApp;
	$('.System').not('#'+inputID).each(function(){
		$(this).animate({opacity : 0}, 666, function(){
			/* XXX - System display:none changes
			if($(this).attr('id').indexOf('CalDav')==-1)
				$(this).css('display','none');
			else*/
				$(this).css('visibility','hidden');
		});
	});

	/* XXX - System display:none changes
	if(inputID.indexOf('CalDav')==-1)
		$('#'+inputID).css('display','block').animate({opacity : 1}, 666, function(){globalEnableAppSwitch=true;});
	else*/
		$('#'+inputID).css('visibility','visible').animate({opacity : 1}, 666, function(){globalEnableAppSwitch=true;});
}

function getLoggedUser()
{
	for(var i=0; i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href.indexOf(globalLoginUsername)!=-1)
			return globalAccountSettings[i];
	return globalAccountSettings[0];
}

function login()
{
	$('#LoginLoader').fadeTo(1200, 1, function(){
		globalLoginUsername=$('#LoginPage').find('[data-type="system_username"]').val();
		globalLoginPassword=$('#LoginPage').find('[data-type="system_password"]').val();
		loadConfig();
	});
}

function logout(forceLogout)
{
	if((typeof forceLogout=='undefined' || forceLogout==null ) && (
		(isAvaible('CardDavMATE') && (!isCardDAVLoaded || globalCardDAVResourceSync)) || 
		(isAvaible('CalDavZAP') && (!isCalDAVLoaded || globalCalDAVResourceSync)) || 
		(isAvaible('Projects') && !isProjectsLoaded) || 
		(isAvaible('Settings') && (!isSettingsLoaded || (globalSettingsSaving!='' && !dontSaveSettings))) || 
		(isAvaible('CalDavZAP') && (globalLimitLoading!='' || globalLimitTodoLoading!=''))
	))
	{
		globalPreventLogoutSync=true;
		return false;
	}
	clearInterval(globalResourceIntervalID);
	if(globalFirstLoadNextApp)
		globalFirstLoadNextApp=false;
	settingsLoaded=false;
	ignoreServerSettings=false;
	//save settings
	checkBeforeClose(false);
	globalResourceIntervalID=null;
	globalLoginUsername='';
	globalLoginPassword='';
	globalXMLCache=null;
	globalResourceNumber=0;
	globalResourceNumberCount=0;
	globalLoadedPrincipals=new Array();
	globalEmailAddress='';
	globalPreventLogoutSync=false;
	globalSyncSettingsSave=false;

	$(document.documentElement).unbind();
	// reset page title
	var tmpMatch = document.title.match('^(.*) \\[.*\\]$');
	if(tmpMatch!=null)
		document.title = tmpMatch[1];

	$('#LoginPage').fadeTo(2000, 1, function(){
		if(typeof isCalDAVLoaded!='undefined' && isCalDAVLoaded)
		{
			logoutCalDAV();
			isCalDAVLoaded=false;
		}

		if(typeof isCardDAVLoaded!='undefined' && isCardDAVLoaded)
		{
			logoutCardDAV();
			isCardDAVLoaded=false;
		}
		if(typeof isProjectsLoaded!='undefined' && isProjectsLoaded)
		{
			logoutProjects();
			isProjectsLoaded = false;
		}
		if(typeof isReportsLoaded!='undefined' && isReportsLoaded)
		{
			logoutReports();
			isReportsLoaded = false;
		}
		if(typeof isSettingsLoaded!='undefined' && isSettingsLoaded)
		{
			logoutSettings();
			isSettingsLoaded = false;
		}

		for(var i=globalAccountSettings.length-1;i>=0;i--)
			if(globalAccountSettings[i].type=='network')
				globalAccountSettings.splice(i, 1);

		if(typeof globalDemoMode=='undefined')
		{
			$('[data-type="system_username"]').val('').change();
			$('[data-type="system_password"]').val('').change();
		}

		$('.integration_d').hide();

		isUserLogged=false;

		if(globalSettings.defaultactiveapp.value==null)
		{
			if(isAvaible('CalDavZAP'))
				globalActiveApp='CalDavZAP';
			else if(isAvaible('CardDavMATE'))
				globalActiveApp='CardDavMATE';
		}
		else
			globalActiveApp=globalSettings.defaultactiveapp.value;

		resetSettings();
		if(isAvaible('CardDavMATE'))
			mainCardDAV();
		if(isAvaible('CalDavZAP'))
			mainCalDAV();
		if(isAvaible('Settings'))
			mainSettings();
		if(isAvaible('Projects'))
			mainProjects();
		if(isAvaible('Reports'))
			mainReports();
		init();
	});
}

function init()
{
	// browser check
	if(($.browser.msie && parseInt($.browser.version, 10)<9) || $.browser.opera)
		$('#login_message').css('display','').text(localization[globalInterfaceLanguage].unsupportedBrowser);

	if(typeof globalDemoMode!='undefined')
	{
		if(typeof globalDemoMode.userName!=undefined)
			$('[data-type="system_username"]').val(globalDemoMode.userName).change();
		if(typeof globalDemoMode.userPassword!=undefined)
			$('[data-type="system_password"]').val(globalDemoMode.userPassword).change();
	}

	loadConfig();
}

function run()
{
	isUserLogged=true;
	window.onfocus=function(){globalWindowFocus=true;}
	window.onblur=function(){if(globalSettings.backgroundsync.value==false) globalWindowFocus=false;}
	$('#LoginPage').fadeOut(2000);

	if(typeof globalAccountSettings=='undefined')
	{
		console.log('Error: \'no account configured\': see config.js!');
		return false;
	}

	if(typeof globalNewVersionNotifyUsers=='undefined' || globalNewVersionNotifyUsers!=null)
		netVersionCheck();

	document.title+=' ['+globalAccountSettings[0].userAuth.userName+']';
	// Automatically detect crossDomain settings
	var detectedHref=location.protocol+'//'+location.hostname+(location.port ? ':'+location.port : '');
	for(var i=0;i<globalAccountSettings.length;i++)
	{
		if(globalAccountSettings[i].crossDomain==undefined || typeof globalAccountSettings[i].crossDomain!='boolean')
		{
			if(globalAccountSettings[i].href.indexOf(detectedHref)==0)
				globalAccountSettings[i].crossDomain=false;
			else
				globalAccountSettings[i].crossDomain=true;

			console.log("Info: [userAccount: '"+globalAccountSettings[i].href.replace('\/\/', '//'+globalAccountSettings[i].userAuth.userName+'@')+"']: crossDomain set to: '"+(globalAccountSettings[i].crossDomain==true ? 'true' : 'false')+"'");
		}
	}

	if(typeof globalAvailableAppsArray!='undefined' && globalAvailableAppsArray!=null && globalAvailableAppsArray.length>1) {
		// show integration banner
		$('.integration_d').css('display', 'block');

		// show app buttons for available apps only
		if(globalAvailableAppsArray.indexOf('CalDavZAP')!=-1)
			$('#intCaldav').attr('title',localization[globalInterfaceLanguage].txtCalendars).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
		if(globalAvailableAppsArray.indexOf('CalDavTODO')!=-1)
			$('#intCaldavTodo').attr('title',localization[globalInterfaceLanguage].txtTodos).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
		if(globalAvailableAppsArray.indexOf('CardDavMATE')!=-1)
			$('#intCarddav').attr('title',localization[globalInterfaceLanguage].txtContacts).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
		if(globalAvailableAppsArray.indexOf('Projects')!=-1)
			$('#intProjects').attr('title',localization[globalInterfaceLanguage].txtProjects).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
		if(globalAvailableAppsArray.indexOf('Reports')!=-1)
			$('#intReports').attr('title',localization[globalInterfaceLanguage].txtReports).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
		if(globalAvailableAppsArray.indexOf('Settings')!=-1)
			$('#intSettings').attr('title',localization[globalInterfaceLanguage].txtSettings).css('display', 'block').find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);

		// show the refresh button
		if(typeof globalEnableRefresh==='boolean' && globalEnableRefresh && (globalAvailableAppsArray.indexOf('CalDavZAP')!=-1 || globalAvailableAppsArray.indexOf('CalDavTODO')!=-1 || globalAvailableAppsArray.indexOf('CardDavMATE')!=-1)) {
			$('#intRefresh').attr('title',localization[globalInterfaceLanguage].txtRefresh).find('.int_error').attr('alt',localization[globalInterfaceLanguage].txtError);
			$('#intRefresh').prev().addBack().css('display', 'block');
		}
	}

	$('#cacheDialogText').text(localization[globalInterfaceLanguage].txtCacheText);
	$('#cacheDialogButton').attr('value',localization[globalInterfaceLanguage].txtCacheButton);
}

function loadConfig()
{
	if(isUserLogged)// !!!!!! kedy moze toto nastat? nexapem ...
		return false;

	var configLoaded=true;
	// Automatically detect crossDomain settings
	var detectedHref=location.protocol+'//'+location.hostname+(location.port ? ':'+location.port : '');

	// check username and password against the server and create config from globalNetworkCheckSettings
	if(typeof globalNetworkCheckSettings!='undefined' && globalNetworkCheckSettings!=null)
	{
		if(globalLoginUsername=='' || globalLoginPassword=='')
		{
			$('#LoginPage').fadeTo(500, 1, function(){if(typeof globalDemoMode=='undefined') $('[data-type="system_username"]').focus()});
			$('#LoginLoader').fadeOut(1200);
			return false;
		}
		else
		{
			if(globalNetworkCheckSettings.crossDomain==undefined || typeof globalNetworkCheckSettings.crossDomain!='boolean')
			{
				if(globalNetworkCheckSettings.href.indexOf(detectedHref)==0)
					globalNetworkCheckSettings.crossDomain=false;
				else
					globalNetworkCheckSettings.crossDomain=true;

				console.log("Info: [globalNetworkCheckSettings: '"+globalNetworkCheckSettings.href+"']: crossDomain set to: '"+(globalNetworkCheckSettings.crossDomain==true ? 'true' : 'false')+"'");
			}

// !!!! preco sa riesi s logout buttonom prave tu?
			// show the logout button
			if(typeof globalAvailableAppsArray!='undefined' && globalAvailableAppsArray!=null && globalAvailableAppsArray.length>1) {
				$('#intLogout').prev().addBack().css('display', 'block');
				$('#intLogout').attr('title',localization[globalInterfaceLanguage].altLogout);
			}
			else {
				$('#Logout').css('display', 'block');
			}

			netCheckAndCreateConfiguration(globalNetworkCheckSettings);
			return true;
		}
	}

	// load the configuration XML(s) from the network
	if(typeof globalNetworkAccountSettings!='undefined' && globalNetworkAccountSettings!=null)
	{
		if(globalLoginUsername=='' || globalLoginPassword=='')
		{
			$('#LoginPage').fadeTo(500, 1, function(){if(typeof globalDemoMode=='undefined') $('[data-type="system_username"]').focus()});
			$('#LoginLoader').fadeOut(1200);
			return false;
		}
		else
		{
			if(globalNetworkAccountSettings.crossDomain==undefined || typeof globalNetworkAccountSettings.crossDomain!='boolean')
			{
				if(globalNetworkAccountSettings.href.indexOf(detectedHref)==0)
					globalNetworkAccountSettings.crossDomain=false;
				else
					globalNetworkAccountSettings.crossDomain=true;

				console.log("Info: [globalNetworkAccountSettings: '"+globalNetworkAccountSettings.href+"']: crossDomain set to: '"+(globalNetworkAccountSettings.crossDomain==true ? 'true' : 'false')+"'");
			}
// !!!! preco sa riesi s logout buttonom prave tu?
			// show the logout button
			if(typeof globalAvailableAppsArray!='undefined' && globalAvailableAppsArray!=null && globalAvailableAppsArray.length>1) {
				$('#intLogout').prev().addBack().css('display', 'block');
				$('#intLogout').attr('title',localization[globalInterfaceLanguage].altLogout);
			}
			else {
				$('#Logout').css('display', 'block');
			}

			netLoadConfiguration(globalNetworkAccountSettings);
			return true;
		}
	}

	if((typeof globalNetworkAccountSettings=='undefined' || globalNetworkAccountSettings==null) && (typeof globalNetworkCheckSettings=='undefined' || globalNetworkCheckSettings==null) && (typeof globalAccountSettings!='undefined' && globalAccountSettings!=null) && globalAccountSettings.length>0)
	{
		var delegCount=0, delegIndex=0;
		if(!isDelegationLoaded)
		{
			for(var i=0; i<globalAccountSettings.length; i++)
				if((typeof globalAccountSettings[i].delegation=='boolean' && globalAccountSettings[i].delegation) || (globalAccountSettings[i].delegation instanceof Array && globalAccountSettings[i].delegation.length>0))
					delegIndex=i;
			for(var i=0; i<globalAccountSettings.length; i++)
				if((typeof globalAccountSettings[i].delegation=='boolean' && globalAccountSettings[i].delegation) || (globalAccountSettings[i].delegation instanceof Array && globalAccountSettings[i].delegation.length>0))
				{
					delegCount++;
					DAVresourceDelegation(globalAccountSettings[i], i, delegIndex);
				}
			if(delegCount>0)
				isDelegationLoaded = true;
		}
		if(delegCount==0 && !isDelegationLoaded)
		{
			// start the client
			if(isAvaible('CardDavMATE'))
				runCardDAV();
			if(isAvaible('CalDavZAP'))
				runCalDAV();
			if(isAvaible('Projects'))
				runProjects();
			if(isAvaible('Settings'))
				runSettings();

			globalResourceNumber=globalAccountSettings.length;
			loadAllResources();
		}
	}
}

function globalMain()
{
	for(var prop in globalSettings)
		globalDefinedSettings.push(prop);

	if(typeof globalEnabledApps=='undefined' || globalEnabledApps==null)
	{
		if(typeof isCalDAVAvaible!='undefined' && isCalDAVAvaible!=null && isCalDAVAvaible)
		{
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CalDavZAP';
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CalDavTODO';
		}
		if(typeof isCardDAVAvaible!='undefined' && isCardDAVAvaible!=null && isCardDAVAvaible)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CardDavMATE';
		if(typeof isSettingsAvaible!='undefined' && isSettingsAvaible!=null && isSettingsAvaible)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Settings';
		if(typeof isProjectsAvaible!='undefined' && isProjectsAvaible!=null && isProjectsAvaible)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Projects';
		if(typeof isReportsAvaible!='undefined' && isReportsAvaible!=null && isReportsAvaible)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Reports';
	}
	else
	{
		if(typeof isCalDAVAvaible!='undefined' && isCalDAVAvaible!=null && isCalDAVAvaible && (globalEnabledApps.indexOf('CalDavZAP')!=-1 || globalEnabledApps.indexOf('CalDavTODO')!=-1 ))
		{
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CalDavZAP';
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CalDavTODO';
		}
		if(typeof isCardDAVAvaible!='undefined' && isCardDAVAvaible!=null && isCardDAVAvaible && globalEnabledApps.indexOf('CardDavMATE')!=-1)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='CardDavMATE';
		if(typeof isSettingsAvaible!='undefined' && isSettingsAvaible!=null && isSettingsAvaible && globalEnabledApps.indexOf('Settings')!=-1)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Settings';
		if(typeof isProjectsAvaible!='undefined' && isProjectsAvaible!=null && isProjectsAvaible && globalEnabledApps.indexOf('Projects')!=-1)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Projects';
		if(typeof isReportsAvaible!='undefined' && isReportsAvaible!=null && isReportsAvaible)
			globalAvailableAppsArray[globalAvailableAppsArray.length]='Reports';
	}

	if(globalAvailableAppsArray.length>1)
		isIntegrated=true;

	if(globalSettings.defaultactiveapp.value==null)
	{
		if(isAvaible('CardDavMATE'))
			globalActiveApp='CardDavMATE';
		else if(isAvaible('CalDavZAP'))
			globalActiveApp='CalDavZAP';
	}
	else
		globalActiveApp=globalSettings.defaultactiveapp.value;

	if(isAvaible('CardDavMATE'))
	{
		// Modify available inputs before making additional changes to vCard form
		if(typeof globalDisabledContactAttributes!='undefined' && globalDisabledContactAttributes instanceof Array)
			for(var i=0;i<globalDisabledContactAttributes.length;i++)
				$('#vCardTemplate').find('[data-attr-name="'+jqueryEscapeSelector(globalDisabledContactAttributes[i])+'"]').remove();

		// hook for vCard template extension
		if(typeof(globalContactsExtInitMain)=='function')
			globalContactsExtInitMain($('#vCardTemplate'));
	}

	/*************************** BAD HACKS SECTION ***************************/
	// here we fix the cross OS/cross broser problems (unfixable in pure CSS)
	if($.browser.webkit && !!window.chrome)	/* Chrome */
	{
		if(navigator.platform.toLowerCase().indexOf('win')==0)	/* Windows version */
		{
			$('#LoginPage, #vCardTemplate, #event_details_template, #todo_details_template, #EditorBoxSettings').find('input').css('text-indent', '2px');
			$('#LoginPage, #vCardTemplate, #event_details_template, #todo_details_template, #EditorBoxSettings').find('select').css({'padding-left': '0px', 'padding-right': '13px'});
		}
		else	/* non-Windows version */
			$('#LoginPage, #vCardTemplate, #event_details_template, #todo_details_template, #EditorBoxSettings').find('input').css('text-indent', '1px');
	}
	else if($.browser.safari)
	{
		$('#LoginPage, #vCardTemplate, #event_details_template, #todo_details_template, #EditorBoxSettings').find('textarea').addClass('safari_hack');
		$('#LoginPage, #vCardTemplate, #event_details_template, #todo_details_template, #EditorBoxSettings').find('input').addClass('safari_hack');
	}
	else if($.browser.msie)	/* IE */
	{
		if(parseInt($.browser.version, 10)==10)	/* IE 10 (because there are no more conditional comments) */
		{
			$('select').css({'padding-top': '1px', 'padding-left': '0px', 'padding-right': '0px'});
			$('textarea').css('padding-top', '3px');
			$('input[type=button]').css('padding-top', '2px');
		}

		// ADD SVG to login screen
		var newSVG=$(SVG_select_login).attr('data-type', 'select_icon').css({'pointer-events': 'none', 'z-index': '1', 'display': 'inline', 'margin-left': '-19px', 'vertical-align': 'top', 'background-color': '#ffffff'});	// background-color = stupid IE9 bug
		$('#Login').find('select[data-type="language"]').after($($('<div>').append($(newSVG).clone()).html()));
	}
	else if($.browser.mozilla)
	{
		// ADD SVG to login screen
		var newSVG=$(SVG_select_login).attr('data-type', 'select_icon').css({'pointer-events': 'none', 'z-index': '1', 'display': 'inline', 'margin-left': '-19px', 'vertical-align': 'top', 'background-color': '#ffffff'});	// background-color = stupid IE9 bug
		$('#Login').find('select[data-type="language"]').after($($('<div>').append($(newSVG).clone()).html()));
	}
	/*************************** END OF BAD HACKS SECTION ***************************/

	/* language selector */
	var lang_num=0;
	var language_option=$('#Login').find('[data-type="language"]').find('option');
	$('#Login').find('[data-type="language"]').html('');

	if(typeof globalInterfaceCustomLanguages!='undefined' && globalInterfaceCustomLanguages.length!=undefined && globalInterfaceCustomLanguages.length>0)
	{
		for(var i=0; i<globalInterfaceCustomLanguages.length; i++)
			if(localization[globalInterfaceCustomLanguages[i]]!=undefined)
			{
				var tmp=language_option;
				tmp.attr('data-type',globalInterfaceCustomLanguages[i]);
				tmp.text(localization[globalInterfaceCustomLanguages[i]]['_name_']);
				$('#Login').find('[data-type="language"]').append(tmp.clone());
				lang_num++;
			}
	}

	if(lang_num==0)	// no language option, use the default (all languages from localization.js)
		for(var loc in localization)
		{
			var tmp=language_option;
			tmp.attr('data-type',loc);
			tmp.text(localization[loc]['_name_']);	// translation
			$('#Login').find('[data-type="language"]').append(tmp.clone());
		}

	// select the globalInterfaceLanguage in the interface
	$('[data-type="language"]').find('[data-type='+globalInterfaceLanguage+']').prop('selected',true);

	// set login screen logo
	if(isAvaible('CalDavZAP') && !isAvaible('CardDavMATE'))
	{
		$('[data-size="login_logo"]').find('img').attr('src', "images/cdz_logo.svg");
		$('#LoginPage').find('.footer').text('CalDavZAP - the open source CalDAV web client');
	}
	else if(isAvaible('CardDavMATE') && !isAvaible('CalDavZAP'))
	{
		$('[data-size="login_logo"]').find('img').attr('src', "images/cdm_logo.svg");
		$('#LoginPage').find('.footer').text('CardDavMATE - the open source CardDAV web client');
	}
	else
	{
		$('#Login').css('margin-top', '41px');
		$('[data-size="login_logo"]').find('img').attr('src', "images/infcloud_logo.svg");
		$('#LoginPage').find('.footer').text('InfCloud - the open source CalDAV/CardDAV web client');
	}
	$('#LoginPage').find('.footer').attr('title', globalVersion);

	if(isAvaible('CardDavMATE'))
		globalMainCardDAV();
	if(isAvaible('CalDavZAP'))
		globalMainCalDAV();
	if(isAvaible('Projects'))
		globalMainProjects();
	if(isAvaible('Reports'))
		globalMainReports();
	if(isAvaible('Settings'))
		globalMainSettings();

	if(isAvaible('CardDavMATE'))
		mainCardDAV();
	if(isAvaible('CalDavZAP'))
		mainCalDAV();
	if(isAvaible('Projects'))
		mainProjects();
	if(isAvaible('Reports'))
		mainReports();
	if(isAvaible('Settings'))
		mainSettings();

	init();
}

function saveSettings(isFormSave)
{

	if(globalSettings.islastdefaultactiveapp.value)
		globalSettings.defaultactiveapp.value=globalActiveApp;

	globalSettings.version.value=globalSettingsVersion;

	var rex = new RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)');
	if(isAvaible('CalDavZAP'))
	{
		globalSettings.activecalendarcollections.value.splice(0, globalSettings.activecalendarcollections.value.length);
		globalSettings.activetodocollections.value.splice(0, globalSettings.activetodocollections.value.length);
		globalSettings.todolistfilterselected.value.splice(0, globalSettings.todolistfilterselected.value.length);

		for(var i=0;i<globalVisibleCalDAVCollections.length;i++)
		{
			var uidParts=globalVisibleCalDAVCollections[i].match(rex)
			globalSettings.activecalendarcollections.value.splice(globalSettings.activecalendarcollections.value.length , 0, uidParts[1]+uidParts[3]);
		}

		for(var i=0;i<globalVisibleCalDAVTODOCollections.length;i++)
		{
			var uidParts=globalVisibleCalDAVTODOCollections[i].match(rex);
			globalSettings.activetodocollections.value.splice(globalSettings.activetodocollections.value.length , 0, uidParts[1]+uidParts[3]);
		}
		if(globalSettings.islastactiveview.value)
		{
			var view= $('#calendar').fullCalendar('getView');
			globalSettings.activeview.value=view.name;
		}

		if(globalSettings.islasttimezone.value)
			globalSettings.timezone.value=globalSessionTimeZone;

		var uidSelected=$('#ResourceCalDAVList').find('.resourceCalDAV_item_selected').attr('data-id');
		if(uidSelected!=undefined && uidSelected!='')
		{
			var par=uidSelected.split('/');
			globalSettings.calendarselected.value=par[par.length-3]+'/'+par[par.length-2]+'/';
		}

		uidSelected=$('#ResourceCalDAVTODOList').find('.resourceCalDAV_item_selected').attr('data-id');
		if(uidSelected!=undefined && uidSelected!='')
		{
			var par=uidSelected.split('/');
			globalSettings.todocalendarselected.value=par[par.length-3]+'/'+par[par.length-2]+'/';
		}

		var filterArray = $('.fc-filter-option-selected');
		for(var i=0; i<filterArray.length; i++)
			globalSettings.todolistfilterselected.value.splice(globalSettings.todolistfilterselected.value.length,0,$($('.fc-filter-option-selected')[i]).attr('data-type'));
	}

	if(isAvaible('CardDavMATE'))
	{
		globalSettings.activeaddressbookcollections.value.splice(0, globalSettings.activeaddressbookcollections.value.length);
		var visAddrs = dataGetChecked('#ResourceCardDAVList');
		for(var i=0;i<visAddrs.length;i++)
		{
			if(visAddrs[i]!='undefined')
			{
				var uidPart=visAddrs[i].match(RegExp('^(https?://)(.*)', 'i'))[1];
				var uidPart2= visAddrs[i].match(RegExp('^(https?://)(.*)', 'i'))[2].split('@')[2];
				globalSettings.activeaddressbookcollections.value.splice(globalSettings.activeaddressbookcollections.value.length , 0, uidPart+uidPart2);
			}
		}

		if($('#ResourceCardDAVList').find('.group.resourceCardDAV_selected').length>0)
			var uidASelected=$('#ResourceCardDAVList').find('.group.resourceCardDAV_selected').attr('data-id');
		else if($('#ResourceCardDAVList').find('.resourceCardDAV_selected').length>0)
			var uidASelected=$('#ResourceCardDAVList').find('.resourceCardDAV_selected').attr('data-id');
		else
			var uidASelected='';
		if(uidASelected!=undefined && uidASelected!='')
			globalSettings.addressbookselected.value=uidASelected;
	}
	if(isAvaible('Settings') && isFormSave)
		return applyFormSettings();
	else
		return globalSettings;
}

function loadXMLSetings(settingsXML)
{
	$(settingsXML).children().each(
	function(ind,elm)
	{
		var type = $(elm).attr('type');
		var locked = typeof $(elm).attr('locked')!='undefined'&&$(elm).attr('locked')!=null&&$(elm).attr('locked')=='true' ? true : false;
		if(typeof globalSettings[$(elm).prop('tagName').toLowerCase()] == 'undefined')
			return true;
		if(locked)
			globalSettings[$(elm).prop('tagName').toLowerCase()].locked=true;

		if($(elm).children().length>0)
		{
			globalSettings[$(elm).prop('tagName').toLowerCase()].value = new Array();
			$(elm).children().each(function(pind,pelm)
			{
				if($(elm).prop('tagName').toLowerCase() == 'urihandlerprofile')
				{
					globalSettings[$(elm).prop('tagName').toLowerCase()].value = {};
					globalSettings[$(elm).prop('tagName').toLowerCase()].value[$(pelm).text().toLowerCase()] = $(pelm).attr('url');
				}
				else if($(elm).prop('tagName').toLowerCase() == 'addresscountryequivalence')
				{
					var eqObject = {};
					eqObject['country'] = $(pelm).attr('name');
					eqObject['regex'] = $(pelm).attr('regex');
					globalSettings[$(elm).prop('tagName').toLowerCase()].value.push(eqObject);
				}
				else if($(elm).prop('tagName').toLowerCase() == 'compatibility')
				{
					globalSettings[$(elm).prop('tagName').toLowerCase()].value = {};
					globalSettings[$(elm).prop('tagName').toLowerCase()].value[$(pelm).attr('name')] = new Array();
					$(pelm).children().each(function(rind,relm)
					{
						globalSettings[$(elm).prop('tagName').toLowerCase()].value[$(pelm).attr('name')].push($(relm).text());
					});
				}
				else if($(pelm).text()!='')
				{
					switch(type)
					{
						case 'integer':
							globalSettings[$(elm).prop('tagName').toLowerCase()].value.push(parseInt($(pelm).text(),10));
							break;
						case 'string':
							if($(pelm).text()!='null')
								globalSettings[$(elm).prop('tagName').toLowerCase()].value.push($(pelm).text());
							else
								globalSettings[$(elm).prop('tagName').toLowerCase()].value.push(null);
							break;
						case 'boolean':
							if($(pelm).text() == 'true')
								globalSettings[$(elm).prop('tagName').toLowerCase()].value.push(true);
							else
								globalSettings[$(elm).prop('tagName').toLowerCase()].value.push(false);
							break;
						default:
							break;
					}
				}
			});
		}
		else if($(elm).text()!='')
		{
			switch(type)
			{
				case 'integer':
					globalSettings[$(elm).prop('tagName').toLowerCase()].value = parseInt($(elm).text(),10);
					break;
				case 'string':
					if($(elm).text()!='null')
						globalSettings[$(elm).prop('tagName').toLowerCase()].value = $(elm).text();
					else
						globalSettings[$(elm).prop('tagName').toLowerCase()].value = null;
					break;
				case 'boolean':
					if($(elm).text() == 'true')
						globalSettings[$(elm).prop('tagName').toLowerCase()].value = true;
					else if($(elm).text() == 'false')
						globalSettings[$(elm).prop('tagName').toLowerCase()].value = false;
					break;
				default:
					break;
			}
		}
	});
}

function applyServerSettings(inputSettings)
{
	if(typeof inputSettings.activecalendarcollections == 'undefined' || inputSettings.activecalendarcollections==null)
		inputSettings.activecalendarcollections = new Array();

	if(typeof inputSettings.activetodocollections == 'undefined' || inputSettings.activetodocollections==null)
		inputSettings.activetodocollections = new Array();

	if(typeof inputSettings.loadedcalendarcollections == 'undefined' || inputSettings.loadedcalendarcollections==null)
	{
		inputSettings.loadedcalendarcollections = new Array();
		if(isAvaible('CalDavZAP'))
			$('#showUnloadedCalendars').css('display','none');
	}

	if(typeof inputSettings.loadedtodocollections == 'undefined' || inputSettings.loadedtodocollections==null)
	{
		inputSettings.loadedtodocollections = new Array();
		if(isAvaible('CalDavZAP'))
			$('#showUnloadedCalendarsTODO').css('display','none');
	}
	if(typeof inputSettings.activeaddressbookcollections == 'undefined' || inputSettings.activeaddressbookcollections==null)
		inputSettings.activeaddressbookcollections = new Array();

	if(typeof inputSettings.loadedaddressbookcollections == 'undefined' || inputSettings.loadedaddressbookcollections==null)
	{
		inputSettings.loadedaddressbookcollections = new Array();
		if(isAvaible('CardDavMATE'))
			$('#showUnloadedAddressbooks').css('display','none');
	}

	transformSettings(inputSettings);

	for(var prop in inputSettings)
	{
		if(globalDefinedSettings.indexOf(prop)==-1 || (typeof globalPreviousSupportedSettings !='undefined' && globalPreviousSupportedSettings.indexOf(prop)==-1))
		{
			if(globalDefinedSettings.indexOf(prop)==-1)
				console.log('Warning: Unsupported property: \''+prop+'\' (you can safely ignore this message)');
			continue;
		}
		if(typeof globalSettings[prop] !='undefined' && !globalSettings[prop].locked)
			globalSettings[prop].value=inputSettings[prop];
	}
}

function transformSettings(settings) {
	if(!settings.version) {
		settings.version = 1;
	}

	while(settings.version<globalSettingsVersion) {
		console.log('Warning: Detected outdated server settings (version ' + settings.version++ +') - transforming to version ' + settings.version);

		switch(settings.version) {
			case 2:
				if(typeof globalActiveCalendarCollections!='undefined' && globalActiveCalendarCollections!=null)
					settings.activecalendarcollections=globalActiveCalendarCollections.slice();
				else
					settings.activecalendarcollections.splice(0, settings.activecalendarcollections.length);

				if(typeof globalActiveTodoCollections!='undefined' && globalActiveTodoCollections!=null)
					settings.activetodocollections=globalActiveTodoCollections.slice();
				else
					settings.activetodocollections.splice(0, settings.activetodocollections.length);

				if(typeof globalLoadedCalendarCollections!='undefined' && globalLoadedCalendarCollections!=null)
					settings.loadedcalendarcollections=globalLoadedCalendarCollections.slice();
				else
					settings.loadedcalendarcollections.splice(0, settings.loadedcalendarcollections.length);

				if(typeof globalLoadedTodoCollections!='undefined' && globalLoadedTodoCollections!=null)
					settings.loadedtodocollections=globalLoadedTodoCollections.slice();
				else
					settings.loadedtodocollections.splice(0, settings.loadedtodocollections.length);

				if(typeof globalActiveAddressbookCollections!='undefined' && globalActiveAddressbookCollections!=null)
					settings.activeaddressbookcollections=globalActiveAddressbookCollections.slice();
				else
					settings.activeaddressbookcollections.splice(0, settings.activeaddressbookcollections.length);

				if(typeof globalLoadedAddressbookCollections!='undefined' && globalLoadedAddressbookCollections!=null)
					settings.loadedaddressbookcollections=globalLoadedAddressbookCollections.slice();
				else
					settings.loadedaddressbookcollections.splice(0, settings.loadedaddressbookcollections.length);

				if(typeof globalContactStoreFN!='undefined' && globalContactStoreFN!=null)
					settings.contactstorefn=globalContactStoreFN.slice();
				else
					settings.contactstorefn=['prefix', ' last', ' middle', ' first', ' suffix'];
				break;
			case 3:
				settings.collectiondisplay=(typeof globalCollectionDisplay!='undefined' && globalCollectionDisplay!=null && globalCollectionDisplay!='') ? globalCollectionDisplay : (
					(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies) ?
					[{label: '{Name}', value: {company: ['{Company}', ' [{Department}]'], personal: ['{LastName}', ' {MiddleName}', ' {FirstName}']}}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}] :
					[{label: '{Name}', value: ['{LastName}', ' {MiddleName}', ' {FirstName}']}, {label: '{Company} [{Department}]', value: ['{Company}', ' [{Department}]']}, {label: '{JobTitle}', value: ['{JobTitle}']}, {label: '{Email}', value: ['{Email[:0]}']}, {label: '{Phone} 1', value: ['{Phone[:0]}']}, {label: '{Phone} 2', value: ['{Phone[:1]}']}, {label: '{NoteText}', value: ['{NoteText}']}]
				);

				settings.collectionsort=(typeof globalCollectionSort!='undefined' && globalCollectionSort!=null && globalCollectionSort!='') ? globalCollectionSort : '';
				break;
			default:
				break;
		}
	}
}

function loadSettings(strobj, fromServer, syncMode)
{
	if(settingsLoaded && !syncMode)
		return false;
	try
	{
		objNew = jQuery.parseJSON(strobj);
		if(typeof objNew=='object')
		{
			if(!syncMode && typeof globalSettingsXML!='undefined' && globalSettingsXML!=null && globalSettingsXML!='')
				loadXMLSetings($(globalSettingsXML));
			if(fromServer)
				applyServerSettings(objNew);
//			$.extend(globalSettings,objNew);
		}
	}
	catch(err)
	{
		console.log('load settings - JSON parsing error: '+err);
		delete globalSettings.version.value;
		loadSettings(JSON.stringify(globalSettings), false, false);
		return false;
	}
	if(syncMode)
		return false;
	if(isAvaible('CalDavZAP'))
	{
		for(var i=0;i<globalSettings.timezonesenabled.value.length;i++)
			if(timeZonesEnabled.indexOf(globalSettings.timezonesenabled.value[i])==-1)
				timeZonesEnabled.push(globalSettings.timezonesenabled.value[i]);

		if(globalSettings.timezonesupport.value)
		{
			globalSessionTimeZone=globalSettings.timezone.value;
				if(globalSessionTimeZone != null && timeZonesEnabled.indexOf(globalSessionTimeZone)==-1)
					timeZonesEnabled.push(globalSessionTimeZone);
		}
		else
		{
			globalSessionTimeZone = 'local';
			timeZonesEnabled.push('local');
		}

		initTimepicker(globalSettings.ampmformat.value);

		if(globalSettings.timeformatagenda.value==null)
		{
			if(globalSettings.ampmformat.value)
				globalSettings.timeformatagenda.value='h:mm TT{ - h:mm TT}';
			else
				globalSettings.timeformatagenda.value='H:mm{ - H:mm}';
		}

		if(globalSettings.timeformatbasic.value==null)
		{
			if(globalSettings.ampmformat.value)
				globalSettings.timeformatbasic.value = 'h:mmT{-h:mmT}';
			else
				globalSettings.timeformatbasic.value = 'H:mm{-H:mm}';
		}

		if(globalSettings.appleremindersmode.value)
		{
			if(globalSettings.todolistfilterselected.value.indexOf('filterAction')==-1 && globalSettings.todolistfilterselected.value.indexOf('filterCompleted')==-1)
			{
				if(globalSettings.todolistfilterselected.value.indexOf('filterProgress')!=-1)
					globalSettings.todolistfilterselected.value[globalSettings.todolistfilterselected.value.indexOf('filterProgress')] = 'filterAction';
				if(globalSettings.todolistfilterselected.value.indexOf('filterCanceled')!=-1)
					globalSettings.todolistfilterselected.value[globalSettings.todolistfilterselected.value.indexOf('filterCanceled')] = 'filterAction';
			}
		}
		if(globalSettings.eventstartfuturelimit.value == null)
		{
			var now=new Date();
			globalToLoadedLimit = new Date(now.getFullYear(), now.getMonth()+12, 1, 0, 0, 0);
			globalToLoadedLimit.setMilliseconds(0);
			globalBeginFuture = new Date(globalToLoadedLimit.getTime());
			globalBeginFuture.setDate(globalBeginFuture.getDate()+14);
			globalToLoadedLimitTodo = new Date(now.getFullYear(), now.getMonth()+12, 1, 0, 0, 0);
			globalToLoadedLimitTodo.setMilliseconds(0);
		}
		if(globalSettings.enablekbnavigation.value!==false)
			initKbTodoNavigation();
		initFullCalendar();
		initTodoList();

		$('#SystemCalDavZAP .fc-header-title').css('width', $('#main_h_placeholder').width()-$('#SystemCalDavZAP .fc-header-left').outerWidth()-$('#SystemCalDavZAP .fc-header-right').outerWidth());
		$('#ResourceCalDAVList, #ResourceCalDAVTODOList').css('bottom',(globalSettings.timezonesupport.value ? 20 : 0));
		$('#alertBox').css('left', ($(window).width()/2)-($('#alertBox').width()/2));
	}
	if(isAvaible('CardDavMATE'))
	{
		// set ABListTableLayout
		globalRefAbListTableHeader = $('#ABListTable').find('.ablist_table_header');
		var colgroups = $('#ABListTable').find('colgroup');

		for(var i=0; i<getDataColumnCount(); i++) {
			globalRefAbListTableHeader.append('<th>');
			colgroups.append('<col>');
		}

		globalRefAbListTableHeader.children().slice(globalFixedContactDataColumnsCount).each(function(ind) {
			$(this).text(getDataColumnLabelAtIndex(ind));
		});

		globalRefABListTableCols=$('#ABListTable').find('colgroup').first().children();
		globalRefABListInnerTableCols=$('#ABListTableInner').find('colgroup').children();
		$('#ABListTable').find('.ablist_table_container').children().attr('colspan', getDataColumnCount()+globalFixedContactDataColumnsCount);
		globalRefABListTable.children('.ablist_header').children().attr('colspan', getDataColumnCount()+globalFixedContactDataColumnsCount);

		if(!globalOrigABListHeader) {
			globalOrigABListHeader=globalRefABListTable.children('.ablist_header').remove();
		}
		if(!globalOrigABListItem) {
			globalOrigABListItem=globalRefABListTable.children('.ablist_item').remove();
		}

		if(globalSettings.enablekbnavigation.value!==false)
			initKbAddrNavigation();

		applyAddrSettings(globalTranslVcardTemplate);
		applyAddrSettings($('#vCardEditor'));
	}
	if(isAvaible('Projects'))
		if(globalSettings.enablekbnavigation.value!==false)
			initKbProjectNavigation();
	settingsLoaded=true;
	if(!isAvaible(globalSettings.defaultactiveapp.value))
		globalActiveApp = globalAvailableAppsArray[0];
	else
		globalActiveApp = globalSettings.defaultactiveapp.value;
}

function checkForLoadedCollections(inputSettings)
{
	var val='', triggerSync=true;
	globalLoadedCollectionsNumber=0;
	globalLoadedCollectionsCount=0;
	if(globalSettingsSaving=='event')
	{
		hideUnloadedCollections('event');
		val = inputSettings.loadedcalendarcollections.value;
		if(val.length>0)
			globalLoadedCollectionsNumber+=$(val).not(globalSettings.loadedcalendarcollections.value).length;
		else
			globalLoadedCollectionsNumber++;
		if($(globalSettings.loadedcalendarcollections.value).not(val).length>0)
		{
			if(globalLoadedCollectionsNumber==0)
			{
				triggerSync=false;
				globalFirstHideLoader=false;
			}
			var unloadArray = $(globalSettings.loadedcalendarcollections.value).not(val);
			unloadCalDAVCollection(unloadArray.toArray(),true);
		}
		if(triggerSync)
			addLoadCalDAVCollection(val, true);
		globalSettings.loadedcalendarcollections.value = val;
	}
	else if(globalSettingsSaving=='todo')
	{
		hideUnloadedCollections('todo');
		val = inputSettings.loadedtodocollections.value;
		if(val.length>0)
			globalLoadedCollectionsNumber+=$(val).not(globalSettings.loadedtodocollections.value).length;
		else
			globalLoadedCollectionsNumber++;
		if($(globalSettings.loadedtodocollections.value).not(val).length>0)
		{
			if(globalLoadedCollectionsNumber==0)
			{
				triggerSync=false;
				globalFirstHideLoader=false;
			}
			var unloadArray = $(globalSettings.loadedtodocollections.value).not(val);
			unloadCalDAVCollection(unloadArray.toArray(),false);
		}
		if(triggerSync)
			addLoadCalDAVCollection(val, false);
		globalSettings.loadedtodocollections.value = val;
	}
	else if(globalSettingsSaving=='addressbook')
	{
		hideUnloadedCardDAVCollections();
		val = inputSettings.loadedaddressbookcollections.value;
		if(val.length>0)
			globalLoadedCollectionsNumber+=$(val).not(globalSettings.loadedaddressbookcollections.value).length;
		else
			globalLoadedCollectionsNumber++;
		if($(globalSettings.loadedaddressbookcollections.value).not(val).length>0)
		{
			if(globalLoadedCollectionsNumber==0)
			{
				triggerSync=false;
				globalFirstHideLoader=false;
			}
			var unloadArray = $(globalSettings.loadedaddressbookcollections.value).not(val);
			unloadCardDAVCollection(unloadArray.toArray());
		}
		if(triggerSync)
			addLoadCardDAVCollection(val)
		globalSettings.loadedaddressbookcollections.value = val;
	}
	if(triggerSync)
		ifLoadCollections();
}

function checkBeforeClose(isFormSave)
{
	if((isAvaible('CalDavZAP') && globalCalDAVInitLoad) || (isAvaible('CardDavMATE') && globalCardDAVInitLoad))
		return false;
	var old_settings=JSON.stringify(globalSettings);
	var settings=saveSettings(isFormSave);
	var new_settings = JSON.stringify(settings);
	if(old_settings == new_settings)
		return false;
	for(var i=0;i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href.indexOf(globalLoginUsername)!=-1 && globalAccountSettings[i].settingsAccount)
		{
			netSaveSettings(globalAccountSettings[i], settings, isFormSave,false);
			break;
		}
}

function isEachResourceLoaded()
{
	var loaded = true;
	for(var i=0; i< globalAccountSettings.length; i++)
		if(typeof globalAccountSettings[i].errorLoaded!='undefined' && globalAccountSettings[i].errorLoaded!=null && globalAccountSettings[i].errorLoaded===true)
			loaded=false;
	return loaded;
}

window.onload=globalMain;

window.onkeydown=function(event)
{
	switch(event.which) {
		case 13:
			if(!isUserLogged)
				$('#Login').find('[data-type="system_login"]').trigger('click');
			break;
		case 27:
			if(globalActiveApp=='CalDavZAP' && $('#CAEvent').is(':visible') && $('#EventDisabler').is(':hidden'))
				$('#closeButton').trigger('click');
			if(globalActiveApp=='Projects' && $('#ProjectEventForm').is(':visible') && $('#ProjectsDisabler').is(':hidden'))
				$('#cancelActivity').trigger('click');
			if($('.sp-container').is(':visible'))
				$('html').trigger('click');
			break;
		default:
			break;
	}
};

var globalEventList=new EventList();
var globalAppleSupport = new AppleSupportNextDateArray();
var globalResourceCalDAVList=new ResourceCalDAVList();
var maxAlarmValue=2147000000;
var globalMultiWeekSize=3;
var globalMaxNextInstanesTodoCheckingNumber=60;

var globalEventIntervalID=null;
var globalResourceRefreshNumber=0;
var globalResourceRefreshNumberTodo=0;
var globalCalDAVInitLoad=true;
var globalCalDAVResourceSync=false;
var globalCalDAVCollectionSync=false;
var globalCalendarNumber=0;
var globalOnlyCalendarNumber=0;
var globalTodoCalendarNumber=0;
var globalOnlyCalendarNumberCount=0;
var globalOnlyTodoCalendarNumberCount=0;
var globalCalendarNumberCount=0;
var globalEventTimeoutID=0;

var cleanResourceCalDAVListTemplate=null;
var cleanResourceCalDAVTODOListTemplate=null;
var cleanVcalendarTemplate=null;
var cleanVtodoTemplate=null;
var origResourceCalDAVListTemplate=null;
var origResourceCalDAVTODOListTemplate=null;
var origVcalendarTemplate=null;
var origVtodoTemplate=null;
var origVtodoLoaderTemplate=null;
var globalSessionTimeZone=null;
var globalCalDAVQs=null;
var globalCalDAVTODOQs=null;
var globalVisibleCalDAVCollections=new Array();
var globalVisibleCalDAVTODOCollections=new Array();
var isResourceComplete=false;
var prevFunctionArray=new Array();
var prevFunctionArrayIterator=0;
var globalWorkerArray=new Array();
var globalIntervalArray=new Array();
var globalCurrentLoadingResource='';
var timeZonesEnabled=new Array();
var cLcouny=42;
var processedTimezones = Array();
var timelist=new Array();
var minelems=[0,15,30,45];
var frequencies = ["SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"];
var globalToday=new Date();
var isCalDAVLoaded=false;
var isCalDAVAvaible=true;
var globalLoadedLimit = new Date();
var globalToLoadedLimit = new Date();
var globalLimitLoading='';
var globalLimitTodoLoading='';
var globalBeginPast = new Date();
var globalBeginFuture = new Date();
var globalLoadedLimitTodo = new Date();
var globalToLoadedLimitTodo = new Date();
var globalDefaultCalendarCollectionActiveAll = false;
var globalDefaultTodoCalendarCollectionActiveAll = false;
var globalDefaultCalendarCollectionLoadAll = false;
var globalDefaultTodoCalendarCollectionLoadAll = false;
var globalTodoLoaderHide='';
var globalEventCollectionsLoading=false;
var globalTodoCollectionsLoading=false;

var globalCalEvent=null;
var globalCalTodo=null;
var globalJsEvent=null;
var globalRevertFunction=null;
var globalPrevDragEventAllDay=null;
var globalPrevDate='';
var globalAllowFcRerender=true;
var globalCalWidth=0;
var globalTodoCheckTimeout=null;
var globalTodoCheckTimeoutDelay=1000;
var globalTodolistStatusArray={};


function logoutCalDAV()
{
	globalTodolistStatusArray={};
	globalTodoCheckTimeout=null;
	globalVisibleCalDAVCollections.splice(0, globalVisibleCalDAVCollections.length);
	globalVisibleCalDAVTODOCollections.splice(0, globalVisibleCalDAVTODOCollections.length);
	processedTimezones.splice(0, processedTimezones.length);
	globalCalendarNumber=0;
	globalOnlyCalendarNumber=0;
	globalTodoCalendarNumber=0;
	globalCalendarNumberCount=0;
	globalLoadedLimit = new Date();
	globalToLoadedLimit = new Date();
	globalLimitLoading='';
	globalLimitTodoLoading='';
	globalBeginPast = new Date();
	globalBeginFuture = new Date();
	globalLoadedLimitTodo = new Date();
	globalToLoadedLimitTodo = new Date();
	globalDefaultCalendarCollectionActiveAll = false;
	globalDefaultTodoCalendarCollectionActiveAll = false;
	globalDefaultCalendarCollectionLoadAll = false;
	globalDefaultTodoCalendarCollectionLoadAll = false;
	globalCalDAVCollectionSync=false;
	globalAllowFcRerender=true;
	globalEventList.reset();
	globalResourceCalDAVList.reset();
	timeZonesEnabled.splice(0,timeZonesEnabled.length);
	if(globalEventIntervalID!=null)
		clearInterval(globalEventIntervalID);

	$('#EventDisabler, #TodoDisabler, #AlertDisabler').fadeOut(2000);
	$('#SystemCalDavZAP,  #SystemCalDavTODO').animate({opacity : 0},200).promise().done(function(){
		$('#SystemCalDavZAP, #SystemCalDavTODO').css('visibility','hidden');
		$('#main, #mainTODO').animate({top: 25}, 0);
		$('#searchForm, #searchFormTODO').hide();
		$('#searchInput, #searchInputTODO').val('').trigger('keyup').trigger('blur');
		$('#calendar').fullCalendar('destroy');
		$('#todoList').fullCalendar('destroy');
		$('#timezonePicker, #timezonePickerTODO').prop('disabled', false).empty();
		$('#eventColor, #todoColor').css('background-color','');
		if($('#ResourceCalDAVList').width()<1)
			$('#ResourceCalDAVToggle').trigger('click');
		if($('#ResourceCalDAVTODOList').width()<1)
			$('#ResourceCalDAVTODOToggle').trigger('click');
	});
}

function mainCalDAV()
{
	localizeCalDAV();
	// init();
}

function localizeCalDAV()
{
	globalCalDAVInitLoad = true;
	$('#ResourceCalDAVList').html(origResourceCalDAVListTemplate);
	$('#ResourceCalDAVTODOList').html(origResourceCalDAVTODOListTemplate);
	$('#CAEvent').html(origVcalendarTemplate);
	$('#CATodo').html(origVtodoTemplate);
	$('#todoLoader').html(origVtodoLoaderTemplate);
	translate();
	$('input[placeholder],textarea[placeholder]').placeholder();
	cleanResourceCalDAVListTemplate=$('#ResourceCalDAVListTemplate').clone().wrap('<div>').parent().html();
	cleanResourceCalDAVTODOListTemplate=$('#ResourceCalDAVTODOListTemplate').clone().wrap('<div>').parent().html();
	cleanVcalendarTemplate=$('#CAEvent .saveLoader').clone().wrap('<div>').parent().html() + $('#repeatConfirmBox').clone().wrap('<div>').parent().html() + $('#event_details_template').clone().wrap('<div>').parent().html();
	cleanVtodoTemplate=$('#repeatConfirmBoxTODO').clone().wrap('<div>').parent().html() + $('#todo_details_template').clone().wrap('<div>').parent().html();
	$('#searchInput, #searchInputTODO').val('');
	globalSettings.titleformatmonth.value = localization[globalInterfaceLanguage]._default_title_format_month_;
	globalSettings.titleformatweek.value = localization[globalInterfaceLanguage]._default_title_format_week_;
	globalSettings.titleformatday.value = localization[globalInterfaceLanguage]._default_title_format_day_;
	globalSettings.titleformattable.value = localization[globalInterfaceLanguage]._default_title_format_table_;
	globalSettings.columnformatagenda.value = localization[globalInterfaceLanguage]._default_column_format_agenda_;
}

function runCalDAV()
{
	if(!isUserLogged)
		run();

	globalResourceRefreshNumber=0;
	globalResourceRefreshNumberTodo=0;

	$('#MainLoader').css('left','0px');
	$('#MainLoader').fadeIn(200);

	if(typeof globalSubscribedCalendars!='undefined' && globalSubscribedCalendars!=null)
	{
		globalAccountSettings[globalAccountSettings.length]=$.extend({},globalAccountSettings[0]);
		globalAccountSettings[globalAccountSettings.length-1].hrefLabel = globalSubscribedCalendars.hrefLabel;
		globalAccountSettings[globalAccountSettings.length-1].calendars = globalSubscribedCalendars.calendars;
		globalAccountSettings[globalAccountSettings.length-1].ignoreAlarms = '';
	}
}

function globalMainCalDAV()
{
	$(window).resize(function(evt){
		if(evt.target!=window)
			return;

		if(typeof globalCalDAVInitLoad!='undefined' && !globalCalDAVInitLoad && !globalResourceRefreshNumber && $('#main').width()!=globalCalWidth)
			$('#CalendarLoader').children('.loaderInfo').text(localization[globalInterfaceLanguage].resizeLoader).parent().css('display','block');

		$('#SystemCalDavZAP .fc-header-title').css('width', $('#main_h_placeholder').width()-$('#SystemCalDavZAP .fc-header-left').outerWidth()-$('#SystemCalDavZAP .fc-header-right').outerWidth());
		$('#ResourceCalDAVList, #ResourceCalDAVTODOList').css('bottom',(globalSettings.timezonesupport.value ? 20 : 0));
		$('#alertBox').css('left', ($(window).width()/2)-($('#alertBox').width()/2));
		$('#calendar').fullCalendar('option', 'contentHeight', $('#main').height() - 14);
		$('#todoList').fullCalendar('allowSelectEvent',false);
		$('#todoList').fullCalendar('option', 'contentHeight', $('#mainTODO').height() - 14);
		$('#todoList').fullCalendar('allowSelectEvent',true);
		$('#todoList').fullCalendar('selectEvent', null, true);

		if($('#CATodo').is(':visible')) {
			checkTodoFormScrollBar();
		}

		if(globalSettings.displayhiddenevents.value)
		{
			hideEventCalendars();
			hideTodoCalendars();
		}
		globalCalWidth = $('#main').width();
	});

	$('#ResourceCalDAVToggle').click(function(){
		var transSpeedResource=70;
		var isResourceVisible=$('#ResourceCalDAVList').width()>1;
		var col0=isResourceVisible? 0:218;
		var col1=isResourceVisible? 0:224;
		var col2=isResourceVisible? 0:224;
		var col3=isResourceVisible? 0:225;

		if(isIntegrated)
		{
			col2+=isResourceVisible? 49:50;
			col3+=50;
		}

		if(typeof globalCalDAVInitLoad!='undefined' && !globalCalDAVInitLoad && !globalResourceRefreshNumber)
			$('#CalendarLoader').children('.loaderInfo').text(localization[globalInterfaceLanguage].resizeLoader).parent().css('display','block');

		if(globalSettings.timezonesupport.value)
			$('#timezoneWrapper').animate({width: col0}, transSpeedResource);

		$('#resourceCalDAV_h, #ResourceCalDAVList').animate({width: col1}, transSpeedResource);
		$('#CalendarLoader').animate({left: col3}, transSpeedResource);
		$('#main_h, #searchForm, #main').animate({left: col2}, transSpeedResource).promise().done(function(){
			$('#SystemCalDavZAP .fc-header-title').width($('#main_h_placeholder').width()-$('#SystemCalDavZAP .fc-header-left').width()-$('#SystemCalDavZAP .fc-header-right').width()-20);
			$(window).resize();
		});
	});

	$('#ResourceCalDAVTODOToggle').click(function(){
		var transSpeedResource=70;
		var isResourceVisible=$('#ResourceCalDAVTODOList').width()>1;
		var col0=isResourceVisible? 0:218;
		var col1=isResourceVisible? 0:224;
		var col2=isResourceVisible? 0:224;
		var col3=isResourceVisible? 0:225;

		if(isIntegrated)
		{
			col2+=isResourceVisible? 49:50;
			col3+=50;
		}

		if(globalSettings.timezonesupport.value)
			$('#timezoneWrapperTODO').animate({width: col0}, transSpeedResource);

		$('#resourceCalDAVTODO_h, #ResourceCalDAVTODOList').animate({width: col1}, transSpeedResource);
		$('#CalendarLoaderTODO').animate({left: col3}, transSpeedResource);
		$('#main_h_TODO, #searchFormTODO').animate({left: col2}, transSpeedResource);
		$('#mainTODO').animate({left: col2}, transSpeedResource, function(){
			$('#todoList').fullCalendar('allowSelectEvent',false);
			$(window).resize();
			$('#todoList').fullCalendar('allowSelectEvent',true);
			$('#todoList').fullCalendar('selectEvent', null, true);
		});
	});

	$('#eventFormShowerTODO').click(function(){
			showNewEvent('TODO');
	});

	$('#eventFormShower').click(function(){
		showNewEvent('');
	});

	$('#searchInput').bind('keyup change', function(){
		if($(this).val()!='')
			$('#reserButton').css('visibility', 'visible');
		else
			$('#reserButton').css('visibility', 'hidden');
	});

	$('#searchInputTODO').bind('keyup change', function(){
		if($(this).val()!='')
			$('#resetButtonTODO').css('visibility', 'visible');
		else
			$('#resetButtonTODO').css('visibility', 'hidden');
	});

	$('#timezonePicker, #timezonePickerTODO').change(function(){
		var previousTimezone=globalSessionTimeZone;
		globalSessionTimeZone=$(this).val();
		$('#timezonePicker').val($(this).val());
		$('#timezonePickerTODO').val($(this).val());
		applyTimezone(previousTimezone);
	});

	/*************************** BAD HACKS SECTION ***************************/
	if($.browser.msie || $.browser.mozilla)
	{
		var newSVG=$(SVG_select_b).attr('data-type', 'select_icon').css({'pointer-events': 'none', 'z-index': '1', 'display': 'inline', 'margin-left': '-19px', 'vertical-align': 'top', 'background-color': '#ffffff'});	// background-color = stupid IE9 bug
		$('#timezoneWrapper, #timezoneWrapperTODO').find('select').after($($('<div>').append($(newSVG).clone()).html()));
	}
	// INFO LABEL ALIGN WITH UNDELYING SELECT FIX
	if($.browser.webkit && !!$.browser.safari)
		$('.infoSpan[data-type="txt_interval"]').css('padding-left', '3px');
	/*************************** END OF BAD HACKS SECTION ***************************/

	globalCalWidth = $('#main').width();
	origResourceCalDAVListTemplate = $('#ResourceCalDAVListTemplate').clone().wrap('<div>').parent().html();
	origResourceCalDAVTODOListTemplate = $('#ResourceCalDAVTODOListTemplate').clone().wrap('<div>').parent().html();
	origVcalendarTemplate = $('#CAEvent .saveLoader').clone().wrap('<div>').parent().html() + $('#repeatConfirmBox').clone().wrap('<div>').parent().html() + $('#event_details_template').clone().wrap('<div>').parent().html();
	origVtodoTemplate = $('#repeatConfirmBoxTODO').clone().wrap('<div>').parent().html() + $('#todo_details_template').clone().wrap('<div>').parent().html();
	origVtodoLoaderTemplate=$('#todoLoader .saveLoader').clone().wrap('<div>').parent().html();

	populateTimezoneKeys();
}

function setCalendarNumber(initSearch)
{
	/*if($('.resourceCalDAV_header:visible').length>1 || (!$('.resourceCalDAV_header:visible').length  && $('.resourceCalDAV_item:visible').length>1))
		$('.addRemoveAllCalDAV').show();
	if($('.resourceCalDAVTODO_header:visible').length>1 || (!$('.resourceCalDAVTODO_header:visible').length  && $('.resourceCalDAVTODO_item:visible').length>1))
		$('.addRemoveAllCalDAVTODO').show();*/
	if(initSearch)
		initSearchEngine();

	globalCalendarNumber=0;
	globalOnlyCalendarNumber=0;
	globalTodoCalendarNumber=0;
	for(var i=0; i<globalResourceCalDAVList.collections.length;i++)
		if(globalResourceCalDAVList.collections[i].uid!=undefined && globalResourceCalDAVList.collections[i].makeLoaded)
		{
			globalCalendarNumber++;
			globalOnlyCalendarNumber++;
		}
	for(var i=0; i<globalResourceCalDAVList.TodoCollections.length;i++)
		if(globalResourceCalDAVList.TodoCollections[i].uid!=undefined && globalResourceCalDAVList.TodoCollections[i].makeLoaded)
		{
			globalCalendarNumber++;
			globalTodoCalendarNumber++;
		}
}
var globalAddressbookList=new AddressbookList();
var globalResourceCardDAVList=new ResourceCardDAVList();
var globalQs=null;

var globalRefABList=null;
var globalRefABListTable=null;
var globalRefAbListTableHeader=null;
var globalRefABListTableCols=null;
var globalRefABListInnerTableCols=null;
var globalRefAddContact=null;
var globalRefVcardEditor=null;				// editor reference stored after each editor cleanup

var globalOrigCardDAVListTemplate=null;		// template for clean resource list
var globalOrigABListHeader=null;			// template for clean addressbook header
var globalOrigABListItem=null;				// template for clean addressbook item
var globalOrigVcardTemplate=null;			// template for clean editor object

var globalTranslCardDAVListTemplate=null;	// template for translated resource list
var globalTranslCardDAVListHeader=null;		// template for translated resource header
var globalTranslCardDAVListItem=null;		// template for translated resource item

var globalTranslVcardTemplate=null;			// template for translated editor object

var globalCardDAVInitLoad=true;
var globalCardDAVResourceSync=false;
var globalCardDAVCollectionSync=false;
var isCardDAVLoaded=false;
var isCardDAVAvaible=true;
var globalDefaultAddressbookCollectionActiveAll=false;
var globalDefaultAddrCollectionLoadAll=false;
var globalAddressbookNumber=0;
var globalAddressbookNumberCount=0;
var globalABEditorCounter=new Object();
var globalAddressElementOldData=new Object();
var globalAddressbookCollectionsLoading=false;
var globalDisableAnimationMessageHiding='';

if(typeof globalContactPhotoScaleFactor==='undefined')
	var globalContactPhotoScaleFactor=1.5;

var globalFixedContactDataColumnsCount = 1;
var globalContactDataColumnDefs = {
	'CATEGORIES': {
		'property': 'cats',
		'minWidth': 90
	},
	'COMPANY': {
		'property': 'company',
		'minWidth': 135
	},
	'DEPARTMENT': {
		'property': 'department',
		'minWidth': 90
	},
	'LASTNAME': {
		'property': 'lastname',
		'minWidth': 90
	},
	'FIRSTNAME': {
		'property': 'firstname',
		'minWidth': 45
	},
	'MIDDLENAME': {
		'property': 'middlename',
		'minWidth': 45
	},
	'PREFIX': {
		'property': 'prefix',
		'minWidth': 27
	},
	'SUFFIX': {
		'property': 'sufix',
		'minWidth': 27
	},
	'NICKNAME': {
		'property': 'nickname',
		'minWidth': 45
	},
	'PHONETICLASTNAME': {
		'property': 'phoneticLastName',
		'minWidth': 90
	},
	'PHONETICFIRSTNAME': {
		'property': 'phoneticFirstName',
		'minWidth': 45
	},
	'BIRTHDAY': {
		'property': 'birthday',
		'minWidth': 90
	},
	'JOBTITLE': {
		'property': 'title',
		'minWidth': 90
	},
	'NOTETEXT': {
		'property': 'note',
		'minWidth': 180
	},
	'ADDRESS': {
		'property': 'address',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 180
	},
	'PHONE': {
		'property': 'phone',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 90
	},
	'EMAIL': {
		'property': 'email',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 135
	},
	'URL': {
		'property': 'url',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 135
	},
	'DATES': {
		'property': 'date',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 90
	},
	'RELATED': {
		'property': 'related',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 45
	},
	'PROFILE': {
		'property': 'social',
		'filterProperities': {
			'TYPE': 'type'
		},
		'minWidth': 90
	},
	'IM': {
		'property': 'impp',
		'filterProperities': {
			'TYPE': 'type',
			'SERVICE-TYPE': 'serviceType'
		},
		'minWidth': 90
	}
};

globalContactDataColumnLabelVars = {
	'Name': 'txtName',

	'FirstName': 'pholderGiven',
	'LastName': 'pholderFamily',
	'MiddleName': 'pholderMiddle',
	'NickName': 'pholderNickname',
	'Prefix': 'pholderPrefix',
	'Suffix': 'pholderSuffix',
	'BirthDay': 'pholderBday',
	'PhoneticLastName': 'pholderPhFamily',
	'PhoneticFirstName': 'pholderPhGiven',
	'JobTitle': 'pholderTitle',
	'Company': 'pholderOrg',
	'Department': 'pholderDepartment',
	'Categories': 'txtCategories',
	'NoteText': 'pholderNoteVal',

	'Address': 'txtAddress',
	'AddressWork': 'txtAddressWork',
	'AddressHome': 'txtAddressHome',
	'AddressOther': 'txtAddressOther',

	'Phone': 'txtPhone',
	'PhoneWork': 'txtPhoneWork',
	'PhoneHome': 'txtPhoneHome',
	'PhoneCell': 'txtPhoneCell',
	'PhoneMain': 'txtPhoneMain',
	'PhonePager': 'txtPhonePager',
	'PhoneFax': 'txtPhoneFax',
	'PhoneIphone': 'txtPhoneIphone',
	'PhoneOther': 'txtPhoneOther',

	'Email': 'txtEmail',
	'EmailWork': 'txtEmailWork',
	'EmailHome': 'txtEmailHome',
	'EmailMobileme': 'txtEmailMobileme',
	'EmailOther': 'txtEmailOther',

	'URL': 'txtUrl',
	'URLWork': 'txtUrlWork',
	'URLHome': 'txtUrlHome',
	'URLHomepage': 'txtUrlHomepage',
	'URLOther': 'txtUrlOther',

	'Dates': 'txtDates',
	'DatesAnniversary': 'txtDatesAnniversary',
	'DatesOther': 'txtDatesOther',

	'Related': 'txtRelated',
	'RelatedManager': 'txtRelatedManager',
	'RelatedAssistant': 'txtRelatedAssistant',
	'RelatedFather': 'txtRelatedFather',
	'RelatedMother': 'txtRelatedMother',
	'RelatedParent': 'txtRelatedParent',
	'RelatedBrother': 'txtRelatedBrother',
	'RelatedSister': 'txtRelatedSister',
	'RelatedChild': 'txtRelatedChild',
	'RelatedFriend': 'txtRelatedFriend',
	'RelatedSpouse': 'txtRelatedSpouse',
	'RelatedPartner': 'txtRelatedPartner',
	'RelatedOther': 'txtRelatedOther',

	'Profile': 'txtProfile',
	'ProfileTwitter': 'txtProfileTwitter',
	'ProfileFacebook': 'txtProfileFacebook',
	'ProfileFlickr': 'txtProfileFlickr',
	'ProfileLinkedin': 'txtProfileLinkedin',
	'ProfileMyspace': 'txtProfileMyspace',
	'ProfileSinaweibo': 'txtProfileSinaweibo',

	'IM': 'txtIm',
	'IMWork': 'txtImWork',
	'IMHome': 'txtImHome',
	'IMMobileme': 'txtImMobileme',
	'IMOther': 'txtImOther',
	'IMAim': 'txtImProtAim',
	'IMIcq': 'txtImProtIcq',
	'IMIrc': 'txtImProtIrc',
	'IMJabber': 'txtImProtJabber',
	'IMMsn': 'txtImProtMsn',
	'IMYahoo': 'txtImProtYahoo',
	'IMFacebook': 'txtImProtFacebook',
	'IMGadugadu': 'txtImProtGadugadu',
	'IMGoogletalk': 'txtImProtGoogletalk',
	'IMQq': 'txtImProtQq',
	'IMSkype': 'txtImProtSkype'
};


// called only once (after tha page is loaded)
function globalMainCardDAV()
{
	$(window).resize(function(evt){
		if(evt.target!=window)
			return;

		var columnLengths = [];
		for(var i=0; i<getDataColumnCount(); i++) {
			columnLengths.push([]);
		}

		globalRefABListTable.children('.ablist_item:visible').each(function() {
			$(this).children().slice(globalFixedContactDataColumnsCount).each(function(ind) {
				columnLengths[ind].push($(this).text().length);
			});
		});

		setDataColumnsWidth(columnLengths);

		$('.ablist_table_wrapper').css('max-height', $('#ABList').innerHeight() - $('.ablist_table_header').outerHeight() - 1);
		checkContactFormScrollBar();
	});

	// set the initial height to get vertical scrollbars working (used also in $(window).resize(...))
	$('.ablist_table_wrapper').css('max-height', $('#ABList').innerHeight() - $('.ablist_table_header').outerHeight() - 1);

	// toggle CardDAV resources
	$('#ResourceCardDAVToggle').click(function(){
		var transSpeedResource=70;
		var isResourceVisible=$('#ResourceCardDAVList').width()>1;
		var col1=isResourceVisible? 0:224;
		var col2=isResourceVisible? 0:225;

		if(isIntegrated)
		{
			col2+=50;
		}

		$('.resourcesCardDAV_d, #ResourceCardDAVList, #ResourceCardDAVListOverlay').animate({width: col1}, transSpeedResource);
		$('.collection_d, #SearchBox, #ABList, #ABListOverlay, #AddressbookOverlay').animate({left: col2}, transSpeedResource);
	});

	globalRefABList=$('#ABList');
	globalRefABListTable=$('#ABListTableInner').find('tbody');
	globalRefAddContact=$('#AddContact');

	// these are restored after each logout
	globalOrigCardDAVListTemplate=$('#ResourceCardDAVListTemplate').clone();

	// clone + cleanup the editor (autocomplete bug in some browsers) + store the reference in globalOrigVcardTemplate
	var tmp=$('#vCardTemplate').clone();
	tmp.find('input[type="text"]').val('');
	tmp.find('textarea').text('');
	globalOrigVcardTemplate=tmp;
}

// called after the page is loaded and after each logout
function mainCardDAV()
{
	globalCardDAVInitLoad=true;

	// localize templates
	//  + store translated templates (globalTranl*)
	//  + initialize placeholder plugin
	localizeCardDAV();

	// cleanup the search field
	$('[data-type="search"]').val('');

	// Switch back to global Init (check for supported browser, demo login & password autofill
	//  then performs loadConfig() /netCheckAndCreateConfiguration() or netLoadConfiguration() or loadAllResources()/
	// init();
}

// POZOR! login vola priamo loadConfig() ... nie je tym nahodou predxadzajuca funkcia zbytocna? ... overit!

// called from loadConfig() and netCheckAndCreateConfiguration() and netLoadConfiguration() and DAVresourceDelegation()
function runCardDAV()
{
	if(!isUserLogged)
		run();

//	$('#SystemCardDavMATE').animate({opacity : 1},200,function(){
//		/* XXX - System display:none changes
//		$('#SystemCardDavMATE').css('display','block'); */
//		$('#SystemCardDavMATE').css('visibility','visible');
//	});

	$('#MainLoader').css('left','0px');
	$('#MainLoader').fadeIn(200);
	initSearchCardDav();
}

function logoutCardDAV()
{
	globalAddressbookList.reset();
	globalResourceCardDAVList.reset();
	globalAddressbookNumber=0;
	globalAddressbookNumberCount=0;
	globalCardDAVCollectionSync=false;
	globalDefaultAddressbookCollectionActiveAll=false;
	globalDefaultAddrCollectionLoadAll=false;
	globalDisableAnimationMessageHiding='';

	// reset ABList
	globalRefABListTable.empty();

	// remove ABList table gutter
	$('.ablist_table_gutter').remove();

	// clear old ABList table column widths
	globalRefABListTableCols.width('');
	globalRefABListInnerTableCols.width('');

	// reset ABList table layout
	globalRefAbListTableHeader.children().slice(globalFixedContactDataColumnsCount).remove();
	globalRefABListTableCols.slice(globalFixedContactDataColumnsCount).remove();
	globalRefABListInnerTableCols.slice(globalFixedContactDataColumnsCount).remove();
	globalRefAbListTableHeader=null;
	globalRefABListTableCols=null;
	globalRefABListInnerTableCols=null;

	// hide update notification
	$('#SystemCardDavMATE').find('div.update_d').hide();

	// if the editor is in "edit" state during the logout,
	//  we need to remove all overlays (for next login)
	$('#ResourceCardDAVListOverlay, #ABListOverlay').fadeOut(2000);
	$('#SystemCardDavMATE').animate({opacity : 0},200,function(){
		/* XXX - System display:none changes
		$('#SystemCardDavMATE').css('display','none');*/
		$('#SystemCardDavMATE').css('visibility', 'hidden');
		$('#ABContactColor').css('background-color', '');
		if($('#ResourceCardDAVList').width()<1)
			$('#ResourceCardDAVToggle').trigger('click');
	});
}

function setAddressbookNumber()
{
	for(var i=0; i<globalResourceCardDAVList.collections.length;i++)
		if(globalResourceCardDAVList.collections[i].uid!=undefined && globalResourceCardDAVList.collections[i].makeLoaded)
			globalAddressbookNumber++;
}